Changeset 4cefac0
- Timestamp:
- Feb 23, 2015, 10:15:02 PM (8 years ago)
- Branches:
- master
- Children:
- 0ebef4e
- Parents:
- 63901be
- Files:
-
- 5 added
- 19 edited
Legend:
- Unmodified
- Added
- Removed
-
common/core.common.php
r63901be r4cefac0 24 24 25 25 /// Автозагрузка общих классов для ядра и cli 26 function common_autoload($class_name){ 27 global $CONFIG; 28 $class_name = strtolower($class_name); 29 $class_name = str_replace('\\', '/', $class_name); 30 @include_once $CONFIG['location']."/common/".$class_name.'.php'; 31 } 26 function common_autoload($class_name) { 27 global $CONFIG; 28 $class_name = strtolower($class_name); 29 $class_name = str_replace('\\', '/', $class_name); 30 @include_once $CONFIG['location'] . "/common/" . $class_name . '.php'; 31 } 32 32 33 spl_autoload_register('common_autoload'); 33 34 … … 37 38 /// @param msg Тело сообщения 38 39 /// @param from Адрес отправителя 39 function mailto($email, $subject, $msg, $from="") { 40 global $CONFIG; 41 require_once($CONFIG['location'].'/common/email_message.php'); 42 43 $email_message=new email_message_class(); 44 $email_message->default_charset="UTF-8"; 45 $email_message->SetEncodedEmailHeader("To", $email, $email); 46 $email_message->SetEncodedHeader("Subject", $subject); 47 if($from) $email_message->SetEncodedEmailHeader("From", $from, $from); 48 else $email_message->SetEncodedEmailHeader("From", $CONFIG['site']['admin_email'], "Почтовый робот {$CONFIG['site']['display_name']}"); 49 $email_message->SetHeader("Sender",$CONFIG['site']['admin_email']); 50 $email_message->SetHeader("X-Multimag-version", MULTIMAG_VERSION); 51 $email_message->AddQuotedPrintableTextPart($msg); 52 $error=$email_message->Send(); 53 54 if(strcmp($error,"")) throw new Exception($error); 55 else return 0; 40 function mailto($email, $subject, $msg, $from = "") { 41 global $CONFIG; 42 require_once($CONFIG['location'] . '/common/email_message.php'); 43 44 $email_message = new email_message_class(); 45 $email_message->default_charset = "UTF-8"; 46 $email_message->SetEncodedEmailHeader("To", $email, $email); 47 $email_message->SetEncodedHeader("Subject", $subject); 48 if ($from) { 49 $email_message->SetEncodedEmailHeader("From", $from, $from); 50 } else { 51 $email_message->SetEncodedEmailHeader("From", $CONFIG['site']['admin_email'], "Почтовый робот {$CONFIG['site']['display_name']}"); 52 } 53 $email_message->SetHeader("Sender", $CONFIG['site']['admin_email']); 54 $email_message->SetHeader("X-Multimag-version", MULTIMAG_VERSION); 55 $email_message->AddQuotedPrintableTextPart($msg); 56 $error = $email_message->Send(); 57 58 if (strcmp($error, "")) { 59 throw new Exception($error); 60 } 61 return 0; 56 62 } 57 63 … … 59 65 /// @param times - время в секундах 60 66 function sectostrinterval($times) { 61 $ret=($times%60).' с.'; 62 $times=round($times/60); 63 if(!$times) return $ret; 64 $ret=($times%60).' м. '.$ret; 65 $times=round($times/60); 66 if(!$times) return $ret; 67 $ret=$times.' ч. '.$ret; 68 return $ret; 67 $ret = ($times % 60) . ' с.'; 68 $times = round($times / 60); 69 if (!$times) { 70 return $ret; 71 } 72 $ret = ($times % 60) . ' м. ' . $ret; 73 $times = round($times / 60); 74 if (!$times) { 75 return $ret; 76 } 77 $ret = $times . ' ч. ' . $ret; 78 return $ret; 69 79 } 70 80 … … 72 82 /// @param date произвольное время в UNIXTIME формате 73 83 function date_day($date) { 74 $ee=date("d M Y 00:00:00",$date);75 $tm=strtotime($ee);76 return $tm;84 $ee = date("d M Y 00:00:00", $date); 85 $tm = strtotime($ee); 86 return $tm; 77 87 } 78 88 … … 84 94 /// @param $date Дата, на которую расчитывается долг 85 95 function agentCalcDebt($agent_id, $no_cache = 0, $firm_id = 0, $local_db = 0, $date = 0) { 86 global $tmpl, $db, $doc_agent_dolg_cache_storage; 87 //if(!$no_cache && isset($doc_agent_dolg_cache_storage[$agent_id])) return $doc_agent_dolg_cache_storage[$agent_id]; 88 settype($agent_id,'int'); 89 settype($firm_id,'int'); 90 settype($date,'int'); 91 $dolg=0; 92 $query = "SELECT `type`, `sum` FROM `doc_list` WHERE `ok`>'0' AND `agent`='$agent_id' AND `mark_del`='0'"; 93 if($firm_id) 94 $query .= " AND `firm_id`='$firm_id'"; 95 if($date) 96 $query .= " AND `date`<=$date"; 97 if($local_db) 98 $res = $local_db->query($query); 99 else $res = $db->query($query); 100 while($nxt=$res->fetch_row()) { 101 switch($nxt[0]) { 102 case 1: $dolg-=$nxt[1]; break; 103 case 2: $dolg+=$nxt[1]; break; 104 case 4: $dolg-=$nxt[1]; break; 105 case 5: $dolg+=$nxt[1]; break; 106 case 6: $dolg-=$nxt[1]; break; 107 case 7: $dolg+=$nxt[1]; break; 108 case 18: $dolg+=$nxt[1]; break; 109 } 110 } 111 $res->free(); 112 $dolg = sprintf("%0.2f", $dolg); 113 //$doc_agent_dolg_cache_storage[$agent_id]=$dolg; 114 return $dolg; 96 global $db;//, $doc_agent_dolg_cache_storage; 97 //if(!$no_cache && isset($doc_agent_dolg_cache_storage[$agent_id])) return $doc_agent_dolg_cache_storage[$agent_id]; 98 settype($agent_id, 'int'); 99 settype($firm_id, 'int'); 100 settype($date, 'int'); 101 $dolg = 0; 102 $query = "SELECT `type`, `sum` FROM `doc_list` WHERE `ok`>'0' AND `agent`='$agent_id' AND `mark_del`='0'"; 103 if ($firm_id) { 104 $query .= " AND `firm_id`='$firm_id'"; 105 } 106 if ($date) { 107 $query .= " AND `date`<=$date"; 108 } 109 if ($local_db) { 110 $res = $local_db->query($query); 111 } else { 112 $res = $db->query($query); 113 } 114 while ($nxt = $res->fetch_row()) { 115 switch ($nxt[0]) { 116 case 1: $dolg-=$nxt[1]; 117 break; 118 case 2: $dolg+=$nxt[1]; 119 break; 120 case 4: $dolg-=$nxt[1]; 121 break; 122 case 5: $dolg+=$nxt[1]; 123 break; 124 case 6: $dolg-=$nxt[1]; 125 break; 126 case 7: $dolg+=$nxt[1]; 127 break; 128 case 18: $dolg+=$nxt[1]; 129 break; 130 } 131 } 132 $res->free(); 133 $dolg = sprintf("%0.2f", $dolg); 134 //$doc_agent_dolg_cache_storage[$agent_id]=$dolg; 135 return $dolg; 115 136 } 116 137 … … 166 187 /// Т.к. используется почти везде, нет смысла выносить в отдельный файл 167 188 class MysqiExtended extends mysqli { 168 169 170 function startTransaction(){171 172 173 174 189 190 /// Начать транзакцию 191 function startTransaction() { 192 return $this->query("START TRANSACTION"); 193 } 194 195 // FOR DEBUG ! 175 196 // function query($query) { 176 197 // echo $query." <hr>\n"; 177 198 // return parent::query($query); 178 199 // } 179 180 /// Получить все значения строки из таблицы по ключу в виде массива 181 /// @param $table Имя таблицы 182 /// @param $key_value Значение ключа, по которому производится выборка. Будет приведено к целому типу. 183 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае sql ошибки вернёт false. В случае, если искомой строки нет в таблице, вернет 0 184 function selectRow($table, $key_value) { 185 settype($key_value,'int'); 186 $res=$this->query('SELECT * FROM `'.$table.'` WHERE `id`='.$key_value); 187 if(!$res) return false; 188 if(!$res->num_rows) return 0; 189 return $res->fetch_assoc(); 190 } 191 192 /// Получить все значения строки из таблицы по ключу в виде массива 193 /// @param table Имя таблицы 194 /// @param key_name Имя ключа, по которому производится выборка. 195 /// @param key_value Значение ключа, по которому производится выборка. 196 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае sql ошибки вернёт false. В случае, если искомой строки нет в таблице, вернет 0 197 function selectRowK($table, $key_name, $key_value) { 198 $key_value = $this->real_escape_string($key_value); 199 $res=$this->query('SELECT * FROM `'.$table.'` WHERE `'.$key_name.'`=\''.$key_value.'\''); 200 if(!$res) return false; 201 if(!$res->num_rows) return 0; 202 return $res->fetch_assoc(); 203 } 204 205 /// Получить заданные значения строки из таблицы по ключу в виде массива 206 /// @param table Имя таблицы 207 /// @param key_value Значение ключа, по которому производится выборка. Будет приведено к целому типу. 208 /// @param array Массив со значениями, содержащими имена полей 209 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае, если искомой строки нет в таблице, вернет массив со значениями, равными '' 210 function selectRowA($table, $key_value, $array) { 211 settype($key_value,'int'); 212 $q=$f=''; 213 foreach($array as $value) { 214 if($f) $q.=',`'.$value.'`'; 215 else { $q='`'.$value.'`'; $f=1;} 216 } 217 $res = $this->query('SELECT '.$q.' FROM `'.$table.'` WHERE `id`='.$key_value); 218 if(!$res->num_rows){ 219 $info = array(); 220 foreach ($array as $value) 221 $info[$value] = ''; 222 return $info; 223 } 224 return $res->fetch_assoc(); 225 } 226 227 /// Получить заданные значения строки из таблицы по ключу в виде массива 228 /// @param table Имя таблицы 229 /// @param key_value Значение ключа, по которому производится выборка. Будет приведено к целому типу. 230 /// @param array Массив с ключами, содержащими имена полей 231 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае, если искомой строки нет в таблице, вернет исходный массив 232 function selectRowAi($table, $key_value, $array) { 233 settype($key_value,'int'); 234 $q=$f=''; 235 foreach($array as $key => $value) { 236 if($f) $q.=',`'.$key.'`'; 237 else { $q='`'.$key.'`'; $f=1;} 238 } 239 $res=$this->query('SELECT '.$q.' FROM `'.$table.'` WHERE `id`='.$key_value); 240 if(!$res->num_rows) return $array; 241 return $res->fetch_assoc(); 242 } 243 244 /// Получить значения столбца из таблицы структуры ключ/param/value по ключу в виде массива 245 /// @param table Имя таблицы 246 /// @param key_value Значение ключа, по которому производится выборка. Будет приведено к целому типу. 247 /// @param array Массив со значениями, содержащими имена полей 248 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае sql ошибки вернёт false. В случае, если искомого значения нет в таблице, вернет пустую строку для такого значения 249 function selectFieldKA($table, $key_name, $key_value, $array) { 250 settype($key_value,'int'); 251 $a=array_fill_keys($array, ''); 252 $res=$this->query('SELECT `param`, `value` FROM `'.$table.'` WHERE `'.$key_name.'`='.$key_value); 253 if(!$res) return false; 254 while($line=$res->fetch_row()) 255 { 256 if(array_key_exists($line[0], $a)) 257 $a[$line[0]]=$line[1]; 258 } 259 return $a; 260 } 261 262 /// Вставить строку в заданную таблицу 263 /// @param table Имя таблицы 264 /// @param array Ассоциативный массив вставляемых данных 265 /// @return id вставленной строки или false в случае ошибки 266 function insertA($table, $array) { 267 $cols=$values=''; 268 $f=0; 269 foreach($array as $key=>$value){ 270 if($value!=='NULL') 271 $value = '\''.$this->real_escape_string($value).'\''; 272 if(!$f){ 273 $cols = '`'.$key.'`'; 274 $values = $value; 275 $f=1; 276 } 277 else { 278 $cols .= ', `'.$key.'`'; 279 $values .= ', '.$value; 280 } 281 } 282 if(!$this->query("INSERT INTO `$table` ($cols) VALUES ($values)")) 283 return false; 284 return $this->insert_id; 285 } 286 287 288 /// Обновить данные в заданной таблице 289 /// @param table Имя таблицы 290 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 291 /// @param field Название поля таблицы 292 /// @param value Новое значение поля таблицы. Автоматически экранируется. 293 /// @return Возвращаемое значение аналогично mysqli::query 294 function update($table, $key_value, $field, $value){ 295 settype($key_value,'int'); 296 if ($value !== 'NULL') { 297 $value = '\'' . $this->real_escape_string($value) . '\''; 298 } 299 return $this->query("UPDATE `$table` SET `$field`=$value WHERE `id`=$key_value"); 300 } 301 302 /// Обновить данные в заданной таблице данными из массива по ключу с именем id 303 /// @param table Имя таблицы 304 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 305 /// @param array Ассоциативный массив ключ/значение для обновления. Значения автоматически экранируется. 306 /// @return Возвращаемое значение аналогично mysql::query 307 function updateA($table, $key_value, $array){ 308 settype($key_value,'int'); 309 $q=$this->updatePrepare($array); 310 return $this->query("UPDATE `$table` SET $q WHERE `id`=$key_value"); 311 } 312 313 /// Обновить данные в заданной таблице данными из массива по ключу с заданным именем 314 /// @param table Имя таблицы 315 /// @param key_name Имя ключа таблицы 316 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 317 /// @param array Ассоциативный массив ключ/значение для обновления. Значения автоматически экранируется. 318 /// @return Возвращаемое значение аналогично mysqli::query 319 function updateKA($table, $key_name, $key_value, $array) { 320 settype($key_value,'int'); 321 $key_name = $this->real_escape_string($key_name); 322 $q=$this->updatePrepare($array); 323 return $this->query("UPDATE `$table` SET $q WHERE `$key_name`=$key_value"); 324 } 325 326 /// Заменить данные в заданной таблице данными из массива по ключу с заданным именем 327 /// @param table Имя таблицы 328 /// @param key_name Имя ключа таблицы 329 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 330 /// @param array Ассоциативный массив ключ/значение для обновления. Значения автоматически экранируется. 331 /// @return Возвращаемое значение аналогично mysqli::query 332 function replaceKA($table, $key_name, $key_value, $array) { 333 settype($key_value,'int'); 334 $q=$f=''; 335 foreach($array as $key => $value) { 336 if($value!=='NULL') 337 $value = '\''.$this->real_escape_string($value).'\''; 338 if($f) $q.=',(\''.$key_value.'\',\''.$key.'\','.$value.')'; 339 else { $q='(\''.$key_value.'\',\''.$key.'\','.$value.')'; $f=1;} 340 } 341 return $this->query('REPLACE `'.$table.'` (`'.$key_name.'`, `param`, `value`) VALUES '.$q); 342 } 343 344 /// Удалить из заданной тоаблицы строку с указанным id 345 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 346 public function delete($table, $key_value) { 347 settype($key_value,'int'); 348 return $this->query('DELETE FROM `'.$table.'` WHERE `id`='.$key_value); 349 } 350 351 /// Подготавливает данные для update запросов 352 /// @param array Ассоциативный массив ключ/значение для обновления. Значения автоматически экранируется. 353 private function updatePrepare($array) { 354 $q=$f=''; 355 foreach($array as $key => $value) { 356 if($value!=='NULL' && $value!=='null') 357 $value = '\''.$this->real_escape_string($value).'\''; 358 if($f) $q.=',`'.$key.'`='.$value; 359 else { $q='`'.$key.'`='.$value; $f=1;} 360 } 361 return $q; 362 } 363 } 200 201 /// Получить все значения строки из таблицы по ключу в виде массива 202 /// @param $table Имя таблицы 203 /// @param $key_value Значение ключа, по которому производится выборка. Будет приведено к целому типу. 204 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае sql ошибки вернёт false. В случае, если искомой строки нет в таблице, вернет 0 205 function selectRow($table, $key_value) { 206 settype($key_value, 'int'); 207 $res = $this->query('SELECT * FROM `' . $table . '` WHERE `id`=' . $key_value); 208 if (!$res) { 209 return false; 210 } 211 if (!$res->num_rows) { 212 return 0; 213 } 214 return $res->fetch_assoc(); 215 } 216 217 /// Получить все значения строки из таблицы по ключу в виде массива 218 /// @param table Имя таблицы 219 /// @param key_name Имя ключа, по которому производится выборка. 220 /// @param key_value Значение ключа, по которому производится выборка. 221 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае sql ошибки вернёт false. В случае, если искомой строки нет в таблице, вернет 0 222 function selectRowK($table, $key_name, $key_value) { 223 $key_value = $this->real_escape_string($key_value); 224 $res = $this->query('SELECT * FROM `' . $table . '` WHERE `' . $key_name . '`=\'' . $key_value . '\''); 225 if (!$res) { 226 return false; 227 } 228 if (!$res->num_rows) { 229 return 0; 230 } 231 return $res->fetch_assoc(); 232 } 233 234 /// Получить заданные значения строки из таблицы по ключу в виде массива 235 /// @param table Имя таблицы 236 /// @param key_value Значение ключа, по которому производится выборка. Будет приведено к целому типу. 237 /// @param array Массив со значениями, содержащими имена полей 238 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае, если искомой строки нет в таблице, вернет массив со значениями, равными '' 239 function selectRowA($table, $key_value, $array) { 240 settype($key_value, 'int'); 241 $q = $f = ''; 242 foreach ($array as $value) { 243 if ($f) { 244 $q.=',`' . $value . '`'; 245 } else { 246 $q = '`' . $value . '`'; 247 $f = 1; 248 } 249 } 250 $res = $this->query('SELECT ' . $q . ' FROM `' . $table . '` WHERE `id`=' . $key_value); 251 if (!$res->num_rows) { 252 $info = array(); 253 foreach ($array as $value) { 254 $info[$value] = ''; 255 } 256 return $info; 257 } 258 return $res->fetch_assoc(); 259 } 260 261 /// Получить заданные значения строки из таблицы по ключу в виде массива 262 /// @param table Имя таблицы 263 /// @param key_value Значение ключа, по которому производится выборка. Будет приведено к целому типу. 264 /// @param array Массив с ключами, содержащими имена полей 265 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае, если искомой строки нет в таблице, вернет исходный массив 266 function selectRowAi($table, $key_value, $array) { 267 settype($key_value, 'int'); 268 $q = $f = ''; 269 foreach ($array as $key => $value) { 270 if ($f) { 271 $q.=',`' . $key . '`'; 272 } else { 273 $q = '`' . $key . '`'; 274 $f = 1; 275 } 276 } 277 $res = $this->query('SELECT ' . $q . ' FROM `' . $table . '` WHERE `id`=' . $key_value); 278 if (!$res->num_rows) { 279 return $array; 280 } 281 return $res->fetch_assoc(); 282 } 283 284 /// Получить значения столбца из таблицы структуры ключ/param/value по ключу в виде массива 285 /// @param table Имя таблицы 286 /// @param key_value Значение ключа, по которому производится выборка. Будет приведено к целому типу. 287 /// @param array Массив со значениями, содержащими имена полей 288 /// @return В случае успеха возвращает ассоциативный массив с данными. В случае sql ошибки вернёт false. В случае, если искомого значения нет в таблице, вернет пустую строку для такого значения 289 function selectFieldKA($table, $key_name, $key_value, $array) { 290 settype($key_value, 'int'); 291 $a = array_fill_keys($array, ''); 292 $res = $this->query('SELECT `param`, `value` FROM `' . $table . '` WHERE `' . $key_name . '`=' . $key_value); 293 if (!$res) { 294 return false; 295 } 296 while ($line = $res->fetch_row()) { 297 if (array_key_exists($line[0], $a)) { 298 $a[$line[0]] = $line[1]; 299 } 300 } 301 return $a; 302 } 303 304 /// Вставить строку в заданную таблицу 305 /// @param table Имя таблицы 306 /// @param array Ассоциативный массив вставляемых данных 307 /// @return id вставленной строки или false в случае ошибки 308 function insertA($table, $array) { 309 $cols = $values = ''; 310 $f = 0; 311 foreach ($array as $key => $value) { 312 if ($value !== 'NULL') { 313 $value = '\'' . $this->real_escape_string($value) . '\''; 314 } 315 if (!$f) { 316 $cols = '`' . $key . '`'; 317 $values = $value; 318 $f = 1; 319 } else { 320 $cols .= ', `' . $key . '`'; 321 $values .= ', ' . $value; 322 } 323 } 324 if (!$this->query("INSERT INTO `$table` ($cols) VALUES ($values)")) { 325 return false; 326 } 327 return $this->insert_id; 328 } 329 330 /// Обновить данные в заданной таблице 331 /// @param table Имя таблицы 332 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 333 /// @param field Название поля таблицы 334 /// @param value Новое значение поля таблицы. Автоматически экранируется. 335 /// @return Возвращаемое значение аналогично mysqli::query 336 function update($table, $key_value, $field, $value) { 337 settype($key_value, 'int'); 338 if ($value !== 'NULL') { 339 $value = '\'' . $this->real_escape_string($value) . '\''; 340 } 341 return $this->query("UPDATE `$table` SET `$field`=$value WHERE `id`=$key_value"); 342 } 343 344 /// Обновить данные в заданной таблице данными из массива по ключу с именем id 345 /// @param table Имя таблицы 346 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 347 /// @param array Ассоциативный массив ключ/значение для обновления. Значения автоматически экранируется. 348 /// @return Возвращаемое значение аналогично mysql::query 349 function updateA($table, $key_value, $array) { 350 settype($key_value, 'int'); 351 $q = $this->updatePrepare($array); 352 return $this->query("UPDATE `$table` SET $q WHERE `id`=$key_value"); 353 } 354 355 /// Обновить данные в заданной таблице данными из массива по ключу с заданным именем 356 /// @param table Имя таблицы 357 /// @param key_name Имя ключа таблицы 358 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 359 /// @param array Ассоциативный массив ключ/значение для обновления. Значения автоматически экранируется. 360 /// @return Возвращаемое значение аналогично mysqli::query 361 function updateKA($table, $key_name, $key_value, $array) { 362 settype($key_value, 'int'); 363 $key_name = $this->real_escape_string($key_name); 364 $q = $this->updatePrepare($array); 365 return $this->query("UPDATE `$table` SET $q WHERE `$key_name`=$key_value"); 366 } 367 368 /// Заменить данные в заданной таблице данными из массива по ключу с заданным именем 369 /// @param table Имя таблицы 370 /// @param key_name Имя ключа таблицы 371 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 372 /// @param array Ассоциативный массив ключ/значение для обновления. Значения автоматически экранируется. 373 /// @return Возвращаемое значение аналогично mysqli::query 374 function replaceKA($table, $key_name, $key_value, $array) { 375 settype($key_value, 'int'); 376 $q = $f = ''; 377 foreach ($array as $key => $value) { 378 if ($value !== 'NULL') { 379 $value = '\'' . $this->real_escape_string($value) . '\''; 380 } 381 if ($f) { 382 $q.=',(\'' . $key_value . '\',\'' . $key . '\',' . $value . ')'; 383 } else { 384 $q = '(\'' . $key_value . '\',\'' . $key . '\',' . $value . ')'; 385 $f = 1; 386 } 387 } 388 return $this->query('REPLACE `' . $table . '` (`' . $key_name . '`, `param`, `value`) VALUES ' . $q); 389 } 390 391 /// Удалить из заданной тоаблицы строку с указанным id 392 /// @param key_value Значение ключа, по которому будет произведено обновление. Будет приведено к целому типу. 393 public function delete($table, $key_value) { 394 settype($key_value, 'int'); 395 return $this->query('DELETE FROM `' . $table . '` WHERE `id`=' . $key_value); 396 } 397 398 /// Подготавливает данные для update запросов 399 /// @param array Ассоциативный массив ключ/значение для обновления. Значения автоматически экранируется. 400 private function updatePrepare($array) { 401 $q = $f = ''; 402 foreach ($array as $key => $value) { 403 if ($value !== 'NULL' && $value !== 'null') { 404 $value = '\'' . $this->real_escape_string($value) . '\''; 405 } 406 if ($f) { 407 $q.=',`' . $key . '`=' . $value; 408 } else { 409 $q = '`' . $key . '`=' . $value; 410 $f = 1; 411 } 412 } 413 return $q; 414 } 415 416 } -
web/core.php
r63901be r4cefac0 149 149 } 150 150 return $result; 151 } 152 153 /// Нормализация номера телефона 154 function normalizePhone($phone) { 155 $phone = preg_replace("/[^0-9+]/", "", $phone); 156 $phoneplus = $phone[0]=='+'; 157 $phone = preg_replace("/[^0-9]/", "", $phone); 158 if($phoneplus && $phone[0]==7 && strlen($phone)==11) { 159 return '+'.$phone; 160 } elseif(!$phoneplus && $phone[0]==8 && strlen($phone)==11) { 161 return '+7'.substr($phone,1); 162 } elseif(!$phoneplus && $phone[0]==9 && strlen($phone)==10) { 163 return '+7'.$phone; 164 } else { 165 return false; 166 } 167 } 168 169 /// Отсылает заголовок перенаправления в броузер и завершает скрипт 170 function redirect($url) { 171 if (headers_sent()) { 172 return false; 173 } 174 175 //$url = HTTP::absoluteURI($url); 176 header('Location: '. $url, true, 301); 177 178 if ( isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] != 'HEAD') { 179 echo ' 180 <p>Redirecting to: <a href="'.str_replace('"', '%22', $url).'">' 181 .htmlspecialchars($url).'</a>.</p> 182 <script type="text/javascript"> 183 //<![CDATA[ 184 if (location.replace == null) { 185 location.replace = location.assign; 186 } 187 location.replace("'.str_replace('"', '\\"', $url).'"); 188 // ]]> 189 </script>'; 190 } 191 exit; 151 192 } 152 193 -
web/css/doc_script.js
r63901be r4cefac0 204 204 function DocHeadInit() 205 205 { 206 var doc_left_block=document.getElementById("doc_left_block") 207 var doc_menu_container=document.getElementById("doc_menu_container") 208 var reset_cost=document.getElementById("reset_cost") 209 210 var lock_blur=0 211 var oldbg=doc_left_block.style.backgroundColor 212 213 doc_left_block.changing=0 214 215 doc_left_block.Save=function() 216 { 217 doc_left_block.style.backgroundColor='#ff8' 218 $.ajax({ 219 type: 'POST', 220 url: '/doc.php', 221 data: $('#doc_head_form').serialize(), 222 success: function(msg) { rcvDataSuccess(msg); }, 223 error: function() { jAlert('Ошибка соединения!','Сохранение данных',null,'icon_err'); }, 224 }); 225 } 226 227 doc_left_block.StartEdit=function() 228 { 229 doc_left_block.changing=1 230 doc_menu_container.style.display='none' 231 if(reset_cost) reset_cost.style.display='none' 232 if(doc_left_block.timeout) window.clearTimeout(doc_left_block.timeout) 233 } 234 235 doc_left_block.FinistEdit=function() 236 { 237 doc_left_block.changing=0 238 doc_menu_container.style.display='' 239 if(reset_cost) reset_cost.style.display='' 240 } 241 242 function rcvDataSuccess(msg) 243 { 244 try 245 { 246 247 if(doc_left_block.timeout) window.clearTimeout(doc_left_block.timeout) 248 var alfa=255 249 doc_left_block.timeout=window.setTimeout(function(){doc_left_block.style.backgroundColor=''}, 2000) 250 var json=eval('('+msg+')'); 251 if(json.response=='err') 252 { 253 doc_left_block.style.backgroundColor='#f00' 254 var errdiv=document.createElement('div') 255 doc_left_block.insertBefore(errdiv,doc_left_block.firstChild) 256 errdiv.className='err' 257 errdiv.style.backgroundColor='#000' 258 errdiv.innerHTML='<b>Ошибка сохранения</b><br>'+json.text 259 } 260 else if(json.response=='ok') 261 { 262 doc_left_block.style.backgroundColor='#bfa' 263 var agent_balance_info=document.getElementById("agent_balance_info") 264 if(agent_balance_info) 265 { 266 agent_balance_info.innerHTML=json.agent_balance 267 if(json.agent_balance>0) agent_balance_info.style.color='#f00' 268 else if(json.agent_balance<0) agent_balance_info.style.color='#080' 269 else agent_balance_info.style.color='' 270 } 271 } 272 else 273 { 274 doc_left_block.style.backgroundColor='#f00' 275 jAlert("Обработка полученного сообщения не реализована<br>"+msg, "Изменение списка товаров", null, 'icon_err'); 276 } 277 doc_left_block.FinistEdit() 278 } 279 catch(e) 280 { 281 doc_left_block.style.backgroundColor='#f00' 282 jAlert("Критическая ошибка!<br>Если ошибка повторится, уведомите администратора о том, при каких обстоятельствах возникла ошибка!"+ 283 "<br><br><i>Информация об ошибке</i>:<br>"+e.name+": "+e.message+"<br>"+msg, "Вставка строки в документ", null, 'icon_err'); 284 } 285 } 286 287 function obj_onclick(event) { 288 doc_left_block.StartEdit() 289 doc_left_block.timeout=window.setTimeout(doc_left_block.Save, 30000) // на всякий случай 290 } 291 292 function obj_onmousedown(event) 293 { 294 doc_left_block.StartEdit() 295 doc_left_block.timeout=window.setTimeout(doc_left_block.Save, 30000) // на всякий случай 296 // Хак для предотвращения отправки формы по onblur, если фокус готовится быть переданным на select и др элемент 297 lock_blur=1 298 window.setTimeout(function() {lock_blur=0}, 60) 299 } 300 301 obj_onblur=function(event) 302 { 303 if(lock_blur) return 304 if(doc_left_block.timeout) window.clearTimeout(doc_left_block.timeout) 305 doc_left_block.timeout=window.setTimeout(doc_left_block.Save, 500) 306 } 307 obj_onkeyup=function(event) 308 { 309 if(doc_left_block.timeout) window.clearTimeout(doc_left_block.timeout) 310 //doc_left_block.timeout=window.setTimeout(doc_left_block.Save, 3000) 311 } 312 313 doc_left_block.SetEvents=function(obj) 314 { 315 obj.addEventListener( 'mousedown', obj_onmousedown, false) 316 obj.addEventListener( 'click', obj_onclick, false) 317 obj.addEventListener( 'blur', obj_onblur, false) 318 obj.addEventListener( 'keyup', obj_onkeyup, false) 319 } 320 321 var fields=doc_left_block.getElementsByTagName('input') 322 for(var i=0; i<fields.length; i++) doc_left_block.SetEvents(fields[i]) 323 var fields=doc_left_block.getElementsByTagName('select') 324 for(var i=0; i<fields.length; i++) doc_left_block.SetEvents(fields[i]) 325 var fields=doc_left_block.getElementsByTagName('textarea') 326 for(var i=0; i<fields.length; i++) doc_left_block.SetEvents(fields[i]) 327 328 initCalendar("datetime",true) 329 330 if(supports_html5_storage()) 331 { 332 if(localStorage['doc_left_block_hidden']=='hidden') 333 { 334 var doc_left_block=document.getElementById("doc_left_block") 335 var doc_main_block=document.getElementById("doc_main_block") 336 var doc_left_arrow=document.getElementById("doc_left_arrow") 337 doc_left_block.style.display='none' 338 doc_main_block.oldmargin=doc_main_block.style.marginLeft 339 doc_main_block.style.marginLeft=0 340 doc_left_arrow.src='/img/i_rightarrow.png' 341 } 342 } 206 var doc_left_block = document.getElementById("doc_left_block"); 207 var doc_menu_container = document.getElementById("doc_menu_container"); 208 var reset_cost = document.getElementById("reset_cost"); 209 210 var lock_blur = 0; 211 var oldbg = doc_left_block.style.backgroundColor; 212 213 doc_left_block.changing = 0; 214 215 doc_left_block.Save = function () { 216 doc_left_block.style.backgroundColor = '#ff8'; 217 $.ajax({ 218 type: 'POST', 219 url: '/doc.php', 220 data: $('#doc_head_form').serialize(), 221 success: function (msg) { 222 rcvDataSuccess(msg); 223 }, 224 error: function () { 225 jAlert('Ошибка соединения!', 'Сохранение данных', null, 'icon_err'); 226 } 227 }); 228 }; 229 230 doc_left_block.StartEdit = function () { 231 doc_left_block.changing = 1; 232 doc_menu_container.style.display = 'none'; 233 if (reset_cost) 234 reset_cost.style.display = 'none'; 235 if (doc_left_block.timeout) 236 window.clearTimeout(doc_left_block.timeout); 237 }; 238 239 doc_left_block.FinistEdit = function () { 240 doc_left_block.changing = 0; 241 doc_menu_container.style.display = ''; 242 if (reset_cost) 243 reset_cost.style.display = ''; 244 }; 245 246 function rcvDataSuccess(msg) { 247 try { 248 if (doc_left_block.timeout) 249 window.clearTimeout(doc_left_block.timeout); 250 var alfa = 255; 251 doc_left_block.timeout = window.setTimeout(function () { 252 doc_left_block.style.backgroundColor = '' 253 }, 2000) 254 var json = eval('(' + msg + ')'); 255 if (json.response == 'err') 256 { 257 doc_left_block.style.backgroundColor = '#f00' 258 var errdiv = document.createElement('div') 259 doc_left_block.insertBefore(errdiv, doc_left_block.firstChild) 260 errdiv.className = 'err' 261 errdiv.style.backgroundColor = '#000' 262 errdiv.innerHTML = '<b>Ошибка сохранения</b><br>' + json.text 263 } 264 else if (json.response == 'ok') 265 { 266 doc_left_block.style.backgroundColor = '#bfa' 267 var agent_balance_info = document.getElementById("agent_balance_info") 268 if (agent_balance_info) 269 { 270 agent_balance_info.innerHTML = json.agent_balance 271 if (json.agent_balance > 0) 272 agent_balance_info.style.color = '#f00' 273 else if (json.agent_balance < 0) 274 agent_balance_info.style.color = '#080' 275 else 276 agent_balance_info.style.color = '' 277 } 278 } 279 else 280 { 281 doc_left_block.style.backgroundColor = '#f00' 282 jAlert("Обработка полученного сообщения не реализована<br>" + msg, "Изменение списка товаров", null, 'icon_err'); 283 } 284 doc_left_block.FinistEdit() 285 } 286 catch (e) 287 { 288 doc_left_block.style.backgroundColor = '#f00' 289 jAlert("Критическая ошибка!<br>Если ошибка повторится, уведомите администратора о том, при каких обстоятельствах возникла ошибка!" + 290 "<br><br><i>Информация об ошибке</i>:<br>" + e.name + ": " + e.message + "<br>" + msg, "Вставка строки в документ", null, 'icon_err'); 291 } 292 } 293 294 function obj_onclick(event) { 295 doc_left_block.StartEdit() 296 doc_left_block.timeout = window.setTimeout(doc_left_block.Save, 30000) // на всякий случай 297 } 298 299 function obj_onmousedown(event) 300 { 301 doc_left_block.StartEdit() 302 doc_left_block.timeout = window.setTimeout(doc_left_block.Save, 30000) // на всякий случай 303 // Хак для предотвращения отправки формы по onblur, если фокус готовится быть переданным на select и др элемент 304 lock_blur = 1 305 window.setTimeout(function () { 306 lock_blur = 0 307 }, 60) 308 } 309 310 obj_onblur = function (event) 311 { 312 if (lock_blur) 313 return 314 if (doc_left_block.timeout) 315 window.clearTimeout(doc_left_block.timeout) 316 doc_left_block.timeout = window.setTimeout(doc_left_block.Save, 500) 317 } 318 obj_onkeyup = function (event) 319 { 320 if (doc_left_block.timeout) 321 window.clearTimeout(doc_left_block.timeout) 322 //doc_left_block.timeout=window.setTimeout(doc_left_block.Save, 3000) 323 } 324 325 doc_left_block.SetEvents = function (obj) 326 { 327 obj.addEventListener('mousedown', obj_onmousedown, false) 328 obj.addEventListener('click', obj_onclick, false) 329 obj.addEventListener('blur', obj_onblur, false) 330 obj.addEventListener('keyup', obj_onkeyup, false) 331 } 332 333 var fields = doc_left_block.getElementsByTagName('input') 334 for (var i = 0; i < fields.length; i++) 335 doc_left_block.SetEvents(fields[i]) 336 var fields = doc_left_block.getElementsByTagName('select') 337 for (var i = 0; i < fields.length; i++) 338 doc_left_block.SetEvents(fields[i]) 339 var fields = doc_left_block.getElementsByTagName('textarea') 340 for (var i = 0; i < fields.length; i++) 341 doc_left_block.SetEvents(fields[i]) 342 343 initCalendar("datetime", true) 344 345 if (supports_html5_storage()) 346 { 347 if (localStorage['doc_left_block_hidden'] == 'hidden') 348 { 349 var doc_left_block = document.getElementById("doc_left_block") 350 var doc_main_block = document.getElementById("doc_main_block") 351 var doc_left_arrow = document.getElementById("doc_left_arrow") 352 doc_left_block.style.display = 'none' 353 doc_main_block.oldmargin = doc_main_block.style.marginLeft 354 doc_main_block.style.marginLeft = 0 355 doc_left_arrow.src = '/img/i_rightarrow.png' 356 } 357 } 358 359 function globalKeyListener(event) { 360 var e = event || window.event; 361 if (e.keyCode == 27) { 362 window.close(); 363 } else if (e.keyCode == 112) { 364 window.open("http://multimag.tndproject.org/wiki/userdoc"); 365 } 366 } 367 addEventListener('keyup', globalKeyListener, false); 343 368 } 344 369 -
web/fpdf/fpdf.php
r63901be r4cefac0 814 814 function MultiCellIconv($w, $h, $txt, $border=0, $align='J', $fill=false) 815 815 { 816 return $this->MultiCell($w, $h, iconv('UTF-8', 'windows-1251', $txt), $border, $align, $fill);816 return $this->MultiCell($w, $h, @iconv('UTF-8', 'windows-1251', $txt), $border, $align, $fill); 817 817 } 818 818 -
web/fpdf/fpdf_mysql.php
r63901be r4cefac0 199 199 } 200 200 201 function draw_groups_tree($pid, $query, $prop) 202 { 203 global $db; 204 $res=$db->query("SELECT `id`, `name` FROM `doc_group` WHERE `pid`='$pid' AND `hidelevel`='0' ORDER BY `id`"); 205 while($nxt=$res->fetch_row()) 206 { 207 if($nxt[0]==0) continue; 208 if(isset($prop['groups']) ) 209 if( ! in_array($nxt[0],$prop['groups']) ) continue; 210 $this->Row($nxt[1],1,$prop['cost_id']); 211 $res2=$db->query($query."WHERE `group`='$nxt[0]' AND `doc_base`.`hidden`='0' ORDER BY `name`"); 212 while($row=$res2->fetch_array()) 213 { 214 $this->Row($row,0,$prop['cost_id']); 215 } 216 $this->draw_groups_tree($nxt[0], $query, $prop); 217 } 218 } 219 } 220 ?> 201 function draw_groups_tree($pid, $query, $prop) { 202 global $db; 203 $res = $db->query("SELECT `id`, `name` FROM `doc_group` WHERE `pid`='$pid' AND `hidelevel`='0' ORDER BY `id`"); 204 while ($nxt = $res->fetch_row()) { 205 if ($nxt[0] == 0) { 206 continue; 207 } 208 if (isset($prop['groups'])) { 209 if (!in_array($nxt[0], $prop['groups'])) { 210 continue; 211 } 212 } 213 $this->Row($nxt[1], 1, $prop['cost_id']); 214 $res2 = $db->query($query . "WHERE `group`='$nxt[0]' AND `doc_base`.`hidden`='0' ORDER BY `name`"); 215 while ($row = $res2->fetch_array()) { 216 $this->Row($row, 0, $prop['cost_id']); 217 } 218 $this->draw_groups_tree($nxt[0], $query, $prop); 219 } 220 } 221 222 } -
web/include/doc.core.php
r63901be r4cefac0 286 286 $res = $db->query("INSERT INTO `doc_log` (`user`, `ip`, `time`,`motion`,`desc`, `object`, `object_id`) 287 287 VALUES ('$uid', '$ip', NOW(),'$motion','$desc', '$object', '$object_id')"); 288 } 289 290 /// @brief Сформировать строку с названием элемента списка номенклатуры в зависимости от настроек 291 /// Если какой-то элемент не задан - он не будет использоваться в формировании результата 292 /// @param $id Id элемента 293 /// @param $vc 294 /// @param $name 295 /// @param $vendor 296 function composePosNameStr($id = 0, $vc = '', $name = '', $vendor = '') { 297 global $CONFIG; 298 if(@$CONFIG['poseditor']['vc'] && $vc) { 299 $name = $vc . ' ' . $name; 300 } 301 if(!@$CONFIG['doc']['no_print_vendor'] && $vendor) { 302 $name .= ' / '.$vendor; 303 } 304 $name .= '(ID:'.$id.')'; 305 return $name; 288 306 } 289 307 -
web/include/doc.nulltype.php
r63901be r4cefac0 1238 1238 1239 1239 if($this->sklad_editor_enable) { 1240 1241 1242 1243 1244 1240 include_once('doc.poseditor.php'); 1241 $poseditor = new DocPosEditor($this); 1242 $poseditor->cost_id = @$this->dop_data['cena']; 1243 $poseditor->sklad_id = $this->doc_data['sklad']; 1244 $poseditor->SetEditable($this->doc_data['ok']?0:1); 1245 1245 } 1246 1246 … … 1262 1262 } 1263 1263 // Снять пометку на удаление 1264 else if($opt=='jundeldoc') 1265 { 1266 try 1267 { 1268 if(! isAccess('doc_'.$this->doc_name,'delete') ) throw new AccessException("Недостаточно привилегий"); 1269 $db->update('doc_list', $this->doc, 'mark_del', 0); 1270 doc_log("UNDELETE", '', "doc", $this->doc); 1271 $json=' { "response": "1", "message": "Пометка на удаление снята!", "buttons": "'.$this->getApplyButtons().'", "statusblock": "Документ не будет удалён" }'; 1272 $tmpl->setContent($json); 1273 } 1274 catch(Exception $e) 1275 { 1276 $tmpl->setContent("{response: 0, message: '".$e->getMessage()."'}"); 1277 } 1264 else if($opt=='jundeldoc') { 1265 $tmpl->setContent($this->serviceUnDelDoc()); 1278 1266 } 1279 1267 /// TODO: Это тоже переделать! … … 1284 1272 // Получение данных наименования 1285 1273 else if ($peopt == 'jgpi') { 1286 1287 1274 $pos = rcvint('pos'); 1275 $tmpl->addContent($poseditor->GetPosInfo($pos)); 1288 1276 } 1289 1277 // Json вариант добавления позиции 1290 1278 else if ($peopt == 'jadd') { 1291 1292 1293 1294 1279 if (!isAccess('doc_' . $this->doc_name, 'edit')) 1280 throw new AccessException("Недостаточно привилегий"); 1281 $pe_pos = rcvint('pe_pos'); 1282 $tmpl->setContent($poseditor->AddPos($pe_pos)); 1295 1283 } 1296 1284 // Json вариант удаления строки 1297 1285 else if ($peopt == 'jdel') { 1298 1299 1300 1301 1286 if (!isAccess('doc_' . $this->doc_name, 'edit')) 1287 throw new AccessException("Недостаточно привилегий"); 1288 $line_id = rcvint('line_id'); 1289 $tmpl->setContent($poseditor->Removeline($line_id)); 1302 1290 } 1303 1291 // Json вариант обновления 1304 1292 else if ($peopt == 'jup') { 1305 1306 1307 1308 1309 1310 1311 1293 if (!isAccess('doc_' . $this->doc_name, 'edit')) 1294 throw new AccessException("Недостаточно привилегий"); 1295 $line_id = rcvint('line_id'); 1296 $value = request('value'); 1297 $type = request('type'); 1298 // TODO: пересчет цены перенести внутрь poseditor 1299 $tmpl->setContent($poseditor->UpdateLine($line_id, $type, $value)); 1312 1300 } 1313 1301 // Получение номенклатуры выбранной группы 1314 1302 else if ($peopt == 'jsklad') { 1315 1316 1317 1303 $group_id = rcvint('group_id'); 1304 $str = "{ response: 'sklad_list', group: '$group_id', content: [" . $poseditor->GetSkladList($group_id) . "] }"; 1305 $tmpl->setContent($str); 1318 1306 } 1319 1307 // Поиск по подстроке по складу 1320 1308 else if ($peopt == 'jsklads') { 1321 1322 1323 1309 $s = request('s'); 1310 $str = "{ response: 'sklad_list', content: " . $poseditor->SearchSkladList($s) . " }"; 1311 $tmpl->setContent($str); 1324 1312 } 1325 1313 // Серийные номера 1326 1314 else if ($peopt == 'jsn') { 1327 1328 1329 1330 1315 $action = request('a'); 1316 $line_id = request('line'); 1317 $data = request('data'); 1318 $tmpl->setContent($poseditor->SerialNum($action, $line_id, $data)); 1331 1319 } 1332 1320 // Сброс цен 1333 1321 else if ($peopt == 'jrc') { 1334 1322 $poseditor->resetPrices(); 1335 1323 } 1336 1324 // Сортировка наименований 1337 1325 else if ($peopt == 'jorder') { 1338 1339 1326 $by = request('by'); 1327 $poseditor->reOrder($by); 1340 1328 } 1341 1329 // Пометка на удаление 1342 else if($opt=='jdeldoc') 1343 { 1344 try 1345 { 1346 if(! isAccess('doc_'.$this->doc_name,'delete') ) throw new AccessException("Недостаточно привилегий"); 1347 $tim=time(); 1348 1349 $res = $db->query("SELECT `id` FROM `doc_list` WHERE `p_doc`='{$this->doc}' AND `mark_del`='0'"); 1350 if($res->num_rows) 1351 throw new Exception("Есть подчинённые не удалённые документы. Удаление невозможно."); 1352 $db->update('doc_list', $this->doc, 'mark_del', $tim); 1353 doc_log("MARKDELETE", '', "doc", $this->doc); 1354 $this->doc_data['mark_del']=$tim; 1355 $json=' { "response": "1", "message": "Пометка на удаление установлена!", "buttons": "'.$this->getApplyButtons().'", "statusblock": "Документ помечен на удаление" }'; 1356 $tmpl->setContent($json); 1357 1358 } 1359 catch(Exception $e) 1360 { 1361 $tmpl->setContent("{response: 0, message: '".$e->getMessage()."'}"); 1362 } 1330 else if($opt=='jdeldoc') { 1331 $tmpl->setContent($this->serviceDelDoc()); 1363 1332 } 1364 1333 // Загрузка номенклатурной таблицы … … 1839 1808 } 1840 1809 1841 /// Обычная накладная в PDF формате 1842 /// @param to_str Вернуть строку, содержащую данные документа (в противном случае - отправить файлом) 1810 /// Получить список номенклатуры 1843 1811 function getDocumentNomenclature() { 1844 1812 global $CONFIG, $db; … … 1874 1842 return $list; 1875 1843 } 1876 1844 1845 /// Установить пометку на удаление у документа 1846 protected function serviceDelDoc() { 1847 global $db; 1848 try { 1849 if (!isAccess('doc_' . $this->doc_name, 'delete')) { 1850 throw new AccessException("Недостаточно привилегий"); 1851 } 1852 $tim = time(); 1853 1854 $res = $db->query("SELECT `id` FROM `doc_list` WHERE `p_doc`='{$this->doc}' AND `mark_del`='0'"); 1855 if ($res->num_rows) { 1856 throw new Exception("Есть подчинённые не удалённые документы. Удаление невозможно."); 1857 } 1858 $db->update('doc_list', $this->doc, 'mark_del', $tim); 1859 doc_log("MARKDELETE", '', "doc", $this->doc); 1860 $this->doc_data['mark_del'] = $tim; 1861 $json = ' { "response": "1", "message": "Пометка на удаление установлена!", "buttons": "' . $this->getApplyButtons() . '", ' 1862 . '"statusblock": "Документ помечен на удаление" }'; 1863 return $json; 1864 } catch (Exception $e) { 1865 return "{response: 0, message: '" . $e->getMessage() . "'}"; 1866 } 1867 } 1868 1869 /// Снять пометку на удаление у документа 1870 protected function serviceUnDelDoc() { 1871 global $db; 1872 try { 1873 if (!isAccess('doc_' . $this->doc_name, 'delete')) { 1874 throw new AccessException("Недостаточно привилегий"); 1875 } 1876 $db->update('doc_list', $this->doc, 'mark_del', 0); 1877 doc_log("UNDELETE", '', "doc", $this->doc); 1878 $json = ' { "response": "1", "message": "Пометка на удаление снята!", "buttons": "' . $this->getApplyButtons() . '", ' 1879 . '"statusblock": "Документ не будет удалён" }'; 1880 return $json; 1881 } catch (Exception $e) { 1882 return "{response: 0, message: '" . $e->getMessage() . "'}"; 1883 } 1884 } 1877 1885 } -
web/include/doc.peremeshenie.php
r63901be r4cefac0 127 127 128 128 $res = $db->query("SELECT `doc_list_pos`.`tovar`, `doc_list_pos`.`cnt`, `doc_base_cnt`.`cnt`, `doc_base`.`name`, `doc_base`.`proizv`, 129 `doc_base`.`pos_type` 129 `doc_base`.`pos_type`, `doc_base`.`vc` 130 130 FROM `doc_list_pos` 131 131 LEFT JOIN `doc_base` ON `doc_base`.`id`=`doc_list_pos`.`tovar` 132 132 LEFT JOIN `doc_base_cnt` ON `doc_base_cnt`.`id`=`doc_base`.`id` AND `doc_base_cnt`.`sklad`='{$doc_info['sklad']}' 133 133 WHERE `doc_list_pos`.`doc`='{$this->doc}'"); 134 $fail_text = ''; 134 135 while ($nxt = $res->fetch_row()) { 135 136 if ($nxt[5] > 0) { … … 137 138 } 138 139 if (!$doc_info['dnc'] && ($nxt[1] > $nxt[2])) { 139 throw new Exception("Недостаточно ($nxt[1]) товара '$nxt[3]:$nxt[4]' на складе($nxt[2])!"); 140 $pos_name = composePosNameStr($nxt[0], $nxt[6], $nxt[3], $nxt[4]); 141 $fail_text .= "Мало товара '$pos_name' - есть:{$nxt[2]}, нужно:{$nxt[1]}. \n"; 142 continue; 140 143 } 141 144 $db->query("UPDATE `doc_base_cnt` SET `cnt`=`cnt`-'$nxt[1]' WHERE `id`='$nxt[0]' AND `sklad`='{$doc_info['sklad']}'"); … … 149 152 $budet = getStoreCntOnDate($nxt[0], $doc_info['sklad']); 150 153 if ($budet < 0) { 151 throw new Exception("Невозможно, т.к. будет недостаточно ($budet) товара '$nxt[3]:$nxt[4]' !"); 154 $pos_name = composePosNameStr($nxt[0], $nxt[6], $nxt[3], $nxt[4]); 155 $t = $budet + $nxt[1]; 156 $fail_text .= "Будет мало товара '$pos_name' - есть:$t, нужно:{$nxt[1]}. \n"; 157 continue; 152 158 } 153 159 } 154 160 } 161 162 if($fail_text) { 163 throw new Exception("Ошибка номенклатуры: \n".$fail_text); 164 } 165 155 166 $res->free(); 156 167 if ($silent) { -
web/include/doc.realiz_op.php
r63901be r4cefac0 54 54 } 55 55 56 }; 57 ?> 56 } -
web/include/doc.realizaciya.php
r63901be r4cefac0 227 227 228 228 $res = $db->query("SELECT `doc_list_pos`.`tovar`, `doc_list_pos`.`cnt`, `doc_base_cnt`.`cnt`, `doc_base`.`name`, `doc_base`.`proizv`, 229 `doc_base`.`pos_type`, `doc_list_pos`.`id`, `doc_base`.`vc`, `doc_list_pos`.`cost` 229 `doc_base`.`pos_type`, `doc_list_pos`.`id`, `doc_base`.`vc`, `doc_list_pos`.`cost`, `doc_base`.`vc` 230 230 FROM `doc_list_pos` 231 231 LEFT JOIN `doc_base` ON `doc_base`.`id`=`doc_list_pos`.`tovar` … … 233 233 WHERE `doc_list_pos`.`doc`='{$this->doc}' AND `doc_base`.`pos_type`='0'"); 234 234 $bonus = 0; 235 $fail_text = ''; 235 236 while ($nxt = $res->fetch_row()) { 236 237 if (!$doc_params['dnc']) { 237 if ($nxt[1] > $nxt[2]) 238 throw new Exception("Недостаточно ($nxt[1]) товара '$nxt[3]:$nxt[4] - $nxt[7]($nxt[0])': на складе только $nxt[2] шт!"); 238 if ($nxt[1] > $nxt[2]) { 239 $pos_name = composePosNameStr($nxt[0], $nxt[9], $nxt[3], $nxt[4]); 240 $fail_text .= "Мало товара '$pos_name' - есть:{$nxt[2]}, нужно:{$nxt[1]}. \n"; 241 continue; 242 } 239 243 } 240 244 … … 243 247 if (!$doc_params['dnc'] && (!$silent)) { 244 248 $budet = getStoreCntOnDate($nxt[0], $doc_params['sklad'], $doc_params['date']); 245 if ($budet < 0) 246 throw new Exception("Невозможно ($silent), т.к. будет недостаточно ($budet) товара '$nxt[3]:$nxt[4] - $nxt[7]($nxt[0])'!"); 249 if ($budet < 0) { 250 $pos_name = composePosNameStr($nxt[0], $nxt[9], $nxt[3], $nxt[4]); 251 $t = $budet + $nxt[1]; 252 $fail_text .= "Будет мало товара '$pos_name' - есть:$t, нужно:{$nxt[1]}. \n"; 253 continue; 254 } 247 255 } 248 256 … … 250 258 $r = $db->query("SELECT COUNT(`doc_list_sn`.`id`) FROM `doc_list_sn` WHERE `rasx_list_pos`='$nxt[6]'"); 251 259 list($sn_cnt) = $r->fetch_row(); 252 if ($sn_cnt != $nxt[1]) 253 throw new Exception("Количество серийных номеров товара $nxt[0] ($nxt[1]) не соответствует количеству серийных номеров ($sn_cnt)"); 260 if ($sn_cnt != $nxt[1]) { 261 $pos_name = composePosNameStr($nxt[0], $nxt[9], $nxt[3], $nxt[4]); 262 $fail_text .= "Мало серийных номеров товара '$pos_name' - есть:$sn_cnt, нужно:{$nxt[1]}. \n"; 263 continue; 264 } 254 265 } 255 256 266 $bonus+=$nxt[8] * $nxt[1] * (@$CONFIG['bonus']['coeff']); 257 267 } 258 259 if ($silent) 268 269 if($fail_text) { 270 throw new Exception("Ошибка номенклатуры: \n".$fail_text); 271 } 272 273 if ($silent) { 260 274 return; 275 } 261 276 if (!$doc_params['no_bonuses'] && $bonus>0) 262 277 $db->query("REPLACE INTO `doc_dopdata` (`doc`,`param`,`value`) VALUES ( '{$this->doc}' ,'bonus','$bonus')"); … … 1191 1206 if (count($gtd_array) == 0) { 1192 1207 if($CONFIG['poseditor']['true_gtd']!='easy') { 1193 throw new \Exception("Не найдены поступления для $cnt единиц товара {$nxt[ 1]} (для реализации N{$line['id']} в прошлом). Товар был оприходован на другую организацию?");1208 throw new \Exception("Не найдены поступления для $cnt единиц товара {$nxt['name']} (для реализации N{$line['id']} в прошлом). Товар был оприходован на другую организацию?"); 1194 1209 } 1195 1210 else { -
web/include/doc.sborka.php
r63901be r4cefac0 21 21 class doc_Sborka extends doc_Nulltype { 22 22 23 24 25 $this->doc_type= 17;26 $this->doc_name= 'sborka';27 $this->doc_viewname= 'Сборка изделия';28 $this->sklad_editor_enable= true;29 $this->header_fields= 'agent cena sklad';30 31 $this->dop_menu_buttons= "<a href='/doc_sc.php?mode=reopen&sn=sborka_zap&doc=$doc&' title='Передать в сценарий'><img src='img/i_launch.png' alt='users'></a>";32 23 public function __construct($doc=0){ 24 parent::__construct($doc); 25 $this->doc_type = 17; 26 $this->doc_name = 'sborka'; 27 $this->doc_viewname = 'Сборка изделия'; 28 $this->sklad_editor_enable = true; 29 $this->header_fields = 'agent cena sklad'; 30 settype($this->doc,'int'); 31 $this->dop_menu_buttons = "<a href='/doc_sc.php?mode=reopen&sn=sborka_zap&doc=$doc&' title='Передать в сценарий'><img src='img/i_launch.png' alt='users'></a>"; 32 } 33 33 34 35 36 34 public function initDefDopdata() { 35 $this->def_dop_data = array('sklad'=>0, 'cena'=>1); 36 } 37 37 38 public function DocApply($silent = 0) { 39 global $db; 40 41 $pres = $db->query("SELECT `doc_list`.`id`, `doc_list`.`date`, `doc_list`.`type`, `doc_list`.`sklad`, `doc_list`.`ok`, `doc_sklady`.`dnc` 42 FROM `doc_list` 43 LEFT JOIN `doc_sklady` ON `doc_sklady`.`id`=`doc_list`.`sklad` 44 WHERE `doc_list`.`id`='{$this->doc}'"); 45 $doc_info = $pres->fetch_assoc(); 46 if (!$doc_info) 47 throw new Exception("Документ {$this->doc} не найден!"); 48 if ($doc_info['ok'] && (!$silent)) 49 throw new Exception('Документ уже был проведён!'); 50 $pres->free(); 51 52 $res = $db->query("SELECT `doc_list_pos`.`tovar`, `doc_list_pos`.`cnt`, `doc_base_cnt`.`cnt` AS `sklad_cnt`, `doc_base`.`name`, `doc_base`.`proizv`, `doc_base`.`pos_type`, `doc_list_pos`.`id`, `doc_list_pos`.`page` 53 FROM `doc_list_pos` 54 LEFT JOIN `doc_base` ON `doc_base`.`id`=`doc_list_pos`.`tovar` 55 LEFT JOIN `doc_base_cnt` ON `doc_base_cnt`.`id`=`doc_base`.`id` AND `doc_base_cnt`.`sklad`='{$doc_info['sklad']}' 56 WHERE `doc_list_pos`.`doc`='{$this->doc}' AND `doc_base`.`pos_type`='0'"); 57 while ($doc_line = $res->fetch_array()) { 58 $sign = $doc_line['page'] ? '-' : '+'; 59 if ($doc_line['page']) { 60 if (!$doc_info['dnc']) 61 if ($doc_line[1] > $doc_line[2]) 62 throw new Exception("Недостаточно ($doc_line[1]) товара '$doc_line[3]:$doc_line[4]($doc_line[0])': на складе только $doc_line[2] шт!"); 63 if (!$doc_info['dnc'] && (!$silent)) { 64 $budet = getStoreCntOnDate($doc_line[0], $doc_info['sklad']); 65 if ($budet < 0) 66 throw new Exception("Невозможно ($silent), т.к. будет недостаточно ($budet) товара '$doc_line[3]:$doc_line[4]($doc_line[0])'!"); 67 } 68 } 69 70 $db->query("UPDATE `doc_base_cnt` SET `cnt`=`cnt` $sign '{$doc_line['cnt']}' WHERE `id`='{$doc_line['tovar']}' AND `sklad`='{$doc_info['sklad']}'"); 71 // Если это первое поступление 72 if ($db->affected_rows == 0) 73 $db->query("INSERT INTO `doc_base_cnt` (`id`, `sklad`, `cnt`) VALUES ('$doc_line[0]', '$doc_info[3]', '{$doc_line['cnt']}')"); 74 } 75 if ($silent) return; 76 $db->update('doc_list', $this->doc, 'ok', time() ); 77 $this->sentZEvent('apply'); 78 } 79 80 function DocCancel() { 81 global $db; 82 $pres = $db->query("SELECT `doc_list`.`id`, `doc_list`.`date`, `doc_list`.`type`, `doc_list`.`sklad`, `doc_list`.`ok`, `doc_sklady`.`dnc` 83 FROM `doc_list` 84 LEFT JOIN `doc_sklady` ON `doc_sklady`.`id`=`doc_list`.`sklad` 85 WHERE `doc_list`.`id`='{$this->doc}'"); 86 $nx = $pres->fetch_row(); 87 if (!$nx) throw new Exception("Документ {$this->doc} не найден!"); 88 if (!$nx[4]) throw new Exception("Документ ещё не проведён!"); 89 90 $db->update('doc_list', $this->doc, 'ok', 0 ); 91 92 $res = $db->query("SELECT `doc_list_pos`.`tovar`, `doc_list_pos`.`cnt`, `doc_base_cnt`.`cnt`, `doc_base`.`name`, `doc_base`.`proizv`, `doc_base`.`pos_type`, `doc_list_pos`.`page` 93 FROM `doc_list_pos` 94 LEFT JOIN `doc_base` ON `doc_base`.`id`=`doc_list_pos`.`tovar` 95 LEFT JOIN `doc_base_cnt` ON `doc_base_cnt`.`id`=`doc_base`.`id` AND `doc_base_cnt`.`sklad`='$nx[3]' 96 WHERE `doc_list_pos`.`doc`='{$this->doc}'"); 97 while ($nxt = $res->fetch_row()) { 98 if ($nxt[5] == 0) { 99 $sign = $nxt[6] ? '+' : '-'; 100 $db->query("UPDATE `doc_base_cnt` SET `cnt`=`cnt` $sign '$nxt[1]' WHERE `id`='$nxt[0]' AND `sklad`='$nx[3]'"); 101 } 102 } 103 } 104 105 function Service() { 106 global $tmpl, $db; 107 $tmpl->ajax = 1; 108 $opt = request('opt'); 109 $peopt = request('peopt'); 110 $pe_pos = request('pe_pos'); 111 include_once('include/doc.zapposeditor.php'); 112 $poseditor = new SZapPosEditor($this); 113 $poseditor->cost_id = $this->dop_data['cena']; 114 $poseditor->sklad_id = $this->doc_data['sklad']; 115 116 if (isAccess('doc_' . $this->doc_name, 'view')) { 117 118 // Json-вариант списка товаров 119 if ($peopt == 'jget') { 120 $doc_sum = $this->recalcSum(); 121 $str = "{ response: 'loadlist', content: [" . $poseditor->GetAllContent() . "], sum: '$doc_sum' }"; 122 $tmpl->addContent($str); 123 } 124 else if($peopt=='jgetgroups') 125 { 126 $doc_content = $poseditor->getGroupList(); 127 $tmpl->addContent($doc_content); 128 } 129 // Получение данных наименования 130 else if ($peopt == 'jgpi') { 131 $pe_pos = rcvint('pos'); 132 $tmpl->addContent($poseditor->GetPosInfo($pe_pos)); 133 } 134 // Json вариант добавления позиции 135 else if ($peopt == 'jadd') { 136 if (!isAccess('doc_sborka', 'edit')) 137 throw new AccessException("Недостаточно привилегий"); 138 $pe_pos = rcvint('pos'); 139 $tmpl->setContent($poseditor->AddPos($pe_pos)); 140 } 141 // Json вариант удаления строки 142 else if ($peopt == 'jdel') { 143 if (!isAccess('doc_sborka', 'edit')) 144 throw new AccessException("Недостаточно привилегий"); 145 $line_id = rcvint('line_id'); 146 $tmpl->setContent($poseditor->Removeline($line_id)); 147 } 148 // Json вариант обновления 149 else if ($peopt == 'jup') { 150 if (!isAccess('doc_sborka', 'edit')) 151 throw new AccessException("Недостаточно привилегий"); 152 $line_id = rcvint('line_id'); 153 $value = request('value'); 154 $type = request('type'); 155 $tmpl->setContent($poseditor->UpdateLine($line_id, $type, $value)); 156 } 157 // Получение номенклатуры выбранной группы 158 else if ($peopt == 'jsklad') { 159 $group_id = rcvint('group_id'); 160 $str = "{ response: 'sklad_list', group: '$group_id', content: [" . $poseditor->GetSkladList($group_id) . "] }"; 161 $tmpl->setContent($str); 162 } 163 // Поиск по подстроке по складу 164 else if ($peopt == 'jsklads') { 165 $s = request('s'); 166 $str = "{ response: 'sklad_list', content: " . $poseditor->SearchSkladList($s) . " }"; 167 $tmpl->setContent($str); 168 } else if ($peopt == 'jsn') { 169 $action = request('a'); 170 $line_id = request('line'); 171 $data = request('data'); 172 $tmpl->setContent($poseditor->SerialNum($action, $line_id, $data)); 173 } 174 else if($opt=='jdeldoc') 175 { 176 try 177 { 178 if(! isAccess('doc_'.$this->doc_name,'delete') ) throw new AccessException("Недостаточно привилегий"); 179 $tim=time(); 180 181 $res = $db->query("SELECT `id` FROM `doc_list` WHERE `p_doc`='{$this->doc}' AND `mark_del`='0'"); 182 if($res->num_rows) 183 throw new Exception("Есть подчинённые не удалённые документы. Удаление невозможно."); 184 $db->update('doc_list', $this->doc, 'mark_del', $tim); 185 doc_log("MARKDELETE", '', "doc", $this->doc); 186 $this->doc_data['mark_del']=$tim; 187 $json=' { "response": "1", "message": "Пометка на удаление установлена!", "buttons": "'.$this->getApplyButtons().'", "statusblock": "Документ помечен на удаление" }'; 188 $tmpl->setContent($json); 189 190 } 191 catch(Exception $e) 192 { 193 $tmpl->setContent("{response: 0, message: '".$e->getMessage()."'}"); 194 } 195 } 196 // Снять пометку на удаление 197 else if($opt=='jundeldoc') 198 { 199 try 200 { 201 if(! isAccess('doc_'.$this->doc_name,'delete') ) throw new AccessException("Недостаточно привилегий"); 202 $db->update('doc_list', $this->doc, 'mark_del', 0); 203 doc_log("UNDELETE", '', "doc", $this->doc); 204 $json=' { "response": "1", "message": "Пометка на удаление снята!", "buttons": "'.$this->getApplyButtons().'", "statusblock": "Документ не будет удалён" }'; 205 $tmpl->setContent($json); 206 } 207 catch(Exception $e) 208 { 209 $tmpl->setContent("{response: 0, message: '".$e->getMessage()."'}"); 210 } 211 } 212 else throw new NotFoundException('Параметр не найден!'); 213 } 214 } 215 }; 216 217 ?> 38 public function DocApply($silent = 0) { 39 global $db; 40 41 $pres = $db->query("SELECT `doc_list`.`id`, `doc_list`.`date`, `doc_list`.`type`, `doc_list`.`sklad`, `doc_list`.`ok`, `doc_sklady`.`dnc` 42 FROM `doc_list` 43 LEFT JOIN `doc_sklady` ON `doc_sklady`.`id`=`doc_list`.`sklad` 44 WHERE `doc_list`.`id`='{$this->doc}'"); 45 $doc_info = $pres->fetch_assoc(); 46 if (!$doc_info) { 47 throw new Exception("Документ {$this->doc} не найден!"); 48 } 49 if ($doc_info['ok'] && (!$silent)) { 50 throw new Exception('Документ уже был проведён!'); 51 } 52 $pres->free(); 53 54 $res = $db->query("SELECT `doc_list_pos`.`tovar`, `doc_list_pos`.`cnt`, `doc_base_cnt`.`cnt` AS `sklad_cnt`, `doc_base`.`name`, `doc_base`.`proizv`, `doc_base`.`pos_type`, `doc_list_pos`.`id`, `doc_list_pos`.`page`, `doc_base`.`vc` 55 FROM `doc_list_pos` 56 INNER JOIN `doc_base` ON `doc_base`.`id`=`doc_list_pos`.`tovar` 57 LEFT JOIN `doc_base_cnt` ON `doc_base_cnt`.`id`=`doc_base`.`id` AND `doc_base_cnt`.`sklad`='{$doc_info['sklad']}' 58 WHERE `doc_list_pos`.`doc`='{$this->doc}' AND `doc_base`.`pos_type`='0'"); 59 $fail_text = ''; 60 while ($line = $res->fetch_array()) { 61 $sign = $line['page'] ? '-' : '+'; 62 $db->query("UPDATE `doc_base_cnt` SET `cnt`=`cnt` $sign '{$line['cnt']}' WHERE `id`='{$line['tovar']}' AND `sklad`='{$doc_info['sklad']}'"); 63 64 if ($line['page']) { 65 if (!$doc_info['dnc']) { 66 if ($line['cnt'] > $line['sklad_cnt']) { 67 $pos_name = composePosNameStr($line['tovar'], $line['vc'], $line['name'], $line['proizv']); 68 $fail_text .= "Мало товара '$pos_name' - есть:{$line['sklad_cnt']}, нужно:{$line['cnt']}. \n"; 69 continue; 70 } 71 } 72 if (!$doc_info['dnc'] && (!$silent)) { 73 $budet = getStoreCntOnDate($line['tovar'], $doc_info['sklad']); 74 if ($budet < 0) { 75 $pos_name = composePosNameStr($line['tovar'], $line['vc'], $line['name'], $line['proizv']); 76 $t = $budet + $line['cnt']; 77 $fail_text .= "Будет мало товара '$pos_name' - есть:$t, нужно:{$line['cnt']}. \n"; 78 continue; 79 } 80 } 81 } 82 83 if($fail_text) { 84 throw new Exception("Ошибка номенклатуры: \n".$fail_text); 85 } 86 // Если это первое поступление 87 if ($db->affected_rows == 0) { 88 $db->query("INSERT INTO `doc_base_cnt` (`id`, `sklad`, `cnt`) VALUES ('$line[0]', '$doc_info[3]', '{$line['cnt']}')"); 89 } 90 } 91 if ($silent) { 92 return; 93 } 94 $db->update('doc_list', $this->doc, 'ok', time() ); 95 $this->sentZEvent('apply'); 96 } 97 98 public function DocCancel() { 99 global $db; 100 $pres = $db->query("SELECT `doc_list`.`id`, `doc_list`.`date`, `doc_list`.`type`, `doc_list`.`sklad`, `doc_list`.`ok`, `doc_sklady`.`dnc` 101 FROM `doc_list` 102 LEFT JOIN `doc_sklady` ON `doc_sklady`.`id`=`doc_list`.`sklad` 103 WHERE `doc_list`.`id`='{$this->doc}'"); 104 $nx = $pres->fetch_row(); 105 if (!$nx) { 106 throw new Exception("Документ {$this->doc} не найден!"); 107 } 108 if (!$nx[4]) { 109 throw new Exception("Документ ещё не проведён!"); 110 } 111 112 $db->update('doc_list', $this->doc, 'ok', 0); 113 114 $res = $db->query("SELECT `doc_list_pos`.`tovar`, `doc_list_pos`.`cnt`, `doc_base_cnt`.`cnt`, `doc_base`.`name`, `doc_base`.`proizv`, 115 `doc_base`.`pos_type`, `doc_list_pos`.`page` 116 FROM `doc_list_pos` 117 LEFT JOIN `doc_base` ON `doc_base`.`id`=`doc_list_pos`.`tovar` 118 LEFT JOIN `doc_base_cnt` ON `doc_base_cnt`.`id`=`doc_base`.`id` AND `doc_base_cnt`.`sklad`='$nx[3]' 119 WHERE `doc_list_pos`.`doc`='{$this->doc}'"); 120 while ($nxt = $res->fetch_row()) { 121 if ($nxt[5] == 0) { 122 $sign = $nxt[6] ? '+' : '-'; 123 $db->query("UPDATE `doc_base_cnt` SET `cnt`=`cnt` $sign '$nxt[1]' WHERE `id`='$nxt[0]' AND `sklad`='$nx[3]'"); 124 } 125 } 126 } 127 128 public function Service() { 129 global $tmpl; 130 $tmpl->ajax = 1; 131 $opt = request('opt'); 132 $peopt = request('peopt'); 133 $pe_pos = request('pe_pos'); 134 include_once('include/doc.zapposeditor.php'); 135 $poseditor = new SZapPosEditor($this); 136 $poseditor->cost_id = $this->dop_data['cena']; 137 $poseditor->sklad_id = $this->doc_data['sklad']; 138 139 if (isAccess('doc_' . $this->doc_name, 'view')) { 140 141 // Json-вариант списка товаров 142 if ($peopt == 'jget') { 143 $doc_sum = $this->recalcSum(); 144 $str = "{ response: 'loadlist', content: [" . $poseditor->GetAllContent() . "], sum: '$doc_sum' }"; 145 $tmpl->addContent($str); 146 } else if ($peopt == 'jgetgroups') { 147 $doc_content = $poseditor->getGroupList(); 148 $tmpl->addContent($doc_content); 149 } 150 // Получение данных наименования 151 else if ($peopt == 'jgpi') { 152 $pe_pos = rcvint('pos'); 153 $tmpl->addContent($poseditor->GetPosInfo($pe_pos)); 154 } 155 // Json вариант добавления позиции 156 else if ($peopt == 'jadd') { 157 if (!isAccess('doc_sborka', 'edit')) { 158 throw new AccessException("Недостаточно привилегий"); 159 } 160 $pe_pos = rcvint('pos'); 161 $tmpl->setContent($poseditor->AddPos($pe_pos)); 162 } 163 // Json вариант удаления строки 164 else if ($peopt == 'jdel') { 165 if (!isAccess('doc_sborka', 'edit')) { 166 throw new AccessException("Недостаточно привилегий"); 167 } 168 $line_id = rcvint('line_id'); 169 $tmpl->setContent($poseditor->Removeline($line_id)); 170 } 171 // Json вариант обновления 172 else if ($peopt == 'jup') { 173 if (!isAccess('doc_sborka', 'edit')) { 174 throw new AccessException("Недостаточно привилегий"); 175 } 176 $line_id = rcvint('line_id'); 177 $value = request('value'); 178 $type = request('type'); 179 $tmpl->setContent($poseditor->UpdateLine($line_id, $type, $value)); 180 } 181 // Получение номенклатуры выбранной группы 182 else if ($peopt == 'jsklad') { 183 $group_id = rcvint('group_id'); 184 $str = "{ response: 'sklad_list', group: '$group_id', content: [" . $poseditor->GetSkladList($group_id) . "] }"; 185 $tmpl->setContent($str); 186 } 187 // Поиск по подстроке по складу 188 else if ($peopt == 'jsklads') { 189 $s = request('s'); 190 $str = "{ response: 'sklad_list', content: " . $poseditor->SearchSkladList($s) . " }"; 191 $tmpl->setContent($str); 192 } else if ($peopt == 'jsn') { 193 $action = request('a'); 194 $line_id = request('line'); 195 $data = request('data'); 196 $tmpl->setContent($poseditor->SerialNum($action, $line_id, $data)); 197 } else if ($opt == 'jdeldoc') { 198 $tmpl->setContent( $this->serviceDelDoc() ); 199 } 200 else if ($opt == 'jundeldoc') { 201 $tmpl->setContent($this->serviceUnDelDoc()); 202 } else { 203 throw new NotFoundException('Параметр не найден!'); 204 } 205 } 206 } 207 } -
web/include/pricewriter/csv.php
r63901be r4cefac0 18 18 // 19 19 20 namespace pricewriter; 21 20 22 /// Класс формирует прайс-лист в формате CSV 21 class PriceWriterCSV extends BasePriceWriter 22 { 23 var $divider; // Разделитель 24 var $shielder; // Экранирование строк 25 var $line; // Текущая строка 26 27 /// Конструктор 28 function __construct($db) 29 { 30 parent::__construct($db); 31 $this->divider = ","; 32 $this->shielder = '"'; 33 $this->line = 0; 34 } 35 36 /// Установить символ разделителя колонок 37 /// @param divider Символ разделителя колонок (,;:) 38 function setDivider($divider=",") { 39 $this->divider=$divider; 40 if($this->divider!=";" && $this->divider!=":") $this->divider=","; 41 } 42 43 /// Установить символ экранирования строк 44 /// @param shielder Символ экранирования строк ('"*) 45 function setShielder($shielder='"') { 46 $this->shielder=$shielder; 47 if($this->shielder!="'" && $this->shielder!="*") $this->shielder="\""; 48 } 49 50 /// Сформировать шапку прайса 51 function open() { 52 global $CONFIG; 53 header("Content-Type: text/csv; charset=utf-8"); 54 header("Content-Disposition: attachment; filename=price_list.csv;"); 55 for($i=0;$i<$this->column_count;$i++) { 56 if(@$CONFIG['site']['price_show_vc']) 57 echo $this->shielder."Код".$this->shielder.$this->divider; 58 echo $this->shielder."Название".$this->shielder.$this->divider.$this->shielder."Цена".$this->shielder; 59 if($i<($this->column_count-1)) echo $this->divider.$this->shielder.$this->shielder.$this->divider; 60 } 61 echo "\n"; 62 $this->line++; 63 } 64 65 /// Сформирвать тело прайса 66 function write($group=0) { 67 global $CONFIG; 68 $res=$this->db->query("SELECT `id`, `name`, `printname` FROM `doc_group` WHERE `pid`='$group' AND `hidelevel`='0' ORDER BY `id`"); 69 while($nxt=$res->fetch_row()) { 70 if($nxt[0]==0) continue; 71 if(is_array($this->view_groups)) 72 if(!in_array($nxt[0],$this->view_groups)) continue; 23 class csv extends BasePriceWriter { 73 24 74 $this->line++; 75 if(@$CONFIG['site']['price_show_vc']) 76 echo $this->divider; 77 echo $this->shielder.$nxt[1].$this->shielder; 78 echo"\n"; 79 $this->writepos($nxt[0], $nxt[2] ); 80 $this->write($nxt[0]); // рекурсия 25 var $divider; //< Разделитель 26 var $shielder; //< Экранирование строк 27 var $line; //< Текущая строка 81 28 82 } 83 } 84 85 /// Сформировать завершающий блок прайса 86 function close() { 87 global $CONFIG; 88 echo"\n\n"; 89 $this->line+=5; 90 if(@$CONFIG['site']['price_show_vc']) 91 echo $this->divider; 92 echo $this->shielder."Generated from MultiMag (http://multimag.tndproject.org), for http://".$CONFIG['site']['name'].$this->shielder; 93 $this->line++; 94 echo"\n"; 95 if(@$CONFIG['site']['price_show_vc']) 96 echo $this->divider; 97 echo $this->shielder."Прайс создан системой MultiMag (http://multimag.tndproject.org), специально для http://".$CONFIG['site']['name'].$this->shielder; 98 } 29 /// Конструктор 30 function __construct($db) { 31 parent::__construct($db); 32 $this->divider = ","; 33 $this->shielder = '"'; 34 $this->line = 0; 35 } 99 36 100 /// Сформировать строки прайса 101 function writepos($group=0) { 102 global $CONFIG; 103 $res=$this->db->query("SELECT `doc_base`.`id`, `doc_base`.`name`, `doc_base`.`cost_date` , `doc_base`.`proizv`, `doc_base`.`vc`, 37 /// Установить символ разделителя колонок 38 /// @param divider Символ разделителя колонок (,;:) 39 function setDivider($divider = ",") { 40 $this->divider = $divider; 41 if ($this->divider != ";" && $this->divider != ":") { 42 $this->divider = ","; 43 } 44 } 45 46 /// Установить символ экранирования строк 47 /// @param shielder Символ экранирования строк ('"*) 48 function setShielder($shielder = '"') { 49 $this->shielder = $shielder; 50 if ($this->shielder != "'" && $this->shielder != "*") { 51 $this->shielder = "\""; 52 } 53 } 54 55 /// Сформировать шапку прайса 56 function open() { 57 global $CONFIG; 58 header("Content-Type: text/csv; charset=utf-8"); 59 header("Content-Disposition: attachment; filename=price_list.csv;"); 60 for ($i = 0; $i < $this->column_count; $i++) { 61 if (@$CONFIG['site']['price_show_vc']) { 62 echo $this->shielder . "Код" . $this->shielder . $this->divider; 63 } 64 echo $this->shielder . "Название" . $this->shielder . $this->divider . $this->shielder . "Цена" . $this->shielder; 65 if ($i < ($this->column_count - 1)) { 66 echo $this->divider . $this->shielder . $this->shielder . $this->divider; 67 } 68 } 69 echo "\n"; 70 $this->line++; 71 } 72 73 /// Сформирвать тело прайса 74 function write($group = 0) { 75 global $CONFIG; 76 $res = $this->db->query("SELECT `id`, `name`, `printname` FROM `doc_group` WHERE `pid`='$group' AND `hidelevel`='0' ORDER BY `id`"); 77 while ($nxt = $res->fetch_row()) { 78 if ($nxt[0] == 0) { 79 continue; 80 } 81 if (is_array($this->view_groups)) { 82 if (!in_array($nxt[0], $this->view_groups)) { 83 continue; 84 } 85 } 86 87 $this->line++; 88 if (@$CONFIG['site']['price_show_vc']) { 89 echo $this->divider; 90 } 91 echo $this->shielder . $nxt[1] . $this->shielder; 92 echo"\n"; 93 $this->writepos($nxt[0], $nxt[2]); 94 $this->write($nxt[0]); // рекурсия 95 } 96 } 97 98 /// Сформировать завершающий блок прайса 99 function close() { 100 global $CONFIG; 101 echo"\n\n"; 102 $this->line+=5; 103 if (@$CONFIG['site']['price_show_vc']) { 104 echo $this->divider; 105 } 106 echo $this->shielder . "Generated from MultiMag (http://multimag.tndproject.org), for http://" . $CONFIG['site']['name'] . $this->shielder; 107 $this->line++; 108 echo"\n"; 109 if (@$CONFIG['site']['price_show_vc']) { 110 echo $this->divider; 111 } 112 echo $this->shielder . "Прайс создан системой MultiMag (http://multimag.tndproject.org), специально для http://" . $CONFIG['site']['name'] . $this->shielder; 113 } 114 115 /// Сформировать строки прайса 116 function writepos($group = 0) { 117 global $CONFIG; 118 $res = $this->db->query("SELECT `doc_base`.`id`, `doc_base`.`name`, `doc_base`.`cost_date` , `doc_base`.`proizv`, `doc_base`.`vc`, 104 119 `doc_base`.`cost` AS `base_price`, `doc_base`.`bulkcnt`, `doc_base`.`group` 105 120 FROM `doc_base` 106 121 LEFT JOIN `doc_group` ON `doc_base`.`group`=`doc_group`.`id` 107 122 WHERE `doc_base`.`group`='$group' AND `doc_base`.`hidden`='0' ORDER BY `doc_base`.`name`"); 108 $i=$cur_col=0; 109 $pc = PriceCalc::getInstance(); 110 while($nxt=$res->fetch_assoc()) { 111 if($cur_col>=$this->column_count){ 112 $cur_col=0; 113 echo"\n"; 114 } 115 else if($cur_col!=0) { 116 echo $this->divider.$this->shielder.$this->shielder.$this->divider; 117 } 123 $i = $cur_col = 0; 124 $pc = \PriceCalc::getInstance(); 125 while ($nxt = $res->fetch_assoc()) { 126 if ($cur_col >= $this->column_count) { 127 $cur_col = 0; 128 echo"\n"; 129 } else if ($cur_col != 0) { 130 echo $this->divider . $this->shielder . $this->shielder . $this->divider; 131 } 118 132 119 $c = $pc->getPosSelectedPriceValue($nxt['id'], $this->cost_id, $nxt); 120 if($c==0) continue; 121 if(($this->view_proizv)&&($nxt['proizv'])) $pr=" (".$nxt['proizv'].")"; else $pr=""; 122 if(@$CONFIG['site']['price_show_vc']) 123 echo $this->shielder.$nxt['vc'].$this->shielder.$this->divider; 124 echo $this->shielder.$nxt['name'].$pr.$this->shielder.$this->divider.$this->shielder.$c.$this->shielder; 133 $c = $pc->getPosSelectedPriceValue($nxt['id'], $this->cost_id, $nxt); 134 if ($c == 0) { 135 continue; 136 } 137 if (($this->view_proizv) && ($nxt['proizv'])) { 138 $pr = " (" . $nxt['proizv'] . ")"; 139 } else { 140 $pr = ""; 141 } 142 if (@$CONFIG['site']['price_show_vc']) { 143 echo $this->shielder . $nxt['vc'] . $this->shielder . $this->divider; 144 } 145 echo $this->shielder . $nxt['name'] . $pr . $this->shielder . $this->divider . $this->shielder . $c . $this->shielder; 125 146 126 $this->line++; 127 $i=1-$i; 128 $cur_col++; 129 } 130 echo"\n\n"; 131 } 147 $this->line++; 148 $i = 1 - $i; 149 $cur_col++; 150 } 151 echo"\n\n"; 152 } 153 132 154 } 133 ?> -
web/include/pricewriter/html.php
r63901be r4cefac0 17 17 // along with this program. If not, see <http://www.gnu.org/licenses/>. 18 18 // 19 namespace pricewriter; 19 20 20 21 /// Класс формирует прайс-лист в формате HTML 21 class PriceWriterHTML extends BasePriceWriter { 22 var $line; ///< Текущая строка 23 var $span; ///< Количество столбцов таблицы 22 class html extends BasePriceWriter { 24 23 25 /// Конструктор 26 function __construct($db) { 27 parent::__construct($db); 28 $this->line=0; 29 } 24 var $line; ///< Текущая строка 25 var $span; ///< Количество столбцов таблицы 30 26 31 /// Сформировать шапку прайса 32 function open() { 33 global $CONFIG; 34 echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"> 35 <html lang=\"ru\"> 36 <head> 37 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"> 27 /// Конструктор 38 28 39 <title>Прайс-лист: задание параметров</title> 40 <style type='text/css'> 41 body {font-size: 10px; color: #000; font-family: sans-serif; background-color: #fff} 42 h1 {font-weight: bold; font-size: 24px; font-family: sans-serif; color: #00f;} 43 h2 {font-weight: bold; font-size: 22px; font-family: sans-serif; color: #00f;} 44 h3 {font-weight: bold; font-size: 20px; font-family: sans-serif; color: #00f;} 45 h4 {font-weight: bold; font-size: 18px; font-family: sans-serif; color: #00f;} 46 h5 {font-weight: bold; font-size: 16px; font-family: sans-serif; color: #00f;} 47 h6 {font-weight: bold; font-size: 14px; font-family: sans-serif; color: #00f;} 48 table {border: #000 1px solid; border-collapse: collapse; width: 100%; font-size: 10px; border-spacing: 0;} 49 tr {background-color: #ffc;} 50 th { border: #000 1px solid; padding: 2px; text-align: center; font-weight: bold; color: #000; background-color: #f60;} 51 th.cost {background-color: #333; color: #fff;} 52 th.n1 {background-color: #f90;} 53 th.n2 {background-color: #fc0;} 54 th.n3 {background-color: #fd0;} 55 td { border: #000 1px solid; padding: 2px; } 56 tr:nth-child(odd) {background-color: #cff;} 57 .mini {font-size: 10px; text-align: center;} 58 .v2 {width: 30px;} 59 .np {page-break-after: always;} 60 </style> 61 </head> 62 <body> 63 <center>"; 64 $i=1; 65 if(is_array($CONFIG['site']['price_text'])) 66 foreach($CONFIG['site']['price_text'] as $text) { 67 echo"<h$i>".html_out($text)."</h$i>"; 68 $this->line++; 69 $i++; 70 } 29 function __construct($db) { 30 parent::__construct($db); 31 $this->line = 0; 32 } 71 33 72 $this->line++; 73 echo"</center><table><tr>"; 74 for($cur_col=0; $cur_col<$this->column_count; $cur_col++) { 75 if(@$CONFIG['site']['price_show_vc']) echo"<th class='cost'>Код</th>"; 76 echo"<th class='cost'>Наименование</th><th class='cost'>Цена</th>"; 77 } 78 echo"</tr>"; 79 if(@$CONFIG['site']['price_show_vc']) 80 $this->span = $this->column_count*3; 81 else $this->span = $this->column_count*2; 82 } 34 /// Сформировать шапку прайса 35 function open() { 36 global $CONFIG; 37 echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"> 38 <html lang=\"ru\"> 39 <head> 40 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"> 83 41 84 /// Сформирвать тело прайса 85 function write($group=0, $level=0) { 86 if($level>3) $level=3; 87 $res=$this->db->query("SELECT `id`, `name`, `printname` FROM `doc_group` WHERE `pid`='$group' AND `hidelevel`='0' ORDER BY `id`"); 88 while($nxt=$res->fetch_row()){ 89 if($nxt[0]==0) continue; 90 if(is_array($this->view_groups)) 91 if(!in_array($nxt[0],$this->view_groups)) continue; 42 <title>Прайс-лист: задание параметров</title> 43 <style type='text/css'> 44 body {font-size: 10px; color: #000; font-family: sans-serif; background-color: #fff} 45 h1 {font-weight: bold; font-size: 24px; font-family: sans-serif; color: #00f;} 46 h2 {font-weight: bold; font-size: 22px; font-family: sans-serif; color: #00f;} 47 h3 {font-weight: bold; font-size: 20px; font-family: sans-serif; color: #00f;} 48 h4 {font-weight: bold; font-size: 18px; font-family: sans-serif; color: #00f;} 49 h5 {font-weight: bold; font-size: 16px; font-family: sans-serif; color: #00f;} 50 h6 {font-weight: bold; font-size: 14px; font-family: sans-serif; color: #00f;} 51 table {border: #000 1px solid; border-collapse: collapse; width: 100%; font-size: 10px; border-spacing: 0;} 52 tr {background-color: #ffc;} 53 th { border: #000 1px solid; padding: 2px; text-align: center; font-weight: bold; color: #000; background-color: #f60;} 54 th.cost {background-color: #333; color: #fff;} 55 th.n1 {background-color: #f90;} 56 th.n2 {background-color: #fc0;} 57 th.n3 {background-color: #fd0;} 58 td { border: #000 1px solid; padding: 2px; } 59 tr:nth-child(odd) {background-color: #cff;} 60 .mini {font-size: 10px; text-align: center;} 61 .v2 {width: 30px;} 62 .np {page-break-after: always;} 63 </style> 64 </head> 65 <body> 66 <center>"; 67 $i = 1; 68 if (is_array($CONFIG['site']['price_text'])) { 69 foreach ($CONFIG['site']['price_text'] as $text) { 70 echo"<h$i>" . html_out($text) . "</h$i>"; 71 $this->line++; 72 $i++; 73 } 74 } 92 75 93 $this->line++; 94 echo"<tr><th class='n$level' colspan='{$this->span}'>".html_out($nxt[1])."</th></tr>"; 95 if($nxt[2]) $nxt[2] .= ' '; 96 $this->writepos($nxt[0], $nxt[2]); 97 $this->write($nxt[0], $level+1); // рекурсия 76 $this->line++; 77 echo"</center><table><tr>"; 78 for ($cur_col = 0; $cur_col < $this->column_count; $cur_col++) { 79 if (@$CONFIG['site']['price_show_vc']) { 80 echo"<th class='cost'>Код</th>"; 81 } 82 echo"<th class='cost'>Наименование</th><th class='cost'>Цена</th>"; 83 } 84 echo"</tr>"; 85 if (@$CONFIG['site']['price_show_vc']) { 86 $this->span = $this->column_count * 3; 87 } else { 88 $this->span = $this->column_count * 2; 89 } 90 } 98 91 99 } 100 } 92 /// Сформирвать тело прайса 93 function write($group = 0, $level = 0) { 94 if ($level > 3) { 95 $level = 3; 96 } 97 $res = $this->db->query("SELECT `id`, `name`, `printname` FROM `doc_group` WHERE `pid`='$group' AND `hidelevel`='0' ORDER BY `id`"); 98 while ($nxt = $res->fetch_row()) { 99 if ($nxt[0] == 0) { 100 continue; 101 } 102 if (is_array($this->view_groups)) { 103 if (!in_array($nxt[0], $this->view_groups)) { 104 continue; 105 } 106 } 101 107 102 /// Сформировать завершающий блок прайса 103 function close() { 104 global $CONFIG; 105 echo "<tr><td colspan='{$this->span}' class='mini'>Generated from MultiMag (<a href='http://multimag.tndproject.org'>http://multimag.tndproject.org</a>), for <a href='http://{$CONFIG['site']['name']}'>http://{$CONFIG['site']['name']}</a><br>Прайс создан системой MultiMag (<a href='http://multimag.tndproject.org'>http://multimag.tndproject.org</a>), специально для <a href='http://{$CONFIG['site']['name']}'>http://{$CONFIG['site']['name']}</a></td></tr></table>"; 106 } 108 $this->line++; 109 echo"<tr><th class='n$level' colspan='{$this->span}'>" . html_out($nxt[1]) . "</th></tr>"; 110 if ($nxt[2]) { 111 $nxt[2] .= ' '; 112 } 113 $this->writepos($nxt[0], $nxt[2]); 114 $this->write($nxt[0], $level + 1); // рекурсия 115 } 116 } 107 117 108 /// Сформировать строки прайса 109 function writepos($group=0, $group_name='') { 110 global $CONFIG; 111 $res = $this->db->query("SELECT `doc_base`.`id`, `doc_base`.`name`, `doc_base`.`cost_date` , `doc_base`.`proizv`, `doc_base`.`vc`, 112 `doc_base`.`cost` AS `base_price`, `doc_base`.`bulkcnt`, `doc_base`.`group` 113 FROM `doc_base` 114 LEFT JOIN `doc_group` ON `doc_base`.`group`=`doc_group`.`id` 115 WHERE `doc_base`.`group`='$group' AND `doc_base`.`hidden`='0' ORDER BY `doc_base`.`name`"); 116 $i = $cur_col = 0; 117 118 if(@$CONFIG['site']['grey_price_days']) 119 $cce_time = $CONFIG['site']['grey_price_days'] * 60*60*24; 120 121 $pc = PriceCalc::getInstance(); 122 while($nxt=$res->fetch_assoc()) { 123 if($cur_col>=$this->column_count) { 124 $cur_col=0; 125 echo"<tr>"; 126 } 127 $cce = ''; 128 if(@$CONFIG['site']['grey_price_days']) { 129 if( strtotime($nxt['cost_date']) < $cce_time ) 130 $cce = ' style=\'color:#888\''; 131 } 132 $c = $pc->getPosSelectedPriceValue($nxt['id'], $this->cost_id, $nxt); 133 if($c==0) continue; 134 if(($this->view_proizv)&&($nxt['proizv'])) $pr=" (".$nxt['proizv'].")"; else $pr=""; 135 if(@$CONFIG['site']['price_show_vc']) 136 echo"<td>".html_out($nxt['vc'])."</td>"; 137 echo "<td>".html_out($group_name.$nxt['name'].$pr)."</td><td{$cce}>".$c."</td>"; 118 /// Сформировать завершающий блок прайса 119 function close() { 120 global $CONFIG; 121 echo "<tr><td colspan='{$this->span}' class='mini'>Generated from MultiMag (<a href='http://multimag.tndproject.org'>http://multimag.tndproject.org</a>), for <a href='http://{$CONFIG['site']['name']}'>http://{$CONFIG['site']['name']}</a><br>Прайс создан системой MultiMag (<a href='http://multimag.tndproject.org'>http://multimag.tndproject.org</a>), специально для <a href='http://{$CONFIG['site']['name']}'>http://{$CONFIG['site']['name']}</a></td></tr></table>"; 122 } 138 123 139 $this->line++; 140 $i=1-$i; 141 $cur_col++; 142 } 143 echo"</tr>"; 144 } 124 /// Сформировать строки прайса 125 function writepos($group = 0, $group_name = '') { 126 global $CONFIG; 127 $res = $this->db->query("SELECT `doc_base`.`id`, `doc_base`.`name`, `doc_base`.`cost_date` , `doc_base`.`proizv`, `doc_base`.`vc`, 128 `doc_base`.`cost` AS `base_price`, `doc_base`.`bulkcnt`, `doc_base`.`group` 129 FROM `doc_base` 130 LEFT JOIN `doc_group` ON `doc_base`.`group`=`doc_group`.`id` 131 WHERE `doc_base`.`group`='$group' AND `doc_base`.`hidden`='0' ORDER BY `doc_base`.`name`"); 132 $i = $cur_col = 0; 133 134 if (@$CONFIG['site']['grey_price_days']) { 135 $cce_time = $CONFIG['site']['grey_price_days'] * 60 * 60 * 24; 136 } 137 138 $pc = \PriceCalc::getInstance(); 139 while ($nxt = $res->fetch_assoc()) { 140 if ($cur_col >= $this->column_count) { 141 $cur_col = 0; 142 echo"<tr>"; 143 } 144 $cce = ''; 145 if (@$CONFIG['site']['grey_price_days']) { 146 if (strtotime($nxt['cost_date']) < $cce_time) { 147 $cce = ' style=\'color:#888\''; 148 } 149 } 150 $c = $pc->getPosSelectedPriceValue($nxt['id'], $this->cost_id, $nxt); 151 if ($c == 0) { 152 continue; 153 } 154 if (($this->view_proizv) && ($nxt['proizv'])) { 155 $pr = " (" . $nxt['proizv'] . ")"; 156 } else { 157 $pr = ""; 158 } 159 if (@$CONFIG['site']['price_show_vc']) { 160 echo"<td>" . html_out($nxt['vc']) . "</td>"; 161 } 162 echo "<td>" . html_out($group_name . $nxt['name'] . $pr) . "</td><td{$cce}>" . $c . "</td>"; 163 164 $this->line++; 165 $i = 1 - $i; 166 $cur_col++; 167 } 168 echo"</tr>"; 169 } 170 145 171 } 146 ?> -
web/include/pricewriter/pdf.php
r63901be r4cefac0 17 17 // along with this program. If not, see <http://www.gnu.org/licenses/>. 18 18 // 19 19 namespace pricewriter; 20 20 21 21 /// Класс формирует прайс-лист в формате PDF 22 class PriceWriterPDF extends BasePriceWriter 23 { 24 var $pdf; 25 26 /// Конструктор 27 function __construct($db) { 28 parent::__construct($db); 29 $this->line = 0; 30 } 31 32 /// Сформировать шапку прайса 33 function open() { 34 global $CONFIG; 35 require_once('fpdf/fpdf_mysql.php'); 36 $this->pdf=new PDF_MySQL_Table(); 37 $this->pdf->Open(); 38 $this->pdf->SetAutoPageBreak(1,12); 39 $this->pdf->AddFont('Arial','','arial.php'); 40 $this->pdf->tMargin=5; 41 $this->pdf->AddPage(); 42 if(@$CONFIG['site']['doc_header']) { 43 $header_img=str_replace('{FN}', $CONFIG['site']['default_firm'], $CONFIG['site']['doc_header']); 44 $this->pdf->Image($header_img,8,10, 190); 45 $this->pdf->Sety(54); 46 } 22 class pdf extends BasePriceWriter { 47 23 48 $i=0; 49 if(is_array($CONFIG['site']['price_text'])) 50 foreach($CONFIG['site']['price_text'] as $text) { 51 $this->pdf->SetFont('Arial','',20-($i*4)); 52 $str = iconv('UTF-8', 'windows-1251', $text); 53 $this->pdf->Cell(0,7-$i,$str,0,1,'C'); 54 $i++; 55 if($i>4) $i=4; 56 } 24 var $pdf; 57 25 58 $this->pdf->SetTextColor(0,0,255); 59 $this->pdf->SetFont('','U',14); 60 $str = 'Прайс загружен с сайта http://'.$CONFIG['site']['name']; 61 $str = iconv('UTF-8', 'windows-1251', $str); 62 $this->pdf->Cell(0,6,$str,0,1,'C',0,'http://'.$CONFIG['site']['name']); 63 $this->pdf->SetFont('','',10); 64 $this->pdf->SetTextColor(0); 65 $str = 'При заказе через сайт может быть предоставлена скидка!'; 66 $str = iconv('UTF-8', 'windows-1251', $str); 67 $this->pdf->Cell(0,5,$str,0,1,'C'); 26 /// Конструктор 27 function __construct($db) { 28 parent::__construct($db); 29 $this->line = 0; 30 } 68 31 69 $dt=date("d.m.Y"); 70 $str = 'Цены действительны на дату: '.$dt.'.'; 71 if(@$CONFIG['site']['grey_price_days']) 72 $str .= ' Цены, выделенные серым цветом, необходимо уточнять.'; 73 $str = iconv('UTF-8', 'windows-1251', $str); 74 $this->pdf->Cell(0,4,$str,0,1,'C'); 32 /// Сформировать шапку прайса 33 function open() { 34 global $CONFIG; 35 require_once('fpdf/fpdf_mysql.php'); 36 $this->pdf = new \PDF_MySQL_Table(); 37 $this->pdf->Open(); 38 $this->pdf->SetAutoPageBreak(1, 12); 39 $this->pdf->AddFont('Arial', '', 'arial.php'); 40 $this->pdf->tMargin = 5; 41 $this->pdf->AddPage(); 42 if (@$CONFIG['site']['doc_header']) { 43 $header_img = str_replace('{FN}', $CONFIG['site']['default_firm'], $CONFIG['site']['doc_header']); 44 $this->pdf->Image($header_img, 8, 10, 190); 45 $this->pdf->Sety(54); 46 } 75 47 76 if(is_array($this->view_groups)) { 77 $this->pdf->Ln(3); 78 $this->pdf->SetFont('','',14); 79 $this->pdf->SetTextColor(255,24,24); 80 $this->str = 'Прайс содержит неполный список позиций, в соответствии с выбранными критериями при его загрузке с сайта.'; 81 $this->str = iconv('UTF-8', 'windows-1251', $str); 82 $this->pdf->MultiCell(0,4,$str,0,'C'); 83 } 84 $this->pdf->Ln(6); 48 $i = 0; 49 if (is_array($CONFIG['site']['price_text'])) { 50 foreach ($CONFIG['site']['price_text'] as $text) { 51 $this->pdf->SetFont('Arial', '', 20 - ($i * 4)); 52 $str = iconv('UTF-8', 'windows-1251', $text); 53 $this->pdf->Cell(0, 7 - $i, $str, 0, 1, 'C'); 54 $i++; 55 if ($i > 4) { 56 $i = 4; 57 } 58 } 59 } 85 60 86 $this->pdf->SetTextColor(0); 87 } 61 $this->pdf->SetTextColor(0, 0, 255); 62 $this->pdf->SetFont('', 'U', 14); 63 $str = 'Прайс загружен с сайта http://' . $CONFIG['site']['name']; 64 $str = iconv('UTF-8', 'windows-1251', $str); 65 $this->pdf->Cell(0, 6, $str, 0, 1, 'C', 0, 'http://' . $CONFIG['site']['name']); 66 $this->pdf->SetFont('', '', 10); 67 $this->pdf->SetTextColor(0); 68 $str = 'При заказе через сайт может быть предоставлена скидка!'; 69 $str = iconv('UTF-8', 'windows-1251', $str); 70 $this->pdf->Cell(0, 5, $str, 0, 1, 'C'); 88 71 89 /// Сформирвать тело прайса 90 /// TODO: здесь количество столбцов задаётся в конфиге, а в других прайсах - параметр самого прайса. привести к единообразию 91 function write() { 92 global $CONFIG; 93 if(!isset($CONFIG['site']['price_width_vc'])) $CONFIG['site']['price_width_vc']=0; 94 if(!$CONFIG['site']['price_col_cnt']) $CONFIG['site']['price_col_cnt']=2; 95 if(!$CONFIG['site']['price_width_cost']) $CONFIG['site']['price_width_cost']=16; 96 if(!$CONFIG['site']['price_width_name']) 97 { 98 $CONFIG['site']['price_width_name']=(194-$CONFIG['site']['price_width_cost']*$CONFIG['site']['price_col_cnt']-$CONFIG['site']['price_width_vc']*$CONFIG['site']['price_col_cnt']-$CONFIG['site']['price_col_cnt']*2)/$CONFIG['site']['price_col_cnt']; 99 settype($CONFIG['site']['price_width_name'],'int'); 100 } 72 $dt = date("d.m.Y"); 73 $str = 'Цены действительны на дату: ' . $dt . '.'; 74 if (@$CONFIG['site']['grey_price_days']) { 75 $str .= ' Цены, выделенные серым цветом, необходимо уточнять.'; 76 } 77 $str = iconv('UTF-8', 'windows-1251', $str); 78 $this->pdf->Cell(0, 4, $str, 0, 1, 'C'); 101 79 102 $this->pdf->numCols=$CONFIG['site']['price_col_cnt']; 80 if (is_array($this->view_groups)) { 81 $this->pdf->Ln(3); 82 $this->pdf->SetFont('', '', 14); 83 $this->pdf->SetTextColor(255, 24, 24); 84 $str = 'Прайс содержит неполный список позиций, в соответствии с выбранными критериями при его загрузке с сайта.'; 85 $str = iconv('UTF-8', 'windows-1251', $str); 86 $this->pdf->MultiCell(0, 4, $str, 0, 'C'); 87 } 88 $this->pdf->Ln(6); 103 89 104 if($CONFIG['site']['price_show_vc']) 105 { 106 $str = iconv('UTF-8', 'windows-1251', 'Код'); 107 $this->pdf->AddCol('vc', $CONFIG['site']['price_width_vc'], $str,''); 108 } 109 110 $str = iconv('UTF-8', 'windows-1251', 'Наименование'); 111 $this->pdf->AddCol('name', $CONFIG['site']['price_width_name'], $str,''); 112 $str = iconv('UTF-8', 'windows-1251', 'Цена'); 113 $this->pdf->AddCol('cost', $CONFIG['site']['price_width_cost'],$str,'R'); 114 $prop=array('HeaderColor'=>array(255,150,100), 115 'color1'=>array(210,245,255), 116 'color2'=>array(255,255,210), 117 'padding'=>1, 118 'cost_id'=>$this->cost_id); 119 if(is_array($this->view_groups)) 120 { 121 $prop['groups']=$this->view_groups; 122 } 90 $this->pdf->SetTextColor(0); 91 } 92 93 /// Сформирвать тело прайса 94 /// TODO: здесь количество столбцов задаётся в конфиге, а в других прайсах - параметр самого прайса. привести к единообразию 95 function write() { 96 global $CONFIG; 97 if (!isset($CONFIG['site']['price_width_vc'])) { 98 $CONFIG['site']['price_width_vc'] = 0; 99 } 100 if (!$CONFIG['site']['price_col_cnt']) { 101 $CONFIG['site']['price_col_cnt'] = 2; 102 } 103 if (!$CONFIG['site']['price_width_cost']) { 104 $CONFIG['site']['price_width_cost'] = 16; 105 } 106 if (!$CONFIG['site']['price_width_name']) { 107 $CONFIG['site']['price_width_name'] = (194 - $CONFIG['site']['price_width_cost'] * $CONFIG['site']['price_col_cnt'] - $CONFIG['site']['price_width_vc'] * $CONFIG['site']['price_col_cnt'] - $CONFIG['site']['price_col_cnt'] * 2) / $CONFIG['site']['price_col_cnt']; 108 settype($CONFIG['site']['price_width_name'], 'int'); 109 } 110 111 $this->pdf->numCols = $CONFIG['site']['price_col_cnt']; 112 113 if ($CONFIG['site']['price_show_vc']) { 114 $str = iconv('UTF-8', 'windows-1251', 'Код'); 115 $this->pdf->AddCol('vc', $CONFIG['site']['price_width_vc'], $str, ''); 116 } 117 118 $str = iconv('UTF-8', 'windows-1251', 'Наименование'); 119 $this->pdf->AddCol('name', $CONFIG['site']['price_width_name'], $str, ''); 120 $str = iconv('UTF-8', 'windows-1251', 'Цена'); 121 $this->pdf->AddCol('cost', $CONFIG['site']['price_width_cost'], $str, 'R'); 122 $prop = array('HeaderColor' => array(255, 150, 100), 123 'color1' => array(210, 245, 255), 124 'color2' => array(255, 255, 210), 125 'padding' => 1, 126 'cost_id' => $this->cost_id); 127 if (is_array($this->view_groups)) { 128 $prop['groups'] = $this->view_groups; 129 } 123 130 124 131 125 132 126 if($this->view_proizv) $proizv='`doc_base`.`proizv`'; 127 else $proizv="''"; 133 if ($this->view_proizv) { 134 $proizv = '`doc_base`.`proizv`'; 135 } else { 136 $proizv = "''"; 137 } 128 138 129 139 $this->pdf->Table("SELECT `doc_base`.`name`, $proizv, `doc_base`.`id` AS `pos_id` , `doc_base`.`cost_date`, `class_unit`.`rus_name1` AS `units_name`, `doc_base`.`vc` 130 140 FROM `doc_base` 131 LEFT JOIN `class_unit` ON `class_unit`.`id`=`doc_base`.`unit` 132 ",$prop); 133 } 134 135 /// Сформировать завершающий блок прайса 136 function close() { 137 $this->pdf->Output(); 138 } 141 LEFT JOIN `class_unit` ON `class_unit`.`id`=`doc_base`.`unit` ", $prop); 142 } 139 143 140 /// Сформировать строки прайса 141 function writepos($group=0, $group_name='') 142 { 143 144 } 145 }; 144 /// Сформировать завершающий блок прайса 145 function close() { 146 $this->pdf->Output(); 147 } 146 148 147 ?> 149 /// Сформировать строки прайса 150 function writepos($group = 0, $group_name = '') { 151 152 } 153 154 } -
web/include/pricewriter/xls.php
r63901be r4cefac0 17 17 // along with this program. If not, see <http://www.gnu.org/licenses/>. 18 18 // 19 19 namespace pricewriter; 20 20 21 21 /// Класс формирует прайс-лист в формате XLS 22 /// TODO: сделать подсветку устаревших цен серым 23 class PriceWriterXLS extends BasePriceWriter 24 { 25 var $workbook; // книга XLS 26 var $worksheet; // Лист XLS 27 var $line; // Текущая строка 28 var $format_line; // формат для строк наименований прайса 29 var $a_format_line; // формат для строк наименований прайса для серой цены 30 var $format_group; // формат для строк групп прайса 31 32 /// Конструктор 33 function __construct($db) { 34 parent::__construct($db); 35 $this->line = 0; 36 } 37 38 /// Сформировать шапку прайса 39 function open() { 40 require_once('include/Spreadsheet/Excel/Writer.php'); 41 global $CONFIG; 42 $this->workbook = new Spreadsheet_Excel_Writer(); 43 // sending HTTP headers 44 $this->workbook->send('price.xls'); 45 46 // Creating a worksheet 47 $this->worksheet =& $this->workbook->addWorksheet($CONFIG['site']['name']); 48 49 $this->format_footer=& $this->workbook->addFormat(); 50 $this->format_footer->SetAlign('center'); 51 $this->format_footer->setColor(39); 52 $this->format_footer->setFgColor(27); 53 $this->format_footer->SetSize(8); 54 55 $this->format_line=array(); 56 $this->format_line[0]=& $this->workbook->addFormat(); 57 $this->format_line[0]->setColor(0); 58 $this->format_line[0]->setFgColor(26); 59 $this->format_line[0]->SetSize(12); 60 $this->format_line[1]=& $this->workbook->addFormat(); 61 $this->format_line[1]->setColor(0); 62 $this->format_line[1]->setFgColor(41); 63 $this->format_line[1]->SetSize(12); 64 65 // для серых цен 66 $this->a_format_line=array(); 67 $this->a_format_line[0]=& $this->workbook->addFormat(); 68 $this->a_format_line[0]->setColor('gray'); 69 $this->a_format_line[0]->setFgColor(26); 70 $this->a_format_line[0]->SetSize(12); 71 $this->a_format_line[1]=& $this->workbook->addFormat(); 72 $this->a_format_line[1]->setColor('gray'); 73 $this->a_format_line[1]->setFgColor(41); 74 $this->a_format_line[1]->SetSize(12); 75 76 $this->format_group=array(); 77 $this->format_group[0]=& $this->workbook->addFormat(); 78 $this->format_group[0]->setColor(0); 79 $this->format_group[0]->setFgColor(53); 80 $this->format_group[0]->SetSize(14); 81 $this->format_group[0]->SetAlign('center'); 82 $this->format_group[1]=& $this->workbook->addFormat(); 83 $this->format_group[1]->setColor(0); 84 $this->format_group[1]->setFgColor(52); 85 $this->format_group[1]->SetSize(14); 86 $this->format_group[1]->SetAlign('center'); 87 $this->format_group[2]=& $this->workbook->addFormat(); 88 $this->format_group[2]->setColor(0); 89 $this->format_group[2]->setFgColor(51); 90 $this->format_group[2]->SetSize(14); 91 $this->format_group[2]->SetAlign('center'); 92 93 94 $format_title =& $this->workbook->addFormat(); 95 $format_title->setBold(); 96 $format_title->setColor('blue'); 97 $format_title->setPattern(1); 98 $format_title->setFgColor('yellow'); 99 $format_title->SetSize(26); 100 101 $format_info =& $this->workbook->addFormat(); 102 //$format_info->setBold(); 103 $format_info->setColor('blue'); 104 $format_info->setPattern(1); 105 $format_info->setFgColor('yellow'); 106 $format_info->SetSize(16); 107 108 $format_header =& $this->workbook->addFormat(); 109 $format_header->setBold(); 110 $format_header->setColor(1); 111 $format_header->setPattern(1); 112 $format_header->setFgColor(63); 113 $format_header->SetSize(16); 114 $format_header->SetAlign('center'); 115 $format_header->SetAlign('vcenter'); 116 // Настройка ширины столбцов 117 118 if(@$CONFIG['site']['price_show_vc']) 119 $column_width = array(8, 8, 112, 15, 15); 120 else $column_width = array(8, 120, 15, 15); 121 foreach($column_width as $id=> $width) 122 $this->worksheet->setColumn($id,$id,$width); 123 $this->column_count = count($column_width); 124 125 if(is_array($CONFIG['site']['price_text'])) 126 foreach($CONFIG['site']['price_text'] as $text) { 127 $str = iconv('UTF-8', 'windows-1251', $text); 128 $this->worksheet->setRow($this->line,30); 129 $this->worksheet->write($this->line, 0, $str, $format_title); 130 $this->worksheet->setMerge($this->line,0,$this->line,$this->column_count-1); 131 $this->line++; 132 } 133 134 $str = 'Прайс загружен с сайта http://'.$CONFIG['site']['name']; 135 $str = iconv('UTF-8', 'windows-1251', $str); 136 $this->worksheet->write($this->line, 0, $str, $format_info); 137 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count-1); 138 $this->line++; 139 140 $str = 'При заказе через сайт может быть предоставлена скидка!'; 141 $str = iconv('UTF-8', 'windows-1251', $str); 142 $this->worksheet->write($this->line, 0, $str, $format_info); 143 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count-1); 144 $this->line++; 145 146 $dt=date("d.m.Y"); 147 $str = 'Цены действительны на дату: '.$dt.'.'; 148 if(@$CONFIG['site']['grey_price_days']) 149 $str .= ' Цены, выделенные серым цветом, необходимо уточнять.'; 150 $str = iconv('UTF-8', 'windows-1251', $str); 151 $this->worksheet->write($this->line, 0, $str, $format_info); 152 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count-1); 153 $this->line++; 154 155 if(is_array($this->view_groups)){ 156 $this->line++; 157 //$this->Ln(3); 158 //$this->SetFont('','',14); 159 //$this->SetTextColor(255,24,24); 160 $str = 'Прайс содержит неполный список позиций, в соответствии с выбранными критериями при его загрузке с сайта.'; 161 $str = iconv('UTF-8', 'windows-1251', $str); 162 $this->worksheet->write($this->line, 0, $str, $format_info); 163 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count-1); 164 $this->line++; 165 } 166 167 $this->line++; 168 $this->worksheet->write(8, 8, ' '); 169 if(@$CONFIG['site']['price_show_vc']) 170 $headers = array("N", "Код", "Наименование", "Наличие", "Цена"); 171 else $headers = array("N", "Наименование", "Наличие", "Цена"); 172 foreach($headers as $id => $item) 173 $headers[$id] = iconv('UTF-8', 'windows-1251', $item); 174 $this->worksheet->writeRow($this->line,0,$headers,$format_header); 175 $this->line++; 176 } 177 178 /// Сформирвать тело прайса 179 function write($group=0, $level=0) { 180 if($level>2) $level=2; 181 $res=$this->db->query("SELECT `id`, `name`, `printname` FROM `doc_group` WHERE `pid`='$group' AND `hidelevel`='0' ORDER BY `id`"); 182 while($nxt=$res->fetch_row()) { 183 if($nxt[0]==0) continue; 184 if(is_array($this->view_groups)) 185 if(!in_array($nxt[0],$this->view_groups)) continue; 186 187 $str = iconv('UTF-8', 'windows-1251', $nxt[1]); 188 $this->worksheet->write($this->line, 0, $str, $this->format_group[$level]); 189 $this->worksheet->setMerge($this->line,0,$this->line,$this->column_count-1); 190 $this->line++; 191 192 $this->writepos($nxt[0], $nxt[2] ); 193 $this->write($nxt[0], $level+1); 194 195 } 196 } 197 198 /// Сформировать завершающий блок прайса 199 function close() { 200 global $CONFIG; 201 $this->line+=5; 202 $this->worksheet->write($this->line, 0, "Generated from MultiMag (http://multimag.tndproject.org) via PHPExcelWriter, for http://".$CONFIG['site']['name'], $this->format_footer); 203 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count-1); 204 $this->line++; 205 $str = iconv('UTF-8', 'windows-1251', "Прайс создан системой MultiMag (http://multimag.tndproject.org), специально для http://".$CONFIG['site']['name']); 206 $this->worksheet->write($this->line, 0, $str, $this->format_footer); 207 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count-1); 208 $this->workbook->close(); 209 } 210 211 /// Сформировать строки прайса 212 function writepos($group=0, $group_name=''){ 213 global $CONFIG; 214 215 $cnt_where=@$CONFIG['site']['vitrina_sklad']?(" AND `doc_base_cnt`.`sklad`=".intval($CONFIG['site']['vitrina_sklad'])." "):''; 216 217 $res = $this->db->query("SELECT `doc_base`.`id`, `doc_base`.`name`, `doc_base`.`cost_date` , `doc_base`.`proizv`, `doc_base`.`vc`, 22 class xls extends BasePriceWriter { 23 24 var $workbook; // книга XLS 25 var $worksheet; // Лист XLS 26 var $line; // Текущая строка 27 var $format_line; // формат для строк наименований прайса 28 var $a_format_line; // формат для строк наименований прайса для серой цены 29 var $format_group; // формат для строк групп прайса 30 31 /// Конструктор 32 33 function __construct($db) { 34 parent::__construct($db); 35 $this->line = 0; 36 } 37 38 /// Сформировать шапку прайса 39 function open() { 40 require_once('include/Spreadsheet/Excel/Writer.php'); 41 global $CONFIG; 42 $this->workbook = new \Spreadsheet_Excel_Writer(); 43 // sending HTTP headers 44 $this->workbook->send('price.xls'); 45 46 // Creating a worksheet 47 $this->worksheet = & $this->workbook->addWorksheet($CONFIG['site']['name']); 48 49 $this->format_footer = & $this->workbook->addFormat(); 50 $this->format_footer->SetAlign('center'); 51 $this->format_footer->setColor(39); 52 $this->format_footer->setFgColor(27); 53 $this->format_footer->SetSize(8); 54 55 $this->format_line = array(); 56 $this->format_line[0] = & $this->workbook->addFormat(); 57 $this->format_line[0]->setColor(0); 58 $this->format_line[0]->setFgColor(26); 59 $this->format_line[0]->SetSize(12); 60 $this->format_line[1] = & $this->workbook->addFormat(); 61 $this->format_line[1]->setColor(0); 62 $this->format_line[1]->setFgColor(41); 63 $this->format_line[1]->SetSize(12); 64 65 // для серых цен 66 $this->a_format_line = array(); 67 $this->a_format_line[0] = & $this->workbook->addFormat(); 68 $this->a_format_line[0]->setColor('gray'); 69 $this->a_format_line[0]->setFgColor(26); 70 $this->a_format_line[0]->SetSize(12); 71 $this->a_format_line[1] = & $this->workbook->addFormat(); 72 $this->a_format_line[1]->setColor('gray'); 73 $this->a_format_line[1]->setFgColor(41); 74 $this->a_format_line[1]->SetSize(12); 75 76 $this->format_group = array(); 77 $this->format_group[0] = & $this->workbook->addFormat(); 78 $this->format_group[0]->setColor(0); 79 $this->format_group[0]->setFgColor(53); 80 $this->format_group[0]->SetSize(14); 81 $this->format_group[0]->SetAlign('center'); 82 $this->format_group[1] = & $this->workbook->addFormat(); 83 $this->format_group[1]->setColor(0); 84 $this->format_group[1]->setFgColor(52); 85 $this->format_group[1]->SetSize(14); 86 $this->format_group[1]->SetAlign('center'); 87 $this->format_group[2] = & $this->workbook->addFormat(); 88 $this->format_group[2]->setColor(0); 89 $this->format_group[2]->setFgColor(51); 90 $this->format_group[2]->SetSize(14); 91 $this->format_group[2]->SetAlign('center'); 92 93 94 $format_title = & $this->workbook->addFormat(); 95 $format_title->setBold(); 96 $format_title->setColor('blue'); 97 $format_title->setPattern(1); 98 $format_title->setFgColor('yellow'); 99 $format_title->SetSize(26); 100 101 $format_info = & $this->workbook->addFormat(); 102 //$format_info->setBold(); 103 $format_info->setColor('blue'); 104 $format_info->setPattern(1); 105 $format_info->setFgColor('yellow'); 106 $format_info->SetSize(16); 107 108 $format_header = & $this->workbook->addFormat(); 109 $format_header->setBold(); 110 $format_header->setColor(1); 111 $format_header->setPattern(1); 112 $format_header->setFgColor(63); 113 $format_header->SetSize(16); 114 $format_header->SetAlign('center'); 115 $format_header->SetAlign('vcenter'); 116 // Настройка ширины столбцов 117 118 if (@$CONFIG['site']['price_show_vc']) { 119 $column_width = array(8, 8, 112, 15, 15); 120 } else { 121 $column_width = array(8, 120, 15, 15); 122 } 123 foreach ($column_width as $id => $width) { 124 $this->worksheet->setColumn($id, $id, $width); 125 } 126 $this->column_count = count($column_width); 127 128 if (is_array($CONFIG['site']['price_text'])) { 129 foreach ($CONFIG['site']['price_text'] as $text) { 130 $str = iconv('UTF-8', 'windows-1251', $text); 131 $this->worksheet->setRow($this->line, 30); 132 $this->worksheet->write($this->line, 0, $str, $format_title); 133 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count - 1); 134 $this->line++; 135 } 136 } 137 138 $str = 'Прайс загружен с сайта http://' . $CONFIG['site']['name']; 139 $str = iconv('UTF-8', 'windows-1251', $str); 140 $this->worksheet->write($this->line, 0, $str, $format_info); 141 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count - 1); 142 $this->line++; 143 144 $str = 'При заказе через сайт может быть предоставлена скидка!'; 145 $str = iconv('UTF-8', 'windows-1251', $str); 146 $this->worksheet->write($this->line, 0, $str, $format_info); 147 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count - 1); 148 $this->line++; 149 150 $dt = date("d.m.Y"); 151 $str = 'Цены действительны на дату: ' . $dt . '.'; 152 if (@$CONFIG['site']['grey_price_days']) { 153 $str .= ' Цены, выделенные серым цветом, необходимо уточнять.'; 154 } 155 $str = iconv('UTF-8', 'windows-1251', $str); 156 $this->worksheet->write($this->line, 0, $str, $format_info); 157 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count - 1); 158 $this->line++; 159 160 if (is_array($this->view_groups)) { 161 $this->line++; 162 //$this->Ln(3); 163 //$this->SetFont('','',14); 164 //$this->SetTextColor(255,24,24); 165 $str = 'Прайс содержит неполный список позиций, в соответствии с выбранными критериями при его загрузке с сайта.'; 166 $str = iconv('UTF-8', 'windows-1251', $str); 167 $this->worksheet->write($this->line, 0, $str, $format_info); 168 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count - 1); 169 $this->line++; 170 } 171 172 $this->line++; 173 $this->worksheet->write(8, 8, ' '); 174 if (@$CONFIG['site']['price_show_vc']) { 175 $headers = array("N", "Код", "Наименование", "Наличие", "Цена"); 176 } else { 177 $headers = array("N", "Наименование", "Наличие", "Цена"); 178 } 179 foreach ($headers as $id => $item) { 180 $headers[$id] = iconv('UTF-8', 'windows-1251', $item); 181 } 182 $this->worksheet->writeRow($this->line, 0, $headers, $format_header); 183 $this->line++; 184 } 185 186 /// Сформирвать тело прайса 187 function write($group = 0, $level = 0) { 188 if ($level > 2) { 189 $level = 2; 190 } 191 $res = $this->db->query("SELECT `id`, `name`, `printname` FROM `doc_group` WHERE `pid`='$group' AND `hidelevel`='0' ORDER BY `id`"); 192 while ($nxt = $res->fetch_row()) { 193 if ($nxt[0] == 0) { 194 continue; 195 } 196 if (is_array($this->view_groups)) { 197 if (!in_array($nxt[0], $this->view_groups)) { 198 continue; 199 } 200 } 201 202 $str = iconv('UTF-8', 'windows-1251', $nxt[1]); 203 $this->worksheet->write($this->line, 0, $str, $this->format_group[$level]); 204 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count - 1); 205 $this->line++; 206 207 $this->writepos($nxt[0], $nxt[2]); 208 $this->write($nxt[0], $level + 1); 209 } 210 } 211 212 /// Сформировать завершающий блок прайса 213 function close() { 214 global $CONFIG; 215 $this->line+=5; 216 $this->worksheet->write($this->line, 0, "Generated from MultiMag (http://multimag.tndproject.org) via PHPExcelWriter, for http://" . $CONFIG['site']['name'], $this->format_footer); 217 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count - 1); 218 $this->line++; 219 $str = iconv('UTF-8', 'windows-1251', "Прайс создан системой MultiMag (http://multimag.tndproject.org), специально для http://" . $CONFIG['site']['name']); 220 $this->worksheet->write($this->line, 0, $str, $this->format_footer); 221 $this->worksheet->setMerge($this->line, 0, $this->line, $this->column_count - 1); 222 $this->workbook->close(); 223 } 224 225 /// Сформировать строки прайса 226 function writepos($group = 0, $group_name = '') { 227 global $CONFIG; 228 229 $cnt_where = @$CONFIG['site']['vitrina_sklad'] ? (" AND `doc_base_cnt`.`sklad`=" . intval($CONFIG['site']['vitrina_sklad']) . " ") : ''; 230 231 $res = $this->db->query("SELECT `doc_base`.`id`, `doc_base`.`name`, `doc_base`.`cost_date` , `doc_base`.`proizv`, `doc_base`.`vc`, 218 232 ( SELECT SUM(`doc_base_cnt`.`cnt`) FROM `doc_base_cnt` WHERE `doc_base_cnt`.`id`=`doc_base`.`id` $cnt_where) AS `cnt`, 219 233 `doc_base`.`transit_cnt`, `doc_base`.`cost` AS `base_price`, `doc_base`.`bulkcnt`, `doc_base`.`group` … … 221 235 LEFT JOIN `doc_group` ON `doc_base`.`group`=`doc_group`.`id` 222 236 WHERE `doc_base`.`group`='$group' AND `doc_base`.`hidden`='0' ORDER BY `doc_base`.`name`"); 223 $i = 0; 224 225 if(@$CONFIG['site']['grey_price_days']) 226 $cce_time = $CONFIG['site']['grey_price_days'] * 60*60*24; 227 228 $pc = PriceCalc::getInstance(); 229 while($nxt = $res->fetch_assoc()) { 230 $c = 0; 231 $this->worksheet->write($this->line, $c++, $nxt['id'], $this->format_line[$i]); // номер 232 233 if(@$CONFIG['site']['price_show_vc']) { 234 $str = iconv('UTF-8', 'windows-1251', $nxt['vc']); 235 $this->worksheet->write($this->line, $c++, $str, $this->format_line[$i]); // код производителя 236 } 237 238 239 $name=iconv('UTF-8', 'windows-1251', "$group_name {$nxt['name']}".(($this->view_proizv&&$nxt['proizv'])?" ({$nxt['proizv']})":'')); 240 $this->worksheet->write($this->line, $c++, $name, $this->format_line[$i]); // наименование 241 242 $nal = $this->GetCountInfo($nxt['cnt'], $nxt['transit_cnt']); 243 $str = iconv('UTF-8', 'windows-1251',$nal); 244 $this->worksheet->write($this->line, $c++, $str, $this->format_line[$i]); // наличие - пока не отображается 245 246 $cost = $pc->getPosSelectedPriceValue($nxt['id'], $this->cost_id, $nxt); 247 if($cost==0) continue; 248 $str=iconv('UTF-8', 'windows-1251',$cost); 249 250 $format = $this->format_line[$i];; 251 if(@$CONFIG['site']['grey_price_days']) { 252 if( strtotime($nxt['cost_date']) < $cce_time ) 253 $format = $this->a_format_line[$i]; 254 } 255 256 $this->worksheet->write($this->line, $c++, $str, $format); // цена 257 258 $this->line++; 259 $i=1-$i; 260 } 261 } 262 }; 263 264 ?> 237 $i = 0; 238 239 if (@$CONFIG['site']['grey_price_days']) { 240 $cce_time = $CONFIG['site']['grey_price_days'] * 60 * 60 * 24; 241 } 242 243 $pc = \PriceCalc::getInstance(); 244 while ($nxt = $res->fetch_assoc()) { 245 $c = 0; 246 $this->worksheet->write($this->line, $c++, $nxt['id'], $this->format_line[$i]); // номер 247 248 if (@$CONFIG['site']['price_show_vc']) { 249 $str = iconv('UTF-8', 'windows-1251', $nxt['vc']); 250 $this->worksheet->write($this->line, $c++, $str, $this->format_line[$i]); // код производителя 251 } 252 253 254 $name = iconv('UTF-8', 'windows-1251', "$group_name {$nxt['name']}" . (($this->view_proizv && $nxt['proizv']) ? " ({$nxt['proizv']})" : '')); 255 $this->worksheet->write($this->line, $c++, $name, $this->format_line[$i]); // наименование 256 257 $nal = $this->GetCountInfo($nxt['cnt'], $nxt['transit_cnt']); 258 $str = iconv('UTF-8', 'windows-1251', $nal); 259 $this->worksheet->write($this->line, $c++, $str, $this->format_line[$i]); // наличие - пока не отображается 260 261 $cost = $pc->getPosSelectedPriceValue($nxt['id'], $this->cost_id, $nxt); 262 if ($cost == 0) { 263 continue; 264 } 265 $str = iconv('UTF-8', 'windows-1251', $cost); 266 267 $format = $this->format_line[$i]; 268 269 if (@$CONFIG['site']['grey_price_days']) { 270 if (strtotime($nxt['cost_date']) < $cce_time) { 271 $format = $this->a_format_line[$i]; 272 } 273 } 274 275 $this->worksheet->write($this->line, $c++, $str, $format); // цена 276 277 $this->line++; 278 $i = 1 - $i; 279 } 280 } 281 282 } 283 -
web/include/reports/profitability.php
r63901be r4cefac0 173 173 } 174 174 $cnt += $nxt['cnt']; 175 $cnt = round($cnt, 3); 175 176 if ($cnt < 0) 176 177 return array(0xFFFFBADF00D, 0, 0); // Невозможно расчитать прибыль, если остатки уходили в минус -
web/include/sendsms.php
r63901be r4cefac0 23 23 class SMSSender { 24 24 25 var $ worker;25 var $transport; 26 26 27 27 function __construct() { … … 30 30 throw new Exception("Работа с sms не настроена!"); 31 31 else if ($CONFIG['sendsms']['service'] == 'infosmska') 32 $this-> worker= new SendSMSTransportInfosmska();32 $this->transport = new SendSMSTransportInfosmska(); 33 33 34 34 else if ($CONFIG['sendsms']['service'] == 'virtualofficetools') 35 $this-> worker= new SendSMSTransportVirtualofficetools();35 $this->transport = new SendSMSTransportVirtualofficetools(); 36 36 } 37 37 38 38 /// Установить текст для отправки 39 39 function setContent($text, $translit = false) { 40 $this-> worker->setContent($text, $translit);41 } 42 43 /// Установить номер для отправки 44 function setNumber($number) { 45 $this-> worker->setNumber($number);40 $this->transport->setContent($text, $translit); 41 } 42 43 /// Установить номер для отправки 44 function setNumber($number) { 45 $this->transport->setNumber($number); 46 46 } 47 47 48 48 /// Отправить sms сообщение 49 49 function send() { 50 $this-> worker->send();50 $this->transport->send(); 51 51 } 52 52 … … 211 211 } 212 212 213 ?> -
web/price.php
r63901be r4cefac0 126 126 } 127 127 128 /// Базовый класс формирования прайс-листов129 class BasePriceWriter {130 protected $view_proizv; ///< Отображать ли наименование производителя131 protected $view_groups; ///< Группы, которые надо отображать. Массив.132 protected $column_count; ///< Кол-во колонок в прайсе133 protected $db; ///< mysqli коннектор к нужной базе134 135 /// Конструктор136 /// @param db mysqli-объект для подключения к базе данных137 public function __construct($db) {138 $this->db = $db;139 $this->column_count = 2;140 $this->view_proizv = 0;141 $this->cost_id = 1;142 $this->view_groups = false;143 }144 145 /// Сформировать прайс-лист, и отправить его в STDOUT146 public function run() {147 $this->open();148 $this->write();149 $this->close();150 }151 152 /// Включает отображение наименования производителя в наименовании товара153 /// @param visible true - отображать , false - не отображать154 public function showProizv($visible=1) {155 $this->view_proizv=$visible;156 }157 158 /// Включает режим отображения в прайс-листе только заданных групп товаров159 /// @param groups Массив с id групп, которые должны быть включены в прайс-лист160 public function setViewGroups($groups) {161 $this->view_groups=$groups;162 }163 164 /// Задаёт количество колонок, отображаемых в прайс-листе165 /// @param count Количество колонок166 public function setColCount($count) {167 $this->column_count=$count;168 settype($this->column_count, "int");169 if($this->column_count<1) $this->column_count=1;170 if($this->column_count>5) $this->column_count=5;171 }172 173 /// Устанавливает цену, которая должна быть отображена в прайс-листе174 /// @param cost Id отображаемой цены175 public function setCost($cost=1) {176 $this->cost_id=$cost;177 settype($this->cost_id, "int");178 }179 180 /// Получить информации о количестве товара. Формат информации - в конфигурационном файле181 /// @param count Количество единиц товара на складе182 /// @param transit Количество единиц товара в пути183 protected function getCountInfo($count, $transit) {184 global $CONFIG;185 if(!isset($CONFIG['site']['vitrina_pcnt_limit'])) $CONFIG['site']['vitrina_pcnt_limit'] = array(1,10,100);186 if($CONFIG['site']['vitrina_pcnt']==1) {187 if($count<=0) {188 if($transit) return 'в пути';189 else return 'уточняйте';190 }191 else if($count<=$CONFIG['site']['vitrina_pcnt_limit'][0]) return '*';192 else if($count<=$CONFIG['site']['vitrina_pcnt_limit'][1]) return '**';193 else if($count<=$CONFIG['site']['vitrina_pcnt_limit'][2]) return '***';194 else return '****';195 }196 else if($CONFIG['site']['vitrina_pcnt']==2) {197 if($count<=0) {198 if($transit) return 'в пути';199 else return 'уточняйте';200 }201 else if($count<=$CONFIG['site']['vitrina_pcnt_limit'][0]) return 'мало';202 else if($count<=$CONFIG['site']['vitrina_pcnt_limit'][1]) return 'есть';203 else if($count<=$CONFIG['site']['vitrina_pcnt_limit'][2]) return 'много';204 else return 'оч.много';205 }206 else return round($count).($transit?('('.$transit.')'):'');207 }208 }209 210 128 try { 211 129 $mode = request('mode'); … … 345 263 <br> 346 264 347 <form action='price.php' method=' get'>265 <form action='price.php' method='post'> 348 266 <input type=hidden name=mode value=get> 349 267 <input type=hidden name=f value=$f> … … 407 325 408 326 switch( $f ) { 409 case 'pdf': require_once('include/pricewriter/pdf.php'); $price=new PriceWriterPDF($db); break; 410 case 'csv': require_once('include/pricewriter/csv.php'); $price=new PriceWriterCSV($db); break; 411 case 'xls': require_once('include/pricewriter/xls.php'); $price=new PriceWriterXLS($db); break; 412 case 'html': require_once('include/pricewriter/html.php'); $price=new PriceWriterHTML($db); break; 413 default: throw new Exception("Запрошенный формат прайс-лиска пока не поддерживается"); 327 case 'pdf': 328 $price = new pricewriter\pdf($db); 329 break; 330 case 'csv': 331 $price = new pricewriter\csv($db); 332 break; 333 case 'xls': 334 $price = new pricewriter\xls($db); 335 break; 336 case 'html': 337 $price = new pricewriter\html($db); 338 break; 339 default: 340 throw new Exception("Запрошенный формат прайс-лиска пока не поддерживается"); 414 341 } 415 342 $price->showProizv($proizv); … … 421 348 $price->setShielder( request('shielder') ); 422 349 } 423 if(request('gs') && is_array($_ POST['g'])) {424 $price->setViewGroups($_ POST['g']);350 if(request('gs') && is_array($_REQUEST['g'])) { 351 $price->setViewGroups($_REQUEST['g']); 425 352 } 426 353 -
web/vitrina.php
r63901be r4cefac0 1561 1561 1562 1562 if(@$_REQUEST['phone']) { // Пробуем выполнить нормализацию номера телефона 1563 $phone = $_REQUEST['phone']; 1564 $phone = preg_replace("/[^0-9+]/", "", $phone); 1565 $phoneplus = $phone[0]=='+'; 1566 $phone = preg_replace("/[^0-9]/", "", $phone); 1567 if($phoneplus && $phone[0]==7 && strlen($phone)==11) { 1568 $phone = '+'.$phone; 1569 } elseif(!$phoneplus && $phone[0]==8 && strlen($phone)==11) { 1570 $phone = '+7'.substr($phone,1); 1571 } elseif(!$phoneplus && $phone[0]==9 && strlen($phone)==10) { 1572 $phone = '+7'.$phone; 1573 } else { 1563 $phone = normalizePhone($_REQUEST['phone']); 1564 if($phone === false) { 1574 1565 header("Location: /vitrina.php?mode=buyform&step=1&cwarn=1"); 1575 1566 return; 1576 1567 } 1577 echo $phone;1578 1568 } else $phone=''; 1579 1569
Note: See TracChangeset
for help on using the changeset viewer.