Esempio n. 1
0
    static function open_in_blank($kp_id, $client_id, $user_id, $save_on_disk = false)
    {
        global $mysqli;
        // Здесь делаем то что в старой версии делали при сохранении КП в файл
        // Данные из РТ
        $multi_dim_arr = self::fetch_kp_rows($kp_id);
        // echo '<pre>';print_r($multi_dim_arr);echo '</pre>';//exit;
        /*if(@$_SESSION['access']['user_id']==18){ 
         		echo '<pre>';print_r($multi_dim_arr);echo '</pre>';
          } */
        // Настройки отображения состовляющих КП
        $display_setting = $multi_dim_arr[key($multi_dim_arr)]['display_setting'];
        $display_setting_2 = $multi_dim_arr[key($multi_dim_arr)]['display_setting_2'];
        $dispSetObj = json_decode($display_setting);
        $itogo = $itogo_print_uslugi = $itogo_extra_uslugi = 0;
        $itogo_print_uslugi1 = $itogo_print_uslugi2 = $itogo_print_uslugi3 = 0;
        $itogo_extra_uslugi1 = $itogo_extra_uslugi2 = $itogo_extra_uslugi3 = 0;
        // echo '<pre>';
        // print_r($multi_dim_arr);
        // echo '</pre>';
        // Разворачиваем массив
        foreach ($multi_dim_arr as $pos_key => $pos_level) {
            // РАБОТАЕМ С ПЕРВОЙ ЯЧЕЙКОЙ РЯДА ТАБЛИЦЫ КП
            // в этой ячейке подразумевается отображение картинки товарной позиции
            // соответсвенное если есть что показывать, то добавляем тег img, если нет то  добавляем пустую строку
            $img_src = 'http://www.apelburg.ru/img/no_image.jpg';
            $img_cell = '<img src="' . $img_src . '" height="180" width="180">';
            $art_img = new Art_Img_development($pos_key, $pos_level['img_folder'], $pos_level['img'], $pos_level['art']);
            // $img_src = $art_img->big;
            // echo '<pre>';
            // print_r($art_img);
            // echo '</pre>';
            // меняем размер изображения
            $img_cell = '';
            foreach ($art_img->big as $key => $img_src) {
                $size_arr = transform_img_size($img_src, 230, 300);
                // $size_arr = array(230,300);
                $img_cell .= '<img src="' . $img_src . '" height="' . $size_arr[0] . '" width="' . $size_arr[1] . '">';
            }
            // $img_cell .= '<img src="'.$img_src.'" height="'.$size_arr[0].'" width="'.$size_arr[1].'">';
            // $img_cell .= '<img src="'.$img_src.'" height="'.$size_arr[0].'" width="'.$size_arr[1].'">';
            // if($pos_level['row_type']=='cat'){ // если позиция из каталога получаем картинку из базы данных каталога
            // 	$art_img = new  Art_Img($pos_level['art']);
            // 	// проверяем наличие изображения
            // 	$img_path = 'http://www.apelburg.ru/img/'.$art_img->big;
            // 	if($img_src = checkImgExists($img_path)){
            // 		// меняем размер изображения
            // 		$size_arr = transform_img_size($img_src,230,300);
            // 		// $size_arr = array(230,300);
            // 		$img_cell = '<img src="'.$img_src.'" height="'.$size_arr[0].'" width="'.$size_arr[1].'">';
            // 	}
            //             }
            // РАБОТАЕМ СО ВТОРОЙ ЯЧЕЙКОЙ РЯДА ТАБЛИЦЫ КП
            // наименование товарной позиции
            // форматируем вывод, разбиваем строки на куски определенной длины и вставляем перед каждым отступ
            $str_len = 40;
            $pos_name = $pos_level['name'];
            $pos_name = nl2br($pos_name);
            if ($save_on_disk && isset($dispSetObj->art)) {
                $article = '';
            } else {
                if ($pos_level['row_type'] != 'cat') {
                    $article = '';
                } else {
                    $article = '<managedDisplay name="art" style="display:' . (isset($dispSetObj->art) ? 'none' : 'inline-block') . '">арт.: <a href="/description/' . @$pos_level['art_id'] . '/" target="_blank">' . @$pos_level['art'] . '</a></managedDisplay>';
                }
            }
            // НАЧИНАЕМ ПЕРЕБИРАТЬ ДАННЫЕ РАСЧЕТОВ
            // примечание - у позиции может быть любое количество расчетов( а каждый расчет в свою очередь может содержать
            //  любое количество нанесений и доп услуг)
            foreach ($pos_level['dop_data'] as $r_key => $r_level) {
                if ($pos_level['row_type'] != 'cat' && isset($r_level['details'])) {
                    $pos_name = $r_level['details'];
                }
                $all_print_summ = $all_extra_summ = 0;
                //$r_ - сокращение обозначающее - уровень Расчёта позиции
                // стоимост артикула в данном расчете (без нанесения и услуг)
                // чтобы в дальнейшем не было проблем с делением преобразуем $quantity в 1 если оно равно 0
                $quantity = $r_level['quantity'] == 0 ? 1 : $r_level['quantity'];
                // стоимость
                $price = $r_level['discount'] != 0 ? round($r_level['price_out'] / 100 * (100 + $r_level['discount']), 2) : $r_level['price_out'];
                $summ = $quantity * $price;
                $itogo += $summ;
                // добавляем данные в  содержимое ячейки<td><div contenteditable="true" class="saveKpPosDescription"  pos_id="'.$pos_key.'">'.$pos_name.'</div></td>
                $description_cell = '<div style="margin-top:5px;"><b>Сувенир:</b></div>
					<table border="0" style="font-family:arial;font-size:13px;" tbl="managed">
					  <tr>
						<td style="width:6px;"></td>
						<td style="width:400px;" managed="text" bd_row_id="' . ($pos_level['row_type'] == 'cat' ? $pos_key : $r_key) . '" bd_field="' . ($pos_level['row_type'] == 'cat' ? 'name' : 'details') . '" action="changeKpPosDescription">' . $pos_name . '</td>
					  </tr>
					  <tr>
						<td style="width:6px;"></td>
						<td>' . $article . '</td>
					  </tr>
					  </table>';
                if (!($save_on_disk && isset($dispSetObj->sizes))) {
                    $description_cell .= '<managedDisplay name="sizes" style="display:' . (!isset($dispSetObj->sizes) && $r_level['tirage_str'] != '' ? 'inline-block' : 'none') . '">
						 <table border="0" style="font-family:arial;font-size:13px;" tbl="managed">
						  <tr>
							<td style="width:6px;"></td>
							<td style="width:400px;" managed="text" bd_row_id="' . $r_key . '" action="changeKpPosDescription" bd_field="tirage_str">' . $r_level['tirage_str'] . '</td>
						  </tr>
						  </table>
					  </managedDisplay>';
                }
                if (!($save_on_disk && isset($dispSetObj->characteristics))) {
                    $description_cell .= '<managedDisplay name="characteristics" style="display:' . (!isset($dispSetObj->characteristics) && $pos_level['characteristics'] != '' ? 'inline-block' : 'none') . '">
						 <table border="0" style="font-family:arial;font-size:13px;" tbl="managed">
						  <tr>
							<td style="width:6px;"></td>
							<td style="width:400px;" managed="text" bd_row_id="' . $pos_key . '" action="changeKpRepresentedData" bd_field="characteristics">' . $pos_level['characteristics'] . '</td>
						  </tr>
						  </table>
					  </managedDisplay>';
                }
                if (!($save_on_disk && isset($dispSetObj->description))) {
                    $description_cell .= '<managedDisplay name="description" style="display:' . (!isset($dispSetObj->description) && $pos_level['description'] != '' ? 'inline-block' : 'none') . '">
					   <table border="0" style="font-family:arial;font-size:13px;" tbl="managed">
						  <tr>
							<td style="width:6px;"></td>
							<td style="width:400px;" managed="text" bd_row_id="' . $pos_key . '" action="changeKpRepresentedData" bd_field="description">' . $pos_level['description'] . '</td>
						  </tr>
						</table>
					</managedDisplay>';
                }
                $description_cell .= '<table style="font-family:arial;font-size:13px;margin-top:10px;width:100%;border-collapse:collapse;width:350px;table-layout:_fixed;" border="0">
					  <tr>
						<td align="right" style="width:250px;color:#888;">1шт.</td>
						<td align="right" style="width:70px;padding:0 5px;"><nobr>' . number_format($price, 2, '.', ' ') . '</nobr></td>
						<td align="left" style="width:30px;">руб.</td>
					  </tr>
					  <tr>
						<td align="right" style="color:#888;">тираж: ' . $quantity . ' шт. </td>
						<td align="right" style="padding:0 5px;"><nobr>' . number_format($summ, 2, '.', ' ') . '</nobr></td>
						<td align="left">руб.</td>
					  </tr>
					</table>';
                // РАБОТАЕМ С НАНЕСЕНИЯМИ И ДОП УСЛУГАМИ СОБИРАЕМ В ЕДИННЫЕ БЛОКИ ДЛЯ ПОСЛЕДУЮЩЕЙ СБОРКИ
                $print_block = $details_block = array();
                $counter = 0;
                // если есть нанесение
                if (isset($r_level['dop_uslugi']['print'])) {
                    $show_count = count($r_level['dop_uslugi']['print']) > 1 ? true : false;
                    $counter2 = 0;
                    foreach ($r_level['dop_uslugi']['print'] as $u_key => $u_level) {
                        if ($u_level['print_details'] == '') {
                            continue;
                        }
                        $print_details_obj = json_decode($u_level['print_details']);
                        if ($print_details_obj == NULL) {
                            continue;
                        }
                        $print_details_arr = json_decode($u_level['print_details'], TRUE);
                        /*if(@$_SESSION['access']['user_id']==18){ 
                        		echo '<pre>';print_r($print_details_arr);echo '</pre>';
                          } */
                        if (isset($print_details_arr['dop_params']['sizes'])) {
                            if ($print_details_arr['dop_params']['sizes'][0]['type'] == 'coeff') {
                                $size_coeff = isset($print_details_arr['dop_params']['sizes'][0]['val']) && $print_details_arr['dop_params']['sizes'][0]['val'] != 0 ? $print_details_arr['dop_params']['sizes'][0]['val'] : 1;
                            }
                            if ($print_details_arr['dop_params']['sizes'][0]['type'] == 'addition') {
                                $size_coeff = isset($print_details_arr['dop_params']['sizes'][0]['val']) ? $print_details_arr['dop_params']['sizes'][0]['val'] : 0;
                                $size_coeff = $print_details_arr['dop_params']['sizes'][0]['target'] == 'summ' ? round($size_coeff / $quantity, 2) : $size_coeff;
                            }
                        } else {
                            $size_coeff = false;
                        }
                        $new_price_arr['price_in'] = $u_level['discount'] != 0 ? $u_level['price_in'] / 100 * (100 + $u_level['discount']) : $u_level['price_in'];
                        $new_price_arr['price_out'] = $u_level['discount'] != 0 ? $u_level['price_out'] / 100 * (100 + $u_level['discount']) : $u_level['price_out'];
                        //$new_price_arr['price_in'] = $u_level['price_in'];
                        //$new_price_arr['price_out'] = $u_level['price_out'];
                        include_once ROOT . "/libs/php/classes/rt_calculators_class.php";
                        $calculations = rtCalculators::make_calculations($quantity, $new_price_arr, $print_details_obj->dop_params);
                        // echo  '<pre>'; print_r($new_price_arr); echo '</pre>';  //
                        /*if(@$_SESSION['access']['user_id']==18){ 
                        				echo '<pre>';print_r($calculations);echo '</pre>';
                        		} */
                        // наименование нанесения
                        include_once ROOT . "/libs/php/classes/print_calculators_class.php";
                        $print_data = printCalculator::convert_print_details_for_kp($u_level['print_details']);
                        /*if(@$_SESSION['access']['user_id']==18){ 
                        				echo '<pre>';print_r($print_data);echo '</pre>';
                        		} */
                        // Собираем данные для print_block (Печать логотипа)
                        $print_block[] = '<table border="0" style="font-family:arial;font-size:13px;right;margin:15px 0 0 11px;width:100%;border-collapse:collapse;width:350px;table-layout:fixed;">';
                        $print_block[] = '<tr><td valign="top" style="width:90px;">метод ' . ($show_count ? ++$counter2 . ': ' : '') . ' </td><td style="width:170px;">' . $print_data['block1']['print_type'] . '</td></tr>';
                        $print_block[] = '<tr><td valign="top">Место нанесения: </td><td>' . $print_data['block1']['place_type'] . '</td></tr>';
                        if (isset($print_data['block1']['price_data']['y_params'])) {
                            $print_block[] = '<tr><td valign="top">' . $print_data['block1']['price_data']['cap'] . ': </td><td>' . count($print_data['block1']['price_data']['y_params']) . ' (' . implode(', ', $print_data['block1']['price_data']['y_params']) . ')</td></tr>';
                            $y_params_count = count($print_data['block1']['price_data']['y_params']);
                            $y_params_coeff = 0;
                            foreach ($print_details_arr['dop_params']['YPriceParam'] as $y_data) {
                                if ($y_data['coeff'] == 0) {
                                    $y_data['coeff'] = 1;
                                }
                                $y_params_coeff += $y_data['coeff'] - 1;
                            }
                        }
                        if (isset($print_data['block1']['print_size'])) {
                            // если тип нанесения Тампопечать ( id =18 ) - то тогда не отображаем площать печати
                            if ($u_level['usluga_id'] != 18) {
                                $print_block[] = '<tr><td valign="top">Площадь печати: </td><td>' . $print_data['block1']['print_size'] . '</td></tr>';
                            }
                            //echo  '<pre>--2--'; print_r($print_details_arr['dop_params']); echo '</pre>';
                        }
                        if (isset($print_data['block2']['data'])) {
                            foreach ($print_data['block2']['data'] as $block2_data) {
                                $print_block[] = '<tr><td valign="top" colspan="2">' . $block2_data['name'] . '</td></tr>';
                            }
                        }
                        $print_block[] = '</table>';
                        $print_block_price = $new_price_arr['price_out'];
                        $print_block_price1 = $new_price_arr['price_out'];
                        if ($display_setting_2 == 0) {
                            // вариант 1
                            // коэффициент площади
                            /*if($size_coeff!==false){
                            			if($print_details_arr['dop_params']['sizes'][0]['type'] == 'coeff'){
                            			    
                            				$print_block_price = $new_price_arr['price_out']*$size_coeff;
                            			}
                            			if($print_details_arr['dop_params']['sizes'][0]['type'] == 'addition'){
                            				$print_block_price = $new_price_arr['price_out']+$size_coeff;
                            				 
                            			}
                            		}
                            		
                            		// добавить коэфф цвета если есть
                            		if(isset($y_params_count) && $y_params_count>0){
                            		    $y_params_coeff = (isset($y_params_coeff))?$y_params_coeff:1;
                            		    $print_block_price += ($new_price_arr['price_out']/$y_params_count)*$y_params_coeff;
                            		}*/
                            $print_block_summ = $quantity * $print_block_price;
                            $all_print_summ += $quantity * $new_price_arr['price_out'];
                            $itogo_print_uslugi += $print_block_summ;
                            //$itogo_extra_uslugi += $calculations['new_summs']['summ_out'] - $print_block_summ;
                        } else {
                            if ($display_setting_2 == 1) {
                                // вариант 2
                                $print_block_price = $new_price_arr['price_out'];
                                $print_block_summ = $quantity * $new_price_arr['price_out'];
                                $all_print_summ += $calculations['new_summs']['summ_out'];
                                $itogo_print_uslugi += $print_block_summ;
                                //$itogo_extra_uslugi += $calculations['new_summs']['summ_out'] - $print_block_summ;
                            } else {
                                if ($display_setting_2 == 2) {
                                    // вариант 3
                                    $print_block_price = $new_price_arr['price_out'];
                                    $print_block_summ = $quantity * $new_price_arr['price_out'];
                                    $all_print_summ += $calculations['new_summs']['summ_out'];
                                    $itogo_print_uslugi += $calculations['new_summs']['summ_out'];
                                }
                            }
                        }
                        //////////////////////////////////////////////////////////////////////////////
                        //////////////////////////////////////////////////////////////////////////////
                        // коэффициент площади
                        /*if($size_coeff!==false){
                        			if($print_details_arr['dop_params']['sizes'][0]['type'] == 'coeff'){
                        				$print_block_price1 = $new_price_arr['price_out']*$size_coeff;
                        			}
                        			if($print_details_arr['dop_params']['sizes'][0]['type'] == 'addition'){
                        				$print_block_price1 = $new_price_arr['price_out']+$size_coeff;
                        				 
                        			}
                        		}
                        			
                        		//$size_coeff = (isset($size_coeff))?$size_coeff:1;
                        		//$print_block_price1 = $new_price_arr['price_out']*$size_coeff;
                        		
                        		// добавить коэфф цвета если есть
                        		if(isset($y_params_count) && $y_params_count>0){
                        			$y_params_coeff = (isset($y_params_coeff))?$y_params_coeff:1;
                        			$print_block_price1 += ($new_price_arr['price_out']/$y_params_count)*$y_params_coeff;
                        		}*/
                        $print_block_summ1 = $quantity * $print_block_price1;
                        $itogo_print_uslugi1 += $quantity * $print_block_price1;
                        //$itogo_extra_uslugi1 += $calculations['new_summs']['summ_out'] - $print_block_summ1;
                        $print_block_price2 = $new_price_arr['price_out'];
                        $print_block_summ2 = $quantity * $new_price_arr['price_out'];
                        $itogo_print_uslugi2 += $quantity * $new_price_arr['price_out'];
                        // $itogo_extra_uslugi2 += $calculations['new_summs']['summ_out'] - $quantity*$new_price_arr['price_out'];
                        $print_block_price3 = $new_price_arr['price_out'];
                        $print_block_summ3 = $quantity * $new_price_arr['price_out'];
                        //$itogo_print_uslugi3 += $calculations['new_summs']['summ_out'];
                        //////////////////////////////////////////////////////////////////////////////
                        //////////////////////////////////////////////////////////////////////////////
                        unset($size_coeff);
                        unset($y_params_coeff);
                        unset($y_params_count);
                        if ($save_on_disk && isset($dispSetObj->full_summ)) {
                            $print_block[] = '<table style="font-family:arial;font-size:13px;right;margin:0 0 5px 0;width:100%;border-collapse:collapse;width:350px;table-layout:_fixed;" border="0">
									  <tr>
										<td align="right" style="width:250px;color:#888;">1шт.</td>
										<td align="right" style="width:70px;padding:0 5px;"><nobr>' . number_format($print_block_price, 2, '.', ' ') . '</nobr></td>
										<td align="left" style="width:30px;">руб.</td>
									  </tr>
									  <tr>
										<td align="right" style="color:#888;">тираж: ' . $quantity . ' шт. </td>
										<td align="right" style="padding:0 5px;"><nobr>' . number_format($print_block_summ, 2, '.', ' ') . '</nobr></td>
										<td align="left">руб.</td>
									  </tr>
									</table>';
                        } else {
                            $print_block[] = '<table style="font-family:arial;font-size:13px;right;margin:0 0 5px 0;width:100%;border-collapse:collapse;width:350px;table-layout:_fixed;" border="0">
									  <tr>
										<td align="right" style="width:250px;color:#888;">1шт.</td>
										<td align="right" style="width:70px;padding:0 5px;"><nobr><span id="metod_display_setting_' . $counter2 . '1_0"  style="display:' . ($display_setting_2 == 0 ? 'inline-block' : 'none') . '">' . number_format($print_block_price1, 2, ',', ' ') . '</span><span id="metod_display_setting_' . $counter2 . '1_1" style="display:' . ($display_setting_2 == 1 ? 'inline-block' : 'none') . '">' . number_format($print_block_price2, 2, ',', ' ') . '</span><span id="metod_display_setting_' . $counter2 . '1_2" style="display:' . ($display_setting_2 == 2 ? 'inline-block' : 'none') . '">' . number_format($print_block_price3, 2, ',', ' ') . '</span></nobr></td>
										<td align="left" style="width:30px;">руб.</td>
									  </tr>
									  <tr>
										<td align="right" style="color:#888;">тираж: ' . $quantity . ' шт. </td>
										<td align="right" style="padding:0 5px;"><nobr><span id="metod_display_setting_' . $counter2 . '2_0"  style="display:' . ($display_setting_2 == 0 ? 'inline-block' : 'none') . '">' . number_format($print_block_summ1, 2, ',', ' ') . '</span><span id="metod_display_setting_' . $counter2 . '2_1" style="display:' . ($display_setting_2 == 1 ? 'inline-block' : 'none') . '">' . number_format($print_block_summ2, 2, ',', ' ') . '</span><span id="metod_display_setting_' . $counter2 . '2_2" style="display:' . ($display_setting_2 == 2 ? 'inline-block' : 'none') . '">' . number_format($print_block_summ3, 2, ',', ' ') . '</span></nobr></td>
										<td align="left">руб.</td>
									  </tr>
									</table>';
                        }
                        unset($print_block_summ);
                        unset($print_block_price);
                        unset($print_block_price3);
                        // Собираем данные для details_block (деталировка по нанесению)
                        $square_coeff = 1;
                        //echo  '<pre>--1--'; print_r( $print_data['block1']['price_data']['y_params']); echo '</pre>';
                        //echo  '<pre>--2--'; print_r( $print_details_arr['dop_params']); echo '</pre>';
                        foreach ($print_details_arr['dop_params'] as $type => $data) {
                            $price_addition = $summ_addition = 0;
                            //
                            if ($type == 'sizes' && isset($data[0]['val'])) {
                                // в итгое не выводится первым потому что в исходном массиве не на первом месте
                                if ($data[0]['val'] == 0) {
                                    $data[0]['val'] = 1;
                                }
                                if ($data[0]['target'] == 'price') {
                                    $square_coeff = $data[0]['val'];
                                }
                                //!!if($data->target == 'summ') $summ_coeff += (float)$data->val-1;
                                if ($square_coeff == 1) {
                                    continue;
                                }
                                $print_summ = $quantity * ($new_price_arr['price_out'] * ($square_coeff - 1));
                                if ($save_on_disk && $display_setting_2 != 0) {
                                    $rows_2[] = '<tr><td align="left" style="width:230px;padding:0 5px 0 15px;">+ ' . ($square_coeff - 1) * 100 . '% за увелич. площади печати</td>';
                                    $rows_2[] = '<td align="right" style="width:90px;">' . number_format($print_summ, 2, '.', ' ') . '</td>';
                                    $rows_2[] = '<td align="left" style="width:30px;">руб. </td></tr>';
                                    /**/
                                } else {
                                    if (!$save_on_disk) {
                                        $rows_2[] = '<tr id="metod_display_setting_' . $counter2 . '3" style="display:' . ($display_setting_2 != 0 ? 'table-row' : 'none') . '"><td align="left" style="width:230px;padding:0 5px 0 15px;">+ ' . ($square_coeff - 1) * 100 . '% за увелич. площади печати</td>';
                                        $rows_2[] = '<td align="right" style="width:90px;">' . number_format($print_summ, 2, '.', ' ') . '</td>';
                                        $rows_2[] = '<td align="left" style="width:30px;">руб. </td></tr>';
                                        /**/
                                    }
                                }
                            }
                            if ($type == 'YPriceParam') {
                                $price_tblYindex = count($data) == 0 ? 1 : count($data);
                                $base_price_for_Y = $new_price_arr['price_out'] / $price_tblYindex;
                                foreach ($data as $index => $Y_data) {
                                    if ($Y_data['coeff'] == 1) {
                                        continue;
                                    }
                                    $Y_coeff = (double) $Y_data['coeff'] - 1;
                                    $print_summ = $quantity * ($base_price_for_Y * $Y_coeff);
                                    if ($save_on_disk && $display_setting_2 != 0) {
                                        $rows_2[] = '<tr><td align="left" style="width:230px;padding:0 5px 0 15px;">+ ' . ($Y_data['coeff'] - 1) * 100 . '% за металлик (' . $print_data['block1']['price_data']['y_params_ids'][$Y_data['id']] . ')</td>';
                                        $rows_2[] = '<td align="right" style="width:90px;">' . number_format($print_summ, 2, '.', ' ') . '</td>';
                                        $rows_2[] = '<td align="left" style="width:30px;">руб. </td></tr>';
                                    } else {
                                        if (!$save_on_disk) {
                                            $rows_2[] = '<tr id="metod_display_setting_' . $counter2 . $index . '4" style="display:' . ($display_setting_2 != 0 ? 'table-row' : 'none') . '"><td align="left" style="width:230px;padding:0 5px 0 15px;">+ ' . ($Y_data['coeff'] - 1) * 100 . '% за металлик (' . $print_data['block1']['price_data']['y_params_ids'][$Y_data['id']] . ')</td>';
                                            $rows_2[] = '<td align="right" style="width:90px;">' . number_format($print_summ, 2, '.', ' ') . '</td>';
                                            $rows_2[] = '<td align="left" style="width:30px;">руб. </td></tr>';
                                        }
                                    }
                                }
                            }
                        }
                        $base_price2 = $new_price_arr['price_out'] * $square_coeff;
                        $spechial_summ = 100;
                        foreach ($print_data['block2'] as $data) {
                            foreach ($data as $data2) {
                                if ($data2['type'] == 'coeff') {
                                    if ($data2['value'] == 1) {
                                        continue;
                                    }
                                    $spechial_summ = 1;
                                    $coeff = $data2['value'] - 1;
                                    $print_summ = $data2['target'] == 'price' ? $quantity * ($base_price2 * $coeff) : $spechial_summ / 100 * $data2['value'];
                                }
                                if ($data2['type'] == 'addition') {
                                    if ($data2['value'] == 0) {
                                        continue;
                                    }
                                    $print_summ = $data2['target'] == 'price' ? $quantity * $data2['value'] : $data2['value'];
                                }
                                $rows_2[] = '<tr><td align="left" style="width:230px;padding:0 5px 0 15px;">' . $data2['name'] . '</td>';
                                $rows_2[] = '<td align="right" style="width:90px;">' . number_format($print_summ, 2, '.', ' ') . '</td>';
                                $rows_2[] = '<td align="left" style="width:30px;">руб. </td></tr>';
                            }
                        }
                        if (isset($rows_2)) {
                            //$details_block11[$counter]['cap'] = 'для метода печати '.(($show_count)? $counter2.': ':'');
                            //$details_block11[$counter]['data'] = $rows_2;
                        }
                        $counter++;
                        // echo  '<pre>'; print_r($rows_2); echo '</pre>';
                        unset($rows_2);
                        //
                        //echo '<table style="margin-top:5px;border-collapse:collapse;" border="1">'.implode('',$rows_2).'</table>';
                    }
                }
                // перебор доп услуг
                if (isset($r_level['dop_uslugi']['extra'])) {
                    foreach ($r_level['dop_uslugi']['extra'] as $u_key => $u_level) {
                        if ($u_level['price_out'] == 0) {
                            continue;
                        }
                        include_once ROOT . "/libs/php/classes/agreement_class.php";
                        // если альтернативное название отсутствует (вводится при заведении услуги "НЕТ В СПИСКЕ")
                        if (trim($u_level['other_name']) == "") {
                            $extra_usluga_details = Agreement::get_usluga_details($u_level['usluga_id']);
                            $u_level['name'] = $extra_usluga_details ? $extra_usluga_details['name'] : 'Неопределено';
                        } else {
                            $u_level['name'] = $u_level['other_name'];
                        }
                        $print_summ = $u_level['for_how'] == 'for_all' ? $u_level['price_out'] : $quantity * $u_level['price_out'];
                        $all_extra_summ += $print_summ;
                        $itogo_extra_uslugi += $print_summ;
                        $itogo_extra_uslugi1 += $print_summ;
                        $itogo_extra_uslugi2 += $print_summ;
                        $itogo_extra_uslugi3 += $print_summ;
                        $rows_2[] = '<tr><td align="left" style="width:230px;height:10px;line-height:10px;padding:0 5px 0 15px;">' . $u_level['name'] . '</td>';
                        $rows_2[] = '<td align="right" style="width:90px;">' . number_format($print_summ, 2, '.', ' ') . '</td>';
                        $rows_2[] = '<td align="left" style="width:30px;">руб. </td></tr>';
                    }
                    if (isset($rows_2)) {
                        $details_block11[$counter]['cap'] = 'для сувенира ';
                        $details_block11[$counter]['data'] = $rows_2;
                    }
                    unset($rows_2);
                }
                // Вставляем блоки в тело КП
                if (isset($print_block) && count($print_block) > 0) {
                    $description_cell .= '<hr style="border:none;border-top:#888 solid 1px;"><div style="margin-top:5px;"><b>Печать логотипа:</b></div>';
                    $description_cell .= '<div style="">' . implode('<div></div>', $print_block) . '</div>';
                }
                if (isset($details_block11) && count($details_block11) > 0) {
                    /*if(true!($save_on_disk && isset($dispSetObj->dop_uslugi))){ //style="display:'.(isset($dispSetObj->dop_uslugi)?'none':'block').'}"*/
                    $description_cell .= '<managedDisplay name="dop_uslugi" style="display:' . (isset($dispSetObj->dop_uslugi) ? 'none' : 'block') . '"><hr style="border:none;border-top:#888 solid 1px;"><div><b>Дополнительные услуги:</b></div>';
                    $description_cell .= '<table style="margin-top:5px;border-collapse:collapse; font-family:arial;font-size:13px;" border="0">';
                    foreach ($details_block11 as $key => $rows) {
                        //$description_cell .=  '<tr><td align="left" height="25" colspan="3" style="padding:0 5px 0 15px;color:#888">'.$rows['cap'].'</td>';
                        $description_cell .= implode('', $rows['data']);
                    }
                    $description_cell .= '</table></managedDisplay>';
                }
                $description_cell .= '<table style="margin:5px 0 10px 0;border-collapse:collapse;" border="0"><tr><td align="left" style="width:220px;"><b>Итого</b></td>';
                /*if(@$_SESSION['access']['user_id']==18){ 
                				echo '---'.$summ.'--'.$all_print_summ.'--'.$all_extra_summ.'---';
                		} */
                $description_cell .= '<td align="right" style="width:100px;"><b>' . number_format($summ + $all_print_summ + $all_extra_summ, 2, '.', ' ') . '</b></td>';
                $description_cell .= '<td align="left" style="width:30px;"><b>руб.</b></td></tr></table>';
                $tbl_rows[] = '<tr><td style="border-bottom:#91B73F solid 2px; border-top:#91B73F solid 2px;" width="300" valign="middle" align="center">' . $img_cell . '</td><td style="border-bottom:#91B73F solid 2px; border-top:#91B73F solid 2px;padding:6px;" width="325" valign="top">' . $description_cell . '</td></tr>';
                $description_cell = $print_description = '';
                unset($details_block11);
                unset($print_details);
                unset($extra_details);
                unset($pos_and_print_cost);
            }
        }
        /********************   ++++++++++++++  *********************/
        // КОНЕЧНАЯ СБОРКА КП
        // Данные для шапки
        $cont_face_data_arr = get_client_cont_face_by_id($client_id, $user_id, true);
        $client_data_arr = select_all_client_data($client_id);
        // получаем данные о получателе КП, сначала вычисляем его id
        // потом передаем его в метод Client::get_cont_face_details($recipient_id);
        reset($multi_dim_arr);
        $recipient_id = $multi_dim_arr[key($multi_dim_arr)]['recipient_id'];
        include_once ROOT . "/libs/php/classes/client_class.php";
        $cont_face_data = Client::get_cont_face_details($recipient_id);
        //print_r($cont_face_data_arr);//exit;625
        $kp_content = '<div id="kpBlankConteiner" style="width:675px;background-color:#FFFFFF;border:#91B73F solid 0px;"><table width="675"  style="border-collapse:collapse;background-color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;" valign="top"><tr><td colspan="2" style="text-align:right;">
			<input  type="hidden" style="width:90px;" id="kpDisplaySettings" value=' . $display_setting . '><input  type="hidden" id="kpDisplaySettings_kpId" value=' . $kp_id . '>';
        if (!($save_on_disk && isset($dispSetObj->header))) {
            $kp_content .= '<div style="text-align:right;font-family:verdana;font-size:12px;font-weight:bold;line-height:16px;"><managedDisplay name="header" style="display:' . (isset($dispSetObj->header) ? 'none' : 'block') . '">В компанию: ' . Client::get_client_name($client_id) . '<br />Кому: ' . $cont_face_data['last_name'] . ' ' . $cont_face_data['name'] . ' ' . $cont_face_data['surname'] . '</managedDisplay></div>';
        }
        //s$kp_content .= '<div style="font-family:verdana;font-size:18px;padding:10px;color:#10B050;text-align:center;border:#91B73F solid 1px;width:675px;">Презентация</div>';
        $kp_content .= '</td></tr>
			                <tr><td colspan="2" style="text-align:center;">
							<div style="font-family:verdana; font-size:18px;padding:10px;color:#10B050;">Презентация</div></td></tr>';
        $kp_content .= '</td></tr>' . implode('', $tbl_rows) . '<tr><td colspan="2" style="text-align:right;">';
        // <div style="border-top:#91B73F solid 2px;width:675px;"></div>
        /********************   ++++++++++++++  *********************/
        if ($save_on_disk && !isset($dispSetObj->full_summ)) {
            if ($itogo != 0) {
                $full_itog = $itogo + $itogo_print_uslugi + $itogo_extra_uslugi;
                $kp_content .= '<div style="text-align:right;">
					 <managedDisplay name="full_summ" style="text-align:right;display:' . (isset($dispSetObj->full_summ) ? 'none' : 'inline-block') . '">
					 <table align="right" style="margin:15px 0px 10px 0;font-family:arial" border="0">';
                if ($itogo_print_uslugi + $itogo_extra_uslugi != 0) {
                    $kp_content .= '<tr>
							 <td width="230" height="20" align="right" valign="top" style="padding-right:2px;" >Общая стоимость сувениров:</td><td width="150" align="right" valign="top">' . number_format($itogo, 2, ',', ' ') . 'руб.</td>
						 </tr>';
                }
                if ($itogo_print_uslugi != 0) {
                    $kp_content .= '<tr>
							 <td align="right" height="20" valign="top">Общая стоимость нанесения:</td><td align="right" valign="top">' . number_format($itogo_print_uslugi, 2, ',', ' ') . 'руб.</td>
						 </tr>';
                }
                if ($itogo_extra_uslugi != 0) {
                    $kp_content .= '<tr>
							 <td align="right" height="30" valign="top">Общая стоимость доп услуг:</td><td align="right" valign="top">' . number_format($itogo_extra_uslugi, 2, ',', ' ') . 'руб.</td>
						 </tr>';
                }
                $kp_content .= '<tr>
							 <td align="right" valign="top" style="font-family:verdana;font-size:14px;font-weight:bold;">Итоговая сумма:</td><td align="right" valign="top" style="font-family:verdana;font-size:14px;font-weight:bold;white-space: nowrap">' . number_format($full_itog, 2, ',', ' ') . 'руб.</td>
						 </tr>
					 </table>
					 </managedDisplay>';
            }
        } else {
            if (!$save_on_disk) {
                if ($itogo != 0) {
                    $full_itog = $itogo + $itogo_print_uslugi + $itogo_extra_uslugi;
                    $kp_content .= '<div style="text-align:right;">
					 <managedDisplay name="full_summ" style="text-align:right;display:' . (isset($dispSetObj->full_summ) ? 'none' : 'inline-block') . '">
					 <table align="right" style="margin:15px 0px 10px 0;font-family:arial" border="0">';
                    if ($itogo_print_uslugi + $itogo_extra_uslugi != 0) {
                        $kp_content .= '<tr>
							 <td width="230" height="20" align="right" valign="top" style="padding-right:2px;" >Общая стоимость сувениров:</td><td width="150" align="right" valign="top">' . number_format($itogo, 2, ',', ' ') . 'руб.</td>
						 </tr>';
                    }
                    if ($itogo_print_uslugi != 0) {
                        $kp_content .= '<tr>
							 <td align="right" height="20" valign="top">Общая стоимость нанесения:</td><td align="right" valign="top"><span id="itogo_display_setting_1_0"  style="display:' . ($display_setting_2 == 0 ? 'inline-block' : 'none') . '">' . number_format($itogo_print_uslugi1, 2, ',', ' ') . '</span><span id="itogo_display_setting_1_1" style="display:' . ($display_setting_2 == 1 ? 'inline-block' : 'none') . '">' . number_format($itogo_print_uslugi2, 2, ',', ' ') . '</span><span id="itogo_display_setting_1_2" style="display:' . ($display_setting_2 == 2 ? 'inline-block' : 'none') . '">' . number_format($itogo_print_uslugi3, 2, ',', ' ') . '</span>руб.</td>
						 </tr>';
                    }
                    if ($itogo_extra_uslugi != 0) {
                        $kp_content .= '<tr>
							 <td align="right" height="30" valign="top">Общая стоимость доп услуг:</td><td align="right" valign="top"><span id="itogo_display_setting_2_0" style="display:' . ($display_setting_2 == 0 ? 'inline-block' : 'none') . '">' . number_format($itogo_extra_uslugi1, 2, ',', ' ') . '</span><span id="itogo_display_setting_2_1" style="display:' . ($display_setting_2 == 1 ? 'inline-block' : 'none') . '">' . number_format($itogo_extra_uslugi2, 2, ',', ' ') . '</span><span id="itogo_display_setting_2_2" style="display:' . ($display_setting_2 == 2 ? 'inline-block' : 'none') . '">' . number_format($itogo_extra_uslugi3, 2, ',', ' ') . '</span>руб.</td>
						 </tr>';
                    }
                    $kp_content .= '<tr style="font-family:verdana;font-size:14px;font-weight:bold;">
							 <td align="right" valign="top">Итоговая сумма:</td><td align="right" valign="top" style="white-space: nowrap">' . number_format($full_itog, 2, ',', ' ') . 'руб.</td>
						 </tr>
					 </table>
					 </managedDisplay>';
                }
            }
        }
        $kp_content .= '<div style="text-align:right;font-family:arial;font-size:12px;line-height:20px;"><br>' . convert_bb_tags(mysql_result(select_manager_data($user_id), 0, 'mail_signature')) . '<br><br><br></div>';
        $kp_content .= '<div style="text-align:justify;font-family:verdana;font-size:10px;line-height:11px;padding:0 20px;"><br>Данная презентация носит исключительно информационный характер и никакая информация, опубликованная в ней, ни при каких условиях не является офертой или публичной офертой, определяемой положениями пункта 2 статьи 437 и статьи 435 Гражданского кодекса Российской Федерации. Для получения подробной информации о реализуемых товарах, работах и услугах и их цене необходимо обращаться к менеджерам компании Апельбург<br><br><br></div></td></tr></table></div>';
        return $kp_content;
    }
Esempio n. 2
0
		if(isset($_GET['source']) && $_GET['source']=='rt'){
			if(RT::checkPosAboutSizes($_GET['id'])==true){
				echo '{"warning":"size_exists"}';
				exit;
			}
		}
		
		include_once(ROOT."/libs/php/classes/rt_calculators_class.php");
		
		echo rtCalculators::change_quantity_and_calculators($_GET['quantity'],$_GET['id'],$_GET['print'],$_GET['extra'],$_GET['source']);
		exit;
	}
	if(isset($_GET['distribute_print'])){
		include_once(ROOT."/libs/php/classes/rt_calculators_class.php");
		
		rtCalculators::distribute_print($_GET['details']);
		exit;
	}
	if(isset($_GET['svetofor_display_relay'])){
	    // echo $_GET['ids'];
		echo RT::svetofor_display_relay($_GET['svetofor_display_relay'],$_GET['ids']);
		exit;
	}

	if(isset($_GET['set_cont_face'])){

		RT::set_cont_face($_GET['set_cont_face'],$_GET['query_num']);
		exit;
	}
   	
Esempio n. 3
0
 static function change_quantity_and_calculators_price_query($quantity, $print_details_obj, $YPriceParam)
 {
     global $mysqli;
     $level = isset($print_details_obj->level) ? $print_details_obj->level : 'full';
     $query = "SELECT*FROM `" . BASE__CALCULATORS_PRICE_TABLES_TBL . "` WHERE `print_type_id` = '" . $print_details_obj->print_id . "' AND `level` = '" . $level . "'  ORDER by id, param_val";
     //echo $query;
     $result = $mysqli->query($query) or die($mysqli->error);
     /**/
     if ($result->num_rows > 0) {
         $priceIn_tblXindex = 0;
         while ($row = $result->fetch_assoc()) {
             //print_r($row);
             if ($row['param_val'] == 0) {
                 // здесь мы определяем в какой диапазон входит новое количество
                 for ($i = 1; isset($row[$i]); $i++) {
                     // если оно меньше минимального тиража
                     //if($row[$i] > $quantity) break;
                     if ($row['price_type'] == 'in') {
                         if ($quantity < $row[1]) {
                             $newIn_Xindex = 1;
                             $lackOfQuantInPrice = true;
                             $minQuantInPrice = $row[1];
                         } else {
                             if ($row[$i] > 0 && $quantity >= $row[$i]) {
                                 $newIn_Xindex = $i;
                             }
                         }
                         if ($row[$i] > 0) {
                             $in_limit = $row[$i];
                             $in_limitIndex = $i;
                         }
                     }
                     if ($row['price_type'] == 'out') {
                         if ($quantity < $row[1]) {
                             $newOut_Xindex = 1;
                             $lackOfQuantOutPrice = true;
                             $minQuantOutPrice = $row[1];
                         } else {
                             if ($quantity >= $row[$i] && $row[$i] > 0) {
                                 $newOut_Xindex = $i;
                             }
                         }
                         if ($row[$i] > 0) {
                             $out_limit = $row[$i];
                             $out_limitIndex = $i;
                         }
                     }
                 }
             }
             // определяем новые входящие и исходящие цены
             if ($row['price_type'] == 'in' && $row['param_val'] == $YPriceParam) {
                 $new_priceIn = $row[$newIn_Xindex];
             }
             if ($row['price_type'] == 'out' && $row['param_val'] == $YPriceParam) {
                 $new_priceOut = $row[$newOut_Xindex];
             }
         }
         $out = array("price_in" => $new_priceIn, "price_out" => $new_priceOut);
         // если тираж был меньше минимального значения в прайсе пересчитываем цены
         if (isset($lackOfQuantIntPrice) && $lackOfQuantInPrice == true) {
             $out['price_in'] = $new_priceIn * $minQuantInPrice / $quantity;
             self::$lackOfQuantity = true;
             self::$lackOfQuantityDetails[] = array('minQuantity' => (int) $minQuantInPrice, 'print_type' => $print_details_obj->print_type);
         }
         if (isset($lackOfQuantOutPrice) && $lackOfQuantOutPrice == true) {
             $out['price_out'] = $new_priceOut * $minQuantOutPrice / $quantity;
             self::$lackOfQuantity = true;
             self::$lackOfQuantityDetails[] = array('minQuantity' => (int) $minQuantOutPrice, 'print_type' => $print_details_obj->print_type);
         }
         //echo $newIn_Xindex .' - '. $in_limitIndex;  echo "\r" ;
         //echo $newOut_Xindex .' - '. $out_limitIndex;
         // если полученная цена оказалась равна 0 то значит стоимость не указана
         if ((double) $out['price_in'] == 0 || (double) $out['price_out'] == 0) {
             // если это последние ряды прайс значит это лимит
             if ($newIn_Xindex == $in_limitIndex) {
                 self::$outOfLimit = true;
                 self::$outOfLimitDetails[] = array('limitValue' => (int) $in_limit, 'print_type' => $print_details_obj->print_type);
             } elseif ($newOut_Xindex == $out_limitIndex) {
                 self::$outOfLimit = true;
                 self::$outOfLimitDetails[] = array('limitValue' => (int) $out_limit, 'print_type' => $print_details_obj->print_type);
             } else {
                 //иначе это индивидуальный расчет cancelCalculator
                 if (!self::$outOfLimit) {
                     self::$needIndividCalculation = true;
                     self::$needIndividCalculationDetails[] = array('print_type' => $print_details_obj->print_type);
                 }
             }
         }
         // echo "\r \$YPriceParam - ".$YPriceParam."\r In".$newIn_Xindex.' '.$new_priceIn; echo "\r Out".$newOut_Xindex.' '.$new_priceOut."\r";
         return $out;
     }
 }
Esempio n. 4
0
 static function add_items_for_specification($dateDataObj, $specification_num, $rows_data, $client_id, $agreement_id, $agreement_date, $our_firm_acting_manegement_face, $client_firm_acting_manegement_face, $date, $short_description, $address, $prepayment)
 {
     global $mysqli;
     // print_r($dateDataObj);
     // exit;
     if (!$specification_num) {
         $query = "SELECT MAX(specification_num) specification_num FROM `" . GENERATED_SPECIFICATIONS_TBL . "` WHERE agreement_id = '" . $agreement_id . "'";
         $result = $mysqli->query($query) or die($mysqli->error);
         if ($result->num_rows > 0) {
             $row = $result->fetch_assoc();
             $specification_num = $row['specification_num'] + 1;
         } else {
             $specification_num = 1;
         }
     }
     $date_arr = explode('.', $date);
     $date = $date_arr[2] . '-' . $date_arr[1] . '-' . $date_arr[0];
     $rows_data_arr = json_decode($rows_data);
     // echo $specification_num.'<pre>'; print_r($rows_data_arr); echo '</pre>';//
     // exit;
     // настройки в завасимости от типа спецификации
     $dates_data = self::date_terms_convert($dateDataObj);
     $shipping = '0000-00-00 00:00:00';
     foreach ($rows_data_arr as $data_arr) {
         if (count($data_arr) == 0) {
             continue;
         }
         $summ_out = 0;
         $uslugi_summ_out = 0;
         $main_id = $data_arr->pos_id;
         $dop_id = $data_arr->row_id;
         $query = "SELECT*FROM `" . RT_MAIN_ROWS . "` WHERE `id` = '" . $main_id . "'";
         // echo $query."\r\n";
         $result = $mysqli->query($query) or die($mysqli->error);
         if ($result->num_rows > 0) {
             // 1). main_data
             $main_data = $result->fetch_assoc();
             $query2 = "SELECT*FROM `" . RT_DOP_DATA . "` WHERE `id` = '" . $dop_id . "'";
             // echo $query."\r\n";
             $result2 = $mysqli->query($query2) or die($mysqli->error);
             if ($result2->num_rows > 0) {
                 // 2). dop_data
                 $dop_data = $result2->fetch_assoc();
                 $expel = array("main" => 0, "print" => 0, "dop" => 0);
                 if (@$dop_data['expel'] != '') {
                     $obj = @json_decode($dop_data['expel']);
                     foreach ($obj as $expel_key => $expel_val) {
                         $expel[$expel_key] = $expel_val;
                     }
                 }
                 $summ_out = $dop_data['quantity'] * $dop_data['price_out'];
                 $name = ($main_data['art'] != '' ? 'арт.' . $main_data['art'] : '') . " " . $main_data['name'];
                 $price = $dop_data['price_out'];
                 // прежде чем записать ряд в спецификацию сверим совпадает ли количество в расчете и в услугах
                 // для этого делаем дополнительный запрос к таблице RT_DOP_USLUGI, далее после добавления ряда
                 // будет такойже запрос к таблице RT_DOP_USLUGI но уже чтобы добавить доп услуги в спецификацию
                 $query2_dop = "SELECT*FROM `" . RT_DOP_USLUGI . "` WHERE `dop_row_id` = '" . $dop_id . "' ORDER BY glob_type";
                 // echo $query."\r\n";
                 $result2_dop = $mysqli->query($query2_dop) or die($mysqli->error);
                 if ($result2_dop->num_rows > 0) {
                     while ($uslugi_data = $result2_dop->fetch_assoc()) {
                         if ($uslugi_data['glob_type'] == 'print' && $uslugi_data['quantity'] != $dop_data['quantity']) {
                             $reload['flag'] = true;
                             //echo $dop_data['quantity'];
                             include_once ROOT . "/libs/php/classes/rt_calculators_class.php";
                             $json_out = rtCalculators::change_quantity_and_calculators($dop_data['quantity'], $dop_data['id'], 'true', 'false');
                             $json_out_obj = json_decode($json_out);
                             // если расчет не может быть произведен по причине outOfLimit или needIndividCalculation
                             // сбрасываем количество тиража и нанесения до 1шт.
                             if (isset($json_out_obj->print->outOfLimit) || isset($json_out_obj->print->needIndividCalculation)) {
                                 rtCalculators::change_quantity_and_calculators(1, $dop_data['id'], 'true', 'false');
                                 $query = "UPDATE `" . RT_DOP_DATA . "` SET  `quantity` = '1'  WHERE `id` = '" . $dop_data['id'] . "'";
                                 $result = $mysqli->query($query) or die($mysqli->error);
                             }
                         }
                         /**/
                         if ($uslugi_data['glob_type'] == 'extra' && $uslugi_data['quantity'] != $dop_data['quantity']) {
                             $query = "UPDATE `" . RT_DOP_USLUGI . "` SET  `quantity` = '" . $dop_data['quantity'] . "'  WHERE `id` = '" . $uslugi_data['id'] . "'";
                             $result = $mysqli->query($query) or die($mysqli->error);
                             $uslugi_data['quantity'] = $dop_data['quantity'];
                         }
                     }
                 }
                 if (isset($reload['flag']) && $reload['flag'] == true) {
                     header('Location:' . HOST . '/?' . $_SERVER['QUERY_STRING']);
                     exit;
                 }
                 if ($main_data['type'] != 'cat') {
                     include_once ROOT . "/libs/php/classes/os_form_class.php";
                     include_once ROOT . "/libs/php/classes/cabinet/cabinet_class.php";
                     //os_form_class.php
                     $cabinet = new Cabinet();
                     $details = $cabinet->get_a_detailed_specifications($main_data['type'], $dop_data['no_cat_json']);
                     $details = strip_tags($details, '<div><br><br/><br />');
                     $details = str_replace(array('<div>', '</div>'), array('<br>', ''), $details);
                     $details = str_replace(array("\n", "\r", "\t"), '', $details);
                     $details = str_replace('<br><br>', '<br>', $details);
                     $details = preg_replace('/<div[^<]+>/', '', $details);
                     $name .= $details;
                 }
                 // записываем ряд
                 $specIdsArr[] = Agreement::insert_row($client_id, $agreement_id, $our_firm_acting_manegement_face, $client_firm_acting_manegement_face, $specification_num, $short_description, $address, $prepayment, $name, $dop_data['quantity'], $price, $dop_data['discount'], $date, $dateDataObj, $dates_data);
                 $query3 = "SELECT*FROM `" . RT_DOP_USLUGI . "` WHERE `dop_row_id` = '" . $dop_id . "' ORDER BY glob_type DESC";
                 // echo $query."\r\n";
                 $result3 = $mysqli->query($query3) or die($mysqli->error);
                 if ($result3->num_rows > 0) {
                     while ($uslugi_data = $result3->fetch_assoc()) {
                         // 3). uslugi_data
                         if ($uslugi_data['glob_type'] == 'print' && !!!$expel["print"]) {
                             include_once ROOT . "/libs/php/classes/print_calculators_class.php";
                             $name = printCalculator::convert_print_details($uslugi_data['print_details']);
                             // записываем ряд
                             $specIdsArr[] = Agreement::insert_row($client_id, $agreement_id, $our_firm_acting_manegement_face, $client_firm_acting_manegement_face, $specification_num, $short_description, $address, $prepayment, $name, $uslugi_data['quantity'], $uslugi_data['price_out'], $uslugi_data['discount'], $date, $dateDataObj, $dates_data);
                         }
                         if ($uslugi_data['glob_type'] == 'extra' && !!!$expel["dop"]) {
                             // если альтернативное название отсутствует (вводится при заведении услуги "НЕТ В СПИСКЕ")
                             if (trim($uslugi_data['other_name']) == "") {
                                 $extra_usluga_details = self::get_usluga_details($uslugi_data['uslugi_id']);
                                 $name = $extra_usluga_details ? $extra_usluga_details['name'] : 'Неопределено';
                             } else {
                                 $name = $uslugi_data['other_name'];
                             }
                             // меняем количество на 1(еденицу) если это надбавка на всю стоимость
                             $uslugi_data['quantity'] = $uslugi_data['for_how'] == 'for_all' ? 1 : $uslugi_data['quantity'];
                             // записываем ряд
                             $specIdsArr[] = Agreement::insert_row($client_id, $agreement_id, $our_firm_acting_manegement_face, $client_firm_acting_manegement_face, $specification_num, $short_description, $address, $prepayment, $name, $uslugi_data['quantity'], $uslugi_data['price_out'], $uslugi_data['discount'], $date, $dateDataObj, $dates_data);
                         }
                         /**/
                     }
                 }
             }
         }
     }
     // exit;
     // этап создания отдельного файла Спецификации и сохраниения его на диск
     // проверяем существует ли папка данного клиента если нет создаем её
     // если происходит ошибка выводим отчет
     // проверяем есть папка данного клента, если её нет то создаем её
     $client_dir_name = $_SERVER['DOCUMENT_ROOT'] . '/admin/order_manager/data/agreements/' . strval($client_id);
     //chmod("data/com_offers/", 0775);
     if (!file_exists($client_dir_name)) {
         if (!mkdir($client_dir_name, 0775)) {
             echo 'ошибка создания папки клиента (4)' . $client_dir_name;
             exit;
         }
     }
     // папка обозначающая год (название папки - название года)
     $agreement_date = explode('-', $agreement_date);
     $year_dir_name = $client_dir_name . '/' . $agreement_date[0];
     if (!file_exists($year_dir_name)) {
         if (!mkdir($year_dir_name, 0775)) {
             echo 'ошибка создания папки с именем года' . $year_dir_name;
             exit;
         }
     }
     // папка для типа договора
     $type_dir_name = $year_dir_name . '/long_term';
     if (!file_exists($type_dir_name)) {
         if (!mkdir($type_dir_name, 0775)) {
             echo 'ошибка создания папки с именем года' . $type_dir_name;
             exit;
         }
     }
     $our_requisit_id = fetchOneValFromGeneratedAgreementTbl(array('retrieve' => 'our_requisit_id', 'coll' => 'id', 'val' => $agreement_id));
     $client_requisit_id = fetchOneValFromGeneratedAgreementTbl(array('retrieve' => 'client_requisit_id', 'coll' => 'id', 'val' => $agreement_id));
     // папка для выбранных сторон
     $full_dir_name = $type_dir_name . '/' . $our_requisit_id . '_' . $client_requisit_id;
     if (!file_exists($full_dir_name)) {
         if (!mkdir($full_dir_name, 0775)) {
             echo 'ошибка создания папки с именем года' . $full_dir_name;
             exit;
         }
     }
     // папка для выбранных спецификаций
     $full_dir_name = $full_dir_name . '/specifications';
     if (!file_exists($full_dir_name)) {
         if (!mkdir($full_dir_name, 0775)) {
             echo 'ошибка создания папки с именем года' . $full_dir_name;
             exit;
         }
     }
     // записываем файл
     $file_name = $full_dir_name . '/' . $specification_num . '.tpl';
     //echo $file_name;
     //$file_name = $dir_name_full.'/com_pred_1_1.doc';
     //if(file_exists($file_name)){
     //echo 'файл с таким именем уже существует (232)';
     //exit;
     //}
     if ($dateDataObj->data_type == 'days') {
         $origin_file_name = ROOT . '/modules/agreement/agreements_templates/specification.tpl';
     }
     if ($dateDataObj->data_type == 'date') {
         $origin_file_name = ROOT . '/modules/agreement/agreements_templates/specification_type2_by_date.tpl';
     }
     $fd_origin = fopen($origin_file_name, 'r');
     $file_content = fread($fd_origin, filesize($origin_file_name));
     fclose($fd_origin);
     $fd = fopen($file_name, 'w');
     $write_result = fwrite($fd, $file_content);
     //\r\n
     fclose($fd);
     /*
     // создаем предзаказ 
     include_once(ROOT."/libs/php/classes/rt_class.php");
     
     RT::make_order($rows_data,$client_id,$_GET['query_num'],$specification_num,$agreement_id,$dateDataObj->doc_type,$dateDataObj->data_type,$dates_data['shipping_date_time'],$dates_data['item_production_term'],$dates_data['final_date_time']);
     */
     return $specification_num;
 }
Esempio n. 5
0
 static function add_data_from_basket($client_id, $manager_id_arr, $customer_data = FALSE, $dop_info = FALSE)
 {
     global $mysqli;
     // print_r($manager_id_arr); echo '--'; exit;
     $user_id = $_SESSION['access']['user_id'];
     //
     $date = date('Y-m-d H:i:s');
     // содержимое корзины
     $basket_arr = $_SESSION['basket'];
     //print_r($dop_info_arr);
     //exit;
     foreach ($basket_arr as $key => $basket_data) {
         $id = $basket_data['article'];
         $characteristics = array();
         // выбираем из базы каталога данные об артикуле
         $query = "SELECT*FROM `" . BASE_TBL . "` WHERE id = '" . $id . "'";
         $result = $mysqli->query($query) or die($mysqli->error);
         $art_data = $result->fetch_assoc();
         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
         //                                         получаем цвета артикула                                           //
         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
         $query = "SELECT color FROM `" . BASE_COLORS_TBL . "` WHERE  art_id ='" . $id . "' AND color<>''";
         $result = $mysqli->query($query) or die($mysqli->error);
         while ($item = $result->fetch_assoc()) {
             $characteristics['colors'][] = $item['color'];
         }
         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
         //                                      получаем материалы артикула                                          //
         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
         $query = "SELECT*FROM `" . BASE_MATERIALS_TBL . "` WHERE  art_id ='" . $id . "'";
         $result = $mysqli->query($query) or die($mysqli->error);
         while ($item = $result->fetch_assoc()) {
             $characteristics['materials'][] = $item['material'];
         }
         require_once ROOT . "/libs/php/classes/rt_calculators_class.php";
         $characteristics = count($characteristics) > 0 ? rtCalculators::json_fix_cyr(json_encode($characteristics)) : '';
         //print_r($dop_info);
         if ($dop_info) {
             $data_arr[$key]['dop_info'] = $dop_info[$key];
         }
         $data_arr[$key]['art_id'] = $basket_data['article'];
         $data_arr[$key]['art'] = $art_data['art'];
         $data_arr[$key]['type'] = 'cat';
         $data_arr[$key]['name'] = $art_data['name'];
         $data_arr[$key]['description'] = $art_data['description'];
         $data_arr[$key]['characteristics'] = $characteristics;
         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
         //                                      формируем  tirage_json                                               //
         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
         if (!empty($basket_data['size_id']) && $basket_data['size_id'] != 'undefined') {
             // если id размера( id строки из BASE_DOP_PARAMS_TBL) указано в корзине используем эту информацию
             $tirage_json = array();
             $tirage_json[$basket_data['size_id']] = array("dop" => "0", "tir" => $basket_data['quantity']);
             $tirage_json = json_encode($tirage_json);
         } else {
             // иначе обращаемся к BASE_DOP_PARAMS_TBL и считываем данные
             $query = "SELECT*FROM `" . BASE_DOP_PARAMS_TBL . "` WHERE  art_id ='" . $id . "'";
             $result = $mysqli->query($query) or die($mysqli->error);
             if ($result->num_rows > 0) {
                 $item = $result->fetch_assoc();
                 $tirage_json = array();
                 $tirage_json[$item['id']] = array("dop" => "0", "tir" => $basket_data['quantity']);
                 $tirage_json = json_encode($tirage_json);
             } else {
                 $tirage_json = '{}';
             }
         }
         $data_arr[$key]['dop_data'][0]['quantity'] = $basket_data['quantity'];
         $data_arr[$key]['dop_data'][0]['price_out'] = $basket_data['price'];
         $data_arr[$key]['dop_data'][0]['tirage_json'] = $tirage_json;
         unset($tirage_json);
         /*
         				// пока нет калькуляторов это не востребованно 
         				
         				
         			    // это просто пример
         				$data_arr[$key]['dop_data'][0]['dop_uslugi'][0]['glob_type'] = 'print';
         				$data_arr[$key]['dop_data'][0]['dop_uslugi'][0]['type'] = '';
         				$data_arr[$key]['dop_data'][0]['dop_uslugi'][0]['quantity'] = $basket_data['quantity'];
         				$data_arr[$key]['dop_data'][0]['dop_uslugi'][0]['price_in'] = 1;
         				$data_arr[$key]['dop_data'][0]['dop_uslugi'][0]['price_out'] = 10;
         */
     }
     $query_num = RT::create_new_query($client_id, $manager_id_arr, $data_arr);
     /**
      *	сохраняем данные введённые в форму 
      *  отправки заказа из корзины в комментарии по запросу	
      *
      *	@author  Алексей Капитонов
      *	@version 15:60 30.10.2015
      */
     // ini_set('error_reporting', E_ALL);
     // ini_set('display_errors', 1);
     // ini_set('display_startup_errors', 1);
     // -->  START  <-- //
     if ($customer_data) {
         include_once ROOT . "/libs/php/classes/comments_class.php";
         $COMMENTS = new Comments_for_query_class();
         $text = trim($customer_data['name']) != '' ? 'Имя: ' . $customer_data['name'] . '<br>' : '';
         $text .= trim($customer_data['reg_phone']) != '' ? 'Телефон: ' . $customer_data['reg_phone'] . '<br>' : '';
         $text .= trim($customer_data['email']) != '' ? 'E-mail: ' . $customer_data['email'] . '<br>' : '';
         $text .= trim(cor_data_for_SQL($customer_data['coment'])) != '' ? 'Пожелания: ' . cor_data_for_SQL($customer_data['coment']) . '<br>' : '';
         $COMMENTS->save_query_comment_Pub(0, $query_num, 'Клиент', $text);
         // -->   END   <-- //
     }
     return $query_num;
 }
Esempio n. 6
0
					 $row_counter = 0; 
					 foreach($dop_row['dop_uslugi']['print'] as $extra_data){
					     // если количество в расчете нанесения не равно количеству в колонке тираж товара 
						 // необходимо присвоить нанесениям такое же количество и пересчитать их
						//$extra_data['quantity'] = 250;
					    if($extra_data['quantity']!=$dop_row['quantity']){
						     $reload['flag'] = true;
						     //echo $dop_row['quantity'];
						     include_once(ROOT."/libs/php/classes/rt_calculators_class.php");
		                     $json_out =  rtCalculators::change_quantity_and_calculators($dop_row['quantity'],$dop_key,'true','false');
							 $json_out_obj =  json_decode($json_out);
							 
							 // если расчет не может быть произведен по причине outOfLimit или needIndividCalculation
							 // сбрасываем количество тиража и нанесения до 1шт.
							 if(isset($json_out_obj->print->outOfLimit) || isset($json_out_obj->print->needIndividCalculation)){
							     rtCalculators::change_quantity_and_calculators(1,$dop_key,'true','false');
								 
								 $query="UPDATE `".RT_DOP_DATA."` SET  `quantity` = '1'  WHERE `id` = '".$dop_key."'";
			                     $result = $mysqli->query($query)or die($mysqli->error);
							 }
							 
	
						 } /**/
						 $extra_data['price_out'] = ($extra_data['discount'] != 0 )? (($extra_data['price_out']/100)*(100 + $extra_data['discount'])) : $extra_data['price_out'];
						 $summ_in[] = $extra_data['quantity']*$extra_data['price_in'];
						 $summ_out[] = $extra_data['quantity']*$extra_data['price_out'];
						 
						 $print_details = json_decode($extra_data['print_details'],true);
						 $YPriceParamCount = (@isset($print_details['dop_params']['YPriceParam']))? count($print_details['dop_params']['YPriceParam']):'';
						 if(isset($print_details['dop_params']['sizes'][0]['id'])){
						     if(isset($print_sizes[$print_details['dop_params']['sizes'][0]['id']])) $size = $print_sizes[$print_details['dop_params']['sizes'][0]['id']];