Пример #1
0
function make_com_offer($id_arr, $stock, $order_num, $client_manager_id, $control_num)
{
    global $db;
    global $client_id;
    global $user_id;
    $order_num = $order_num != 'false' && $order_num != '' ? $order_num : '00000';
    $client_manager_id = $client_manager_id != 'false' && $client_manager_id != '' ? $client_manager_id : false;
    $com_offer_descriptions = array();
    $com_offer_description_length = 80;
    $prefix = '../admin/order_manager/';
    //echo $order_num.' '.$client_manager_id;
    $cont_face_data_arr = get_client_cont_face_by_id($client_id, $client_manager_id, true);
    $client_data_arr = select_all_client_data($client_id);
    //print_r($cont_face_data_arr);
    //exit;
    // собираем контент коммерческого предложения
    $file_content = '<div style="width:625px;background-color:#FFFFFF;"><div style="text-align:right;font-family:verdana;font-size:12px;font-weight:bold;line-height:16px;"><br>В компанию: ' . $client_data_arr['comp_full_name'] . '<br>Кому: ' . $cont_face_data_arr['name'] . '<br>Контакты: ' . $cont_face_data_arr['phone'] . '<br>' . $cont_face_data_arr['email'] . '<br><br></div>
		<div style="font-family:verdana;font-size:18px;padding:10px;color:#10B050;text-align:center">Коммерческое предложение</div>';
    $file_content .= '<table width="625"  style="border:#CCCCCC solid 1px; border-collapse:collapse;background-color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;" valign="top">';
    $tr_td = '<tr><td style="border:#CCCCCC solid 1px;" width="300" valign="middle" align="center">';
    $td_tr = '</td></tr>';
    $td_td = '</td><td style="border:#CCCCCC solid 1px;padding:6px;" width="325" valign="top">';
    // этап создания контента меню
    // принцип следующий сортируем id в порядке возрастания, и считываем ряды из таблицы в порядке возрастания, при считывании        // рядов первоначально считывается персонализация относящаяся к артикулу, записываем её данные в массив, когда доходим до        // ряда "article" или ряда "ordinary" проверям были ли созданна переменная содержащая информацию о нанесении если да
    // записываем данные по нанесению которые были считанны до этого в общую строку, предварительно развернув массив
    // с этими данными, затем переменную с данными о нанесении удаляем, если нет добавляем пустую запись
    // собранную сроку записываем в итоговый массив который перед записью в файл разворачиваем
    // если в конце всей обработки были считанны данные по нанесению но строка артикул в итоге не последовала
    // тогда эти данные добавляются в итоговый массив без данных об артикуле, на последнем шаге
    // перед разворотом массива и записью данных в файл
    // этап создания файла КП и сохраниения его на диск
    // проверяем существует ли папка данного клиента если нет создаем её
    // если происходит ошибка выводим отчет
    // проверяем существует ли файл с таким названием если сушествует выводим предупреждение
    // создаем и записываем файл если происходит ошибка выводим отчет
    /**/
    natsort($id_arr);
    $string = $article_string = $ordinary_string = $print_string = $itog_string = '';
    // схема:
    //  1).   блокируем таблицу CALCULATE_TBL
    //        блокируем таблицу CALCULATE_TBL_PROTOCOL
    //  2).        получаем id
    //  3).   производим изменения в таблице CALCULATE_TBL
    //  4).        разблокируем таблицы CALCULATE_TBL и CALCULATE_TBL_PROTOCOL
    //  1)
    mysql_query("LOCK TABLES " . CALCULATE_TBL . " WRITE, " . CALCULATE_TBL_PROTOCOL . " WRITE, " . COM_PRED_LIST_OLD . " WRITE , " . LAST_COM_PRED_NUM . " WRITE, " . BASE_TBL . " READ ") or die(mysql_error());
    $previos_marker_summ_print = '';
    foreach ($id_arr as $id_row) {
        //  2)
        $row_id = check_changes_to_rt_protocol($control_num, $id_row);
        if ($row_id == false) {
            mysql_query("UNLOCK TABLES") or die(mysql_error());
            return;
        }
        //  3)
        $query = "SELECT*FROM `" . CALCULATE_TBL . "` WHERE `id` = '" . $row_id . "'";
        $result = mysql_query($query, $db);
        if (!$result) {
            echo mysql_error();
        }
        $item = mysql_fetch_assoc($result);
        if ($item['type'] == 'article') {
            $article_string = $tr_td;
            // проверяем наличие изображения
            $query_dop = "SELECT*FROM `" . BASE_TBL . "` WHERE `art` = '" . $item['article'] . "'";
            $result_dop = mysql_query($query_dop, $db);
            if (!$result_dop) {
                echo mysql_error();
            }
            $item_dop = mysql_fetch_assoc($result_dop);
            $id = $item_dop['id'];
            $img_path = '../../img/' . $item_dop['image'] . '.jpg';
            $img_src = checkImgExists($img_path);
            //$img_path = '';
            //$img_src = '../../skins/images/img_design/icon_index_2.jpg';
            // меняем размер изображения
            $size_arr = transform_img_size($img_src, 230, 300);
            //$size_arr = array(230,300);
            //$size_arr = array(100,100);
            // вставляем изображение
            $article_string .= '<img src="' . $img_src . '" height="' . $size_arr[0] . '" width=' . $img_src[1] . '">' . $td_td;
            // количество
            $quantity = $item['quantity'];
            // стоимость
            $price = $item['discount'] == 0 ? $item['price'] : $item['price'] + $item['price'] / 100 * $item['discount'];
            $summ = $quantity * $price;
            $article = $item['marker_hidearticle'] == 'on' ? '' : 'арт.: <a href="/index.php?page=description&id=' . $id . '" target="_blank">' . $item['article'] . '</a>';
            // наименование сувенира
            $str_len = 40;
            $article_name = $item['name'];
            $article_name = nl2br($article_name);
            $article_name = iconv("UTF-8", "windows-1251//TRANSLIT", $article_name);
            if (strpos($article_name, '<br>') == true) {
                $article_name = str_replace('<br>', '<br />', $article_name);
            }
            $article_name_arr = explode('<br />', $article_name);
            $new_line = '<br />&nbsp;&nbsp;&nbsp;';
            foreach ($article_name_arr as $key => $piece) {
                if (strlen($piece) > $str_len) {
                    $piece = wordwrap($piece, $str_len, $new_line);
                    $article_name_arr[$key] = $piece;
                } else {
                    $article_name_arr[$key] = trim($piece);
                }
            }
            $article_name = implode($new_line, $article_name_arr);
            $article_name = iconv("windows-1251", "UTF-8//TRANSLIT", $article_name);
            //iconv_strlen($article_name,'UTF-8')
            $article_string .= '<b>Сувенир:</b><br />
				&nbsp;&nbsp;&nbsp;' . $article_name . '<br />
				&nbsp;&nbsp;&nbsp;' . $article . '<br />
				&nbsp;&nbsp;&nbsp;Тираж: ' . $item['quantity'] . ' шт.<br />
				&nbsp;&nbsp;&nbsp;1шт.: ' . number_format($price, 2, '.', ' ') . 'руб. / тираж: ' . number_format($summ, 2, '.', ' ') . 'руб.<br />';
            $description_str = strip_tags($article_name);
            $description_str = str_replace('<br>', ' ', $description_str);
            $description_str = str_replace('<br/>', ' ', $description_str);
            $description_str = str_replace('<br />', ' ', $description_str);
            $description_str = str_replace('&nbsp;', ' ', $description_str);
            $description_str = preg_replace('|[\\s]+|s', ' ', $description_str);
            $description_str = trim($description_str, ' ');
            $description_str = str_replace(' ', ',', $description_str);
            $com_offer_description = substr($description_str, 0, strpos($description_str, ','));
            $com_offer_description = strlen($com_offer_description) > $com_offer_description_length ? substr($com_offer_description, 0, $com_offer_description_length) : $com_offer_description;
            if (trim($com_offer_description) != '') {
                $com_offer_descriptions[] = $com_offer_description;
            }
            if ($stock) {
                $ostatok_update_time = substr($item_dop['ostatok_update_time'], 11, 5);
                $ostatok_update_date = substr($item_dop['ostatok_update_time'], 8, 2) . substr($item_dop['ostatok_update_time'], 4, 4) . substr($item_dop['ostatok_update_time'], 0, 4);
                $ostatok = $item_dop['ostatok'];
                $ostatok_block = '<div style="font-size:10px;color:#669900;">
					 &nbsp;&nbsp;&nbsp;<span style="font-size:13px;font-family:Arial;">остаток - ' . $ostatok . '</span> шт. на&nbsp; 
					 <span style="font-size:11px;font-family:Arial;">' . $ostatok_update_time . ' &nbsp;' . $ostatok_update_date . '</span>
				  </div><br />';
            } else {
                $ostatok_block = '<br />';
            }
            $short_space_str = '&nbsp;&nbsp;&nbsp;';
            $long_space_str = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
            $quantity_for_division = $quantity == 0 ? 1 : $quantity;
            if (isset($print_rows)) {
                $print_rows = array_reverse($print_rows);
                $print_string = '<b>Лого:</b><br />';
                $itog_string = '<br /><b>Стоимость сувенира + лого:</b><br />';
                for ($i = 0; $i < count($print_rows); $i++) {
                    if (count($print_rows) == 1) {
                        $print_string .= $short_space_str . str_replace('{##}', $short_space_str, $print_rows[$i][1]);
                        $itog_string .= $short_space_str . '<span style="color:#00B050;font-weight:bold;">1шт. : ' . number_format(($summ + $print_rows[$i][0]) / $quantity_for_division, 2, '.', ' ') . ' руб. / тираж: ' . number_format($summ + $print_rows[$i][0], 2, '.', ' ') . 'руб.</span><br />';
                    } else {
                        $print_string .= '<br />' . $short_space_str . ($i + 1) . '. ' . str_replace('{##}', $long_space_str, $print_rows[$i][1]);
                        $itog_string .= $short_space_str . '<span style="color:#00B050;font-weight:bold;">' . ($i + 1) . '. 1шт. : ' . number_format(($summ + $print_rows[$i][0]) / $quantity_for_division, 2, '.', ' ') . ' руб. / тираж: ' . number_format($summ + $print_rows[$i][0], 2, '.', ' ') . 'руб.</span><br />';
                    }
                }
            }
            $rows_data[] = $article_string . $ostatok_block . $print_string . $itog_string . $td_tr;
            unset($print_rows);
            $article_string = $print_string = $itog_string = '';
        } elseif ($item['type'] == 'ordinary') {
            // пустая ячейка
            $ordinary_string = $tr_td . '&nbsp;' . $td_td;
            // количество
            $quantity = $item['quantity'];
            // стоимость
            $price = $item['discount'] == 0 ? $item['price'] : $item['price'] + $item['price'] / 100 * $item['discount'];
            $summ = $quantity * $price;
            // наименование сувенира
            $str_len = 40;
            $article_name = $item['name'];
            $article_name = nl2br($article_name);
            $article_name = iconv("UTF-8", "windows-1251//TRANSLIT", $article_name);
            if (strpos($article_name, '<br>') == true) {
                $article_name = str_replace('<br>', '<br />', $article_name);
            }
            $article_name_arr = explode('<br />', $article_name);
            $new_line = '<br />&nbsp;&nbsp;&nbsp;';
            foreach ($article_name_arr as $key => $piece) {
                if (strlen($piece) > $str_len) {
                    $piece = wordwrap($piece, $str_len, $new_line);
                    $article_name_arr[$key] = $piece;
                } else {
                    $article_name_arr[$key] = trim($piece);
                }
            }
            $article_name = implode($new_line, $article_name_arr);
            $article_name = iconv("windows-1251", "UTF-8//TRANSLIT", $article_name);
            //iconv_strlen($article_name,'UTF-8')
            $ordinary_string .= '
				&nbsp;&nbsp;&nbsp;' . $article_name . '<br />
				&nbsp;&nbsp;&nbsp;Тираж: ' . $item['quantity'] . ' шт.<br />
				&nbsp;&nbsp;&nbsp;1шт.: ' . number_format($price, 2, '.', ' ') . 'руб. / тираж: ' . number_format($summ, 2, '.', ' ') . 'руб.<br /><br />';
            $short_space_str = '&nbsp;&nbsp;&nbsp;';
            $long_space_str = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
            $quantity_for_division = $quantity == 0 ? 1 : $quantity;
            if (isset($print_rows)) {
                $print_rows = array_reverse($print_rows);
                $print_string = '<b>Лого:</b><br />';
                $itog_string = '<br /><b>Стоимость сувенира + лого:</b><br />';
                for ($i = 0; $i < count($print_rows); $i++) {
                    if (count($print_rows) == 1) {
                        $print_string .= $short_space_str . str_replace('{##}', $short_space_str, $print_rows[$i][1]);
                        $itog_string .= $short_space_str . '<span style="color:#00B050;font-weight:bold;">1шт. : ' . number_format(($summ + $print_rows[$i][0]) / $quantity_for_division, 2, '.', ' ') . ' руб. / тираж: ' . number_format($summ + $print_rows[$i][0], 2, '.', ' ') . 'руб.</span><br />';
                    } else {
                        $print_string .= '<br />' . $short_space_str . ($i + 1) . '. ' . str_replace('{##}', $long_space_str, $print_rows[$i][1]);
                        $itog_string .= $short_space_str . '<span style="color:#00B050;font-weight:bold;">' . ($i + 1) . '. 1шт. : ' . number_format(($summ + $print_rows[$i][0]) / $quantity_for_division, 2, '.', ' ') . ' руб. / тираж: ' . number_format($summ + $print_rows[$i][0], 2, '.', ' ') . 'руб.</span><br />';
                    }
                }
            }
            $rows_data[] = $ordinary_string . $print_string . $itog_string . $td_tr;
            unset($print_rows);
            $ordinary_string = $print_string = $itog_string = '';
        } elseif ($item['type'] == 'print') {
            // количество
            $print_quantity = $item['quantity'];
            // стоимость
            $print_price = $item['discount'] == 0 ? $item['price'] : $item['price'] + $item['price'] / 100 * $item['discount'];
            $print_summ = $item['quantity'] * $print_price;
            // наименование нанесения
            $str_len = 38;
            $print_description = $item['name'];
            $print_description = nl2br($print_description);
            $print_description = iconv("UTF-8", "windows-1251//TRANSLIT", $print_description);
            if (strpos($print_description, '<br>') == true) {
                $print_description = str_replace('<br>', '<br />', $print_description);
            }
            $print_description_arr = explode('<br />', $print_description);
            $new_line = '<br />{##}';
            foreach ($print_description_arr as $key => $piece) {
                if (strlen($piece) > $str_len) {
                    $piece = wordwrap($piece, $str_len, $new_line);
                    $print_description_arr[$key] = $piece;
                } else {
                    $print_description_arr[$key] = trim($piece);
                }
            }
            $print_description = implode($new_line, $print_description_arr);
            $print_description = iconv("windows-1251", "UTF-8//TRANSLIT", $print_description);
            //iconv_strlen($print_description,'UTF-8')
            $string .= $print_description . '<br />
				{##}Тираж: ' . $item['quantity'] . ' шт.<br />
				{##}1шт.: ' . number_format($print_price, 2, '.', ' ') . 'руб. / тираж: ' . number_format($print_summ, 2, '.', ' ') . 'руб.<br />';
            // если предыдущий ряд был отмечен маркером marker_summ_print (объединить расчет нанесения) то объеденяем данные
            // внося их в созданный ранее эелемент массива, если нет добавляем новый элемент.
            if ($previos_marker_summ_print == 'on') {
                $print_rows[count($print_rows) - 1] = array($print_rows[count($print_rows) - 1][0] + $print_summ, $string . '<br />{##}' . $print_rows[count($print_rows) - 1][1]);
            } else {
                $print_rows[] = array($print_summ, $string);
            }
            $string = '';
            $previos_marker_summ_print = $item['marker_summ_print'];
        }
    }
    $com_pred_num = get_new_com_offer_num();
    $query = "INSERT INTO `" . COM_PRED_LIST_OLD . "` SET `client_id` = '" . $client_id . "',\n\t\t                                              `com_pred_num` = '" . $com_pred_num . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t  `order_num` = '" . $order_num . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t  `manager` = '" . $cont_face_data_arr['name'] . "',\n\t\t\t\t\t\t\t\t\t\t\t\t\t  `description` = '" . implode(', ', $com_offer_descriptions) . "'\n\t\t\t\t\t\t\t\t\t\t\t\t\t  ";
    mysql_query($query, $db) or die(mysql_error());
    //  4)
    mysql_query("UNLOCK TABLES") or die(mysql_error());
    // если в конце были данные по нанесению, но не было строки артикул, записываем их в массив данных
    if (isset($print_rows)) {
        $print_rows = array_reverse($print_rows);
        //$print_string = '<b>Лого:</b><br />';
        for ($i = 0; $i < count($print_rows); $i++) {
            $print_string .= '&nbsp;&nbsp;&nbsp;' . ($i + 1) . '. ' . $print_rows[$i][1];
        }
        $rows_data[] = $tr_td . '' . $td_td . $article_string . $print_string . $td_tr;
    }
    // записываем все данные в строку предварительно разварнув массив
    $file_content .= implode('', array_reverse($rows_data)) . '</td></tr></table>
		   <div style="text-align:right;font-family:verdana;font-size:12px;line-height:20px;"><br>' . convert_bb_tags(mysql_result(select_manager_data($user_id), 0, 'mail_signature')) . '<br><br><br></div></div>';
    // этап создания файла КП и сохраниения его на диск
    // проверяем существует ли папка данного клиента если нет создаем её
    // если происходит ошибка выводим отчет
    // проверяем существует ли файл с таким названием если сушествует выводим предупреждение
    // создаем и записываем файл если происходит ошибка выводим отчет
    // проверяем есть папка данного клента, если её нет то создаем её
    $dir_name_full = $prefix . 'data/com_offers/' . strval(intval($_GET['client_id']));
    //chmod("data/com_offers/", 0755);
    if (!file_exists($dir_name_full)) {
        if (!mkdir($dir_name_full, 0700)) {
            echo 'ошибка создания папки клиента (4)' . $dir_name_full;
            exit;
        }
    } else {
        if (!is_dir($dir_name_full)) {
            if (!unlink($dir_name_full)) {
                echo 'ошибка удаления одноименного с папкой файла (3)';
                exit;
            }
            echo 'повторите команду создания КП (3.1)';
            exit;
        }
    }
    // записываем файл
    $file_name = $dir_name_full . '/com_pred_' . date('Y_d_m__Gis') . '_' . $order_num . '_' . $com_pred_num . '.doc';
    //$file_name = $dir_name_full.'/com_pred_1_1.doc';
    if (file_exists($file_name)) {
        echo 'файл с таким именем уже существует (2)';
        exit;
    }
    $fd = fopen($file_name, 'w');
    $write_result = fwrite($fd, $file_content);
    //\r\n
    fclose($fd);
    if ($write_result) {
        echo 1;
    } else {
        echo 'ошибка создания файла коммерческого предложения (1)';
    }
    //print_r($id_arr);
    exit;
}
Пример #2
0
    static function open_in_blank_old($kp_id, $client_id, $user_id, $save_on_disk = false)
    {
        global $mysqli;
        $stock = false;
        $com_offer_descriptions = array();
        $com_offer_description_length = 80;
        $string = $article_string = $ordinary_string = $print_string = $itog_string = $previos_marker_summ_print = '';
        // Здесь делаем то что в старой версии делали при сохранении КП в файл
        $cont_face_data_arr = get_client_cont_face_by_id($client_id, $user_id, true);
        $client_data_arr = select_all_client_data($client_id);
        //print_r($cont_face_data_arr);
        //exit;
        $rows_data = self::fetch_kp_rows($kp_id);
        $rows_data = array_reverse($rows_data);
        // собираем контент коммерческого предложения
        //if($save_on_disk)//?'.$_SERVER['QUERY_STRING'].'&show_kp_in_blank='.$kp_id.'
        $kp_content = '<div style="width:675px;background-color:#FFFFFF;"><div style="text-align:right;font-family:verdana;font-size:12px;font-weight:bold;line-height:16px;"><br />В компанию: ' . $client_data_arr['comp_full_name'] . '<br />Кому: ' . $cont_face_data_arr['name'] . '<br />Контакты: ' . $cont_face_data_arr['phone'] . '<br />' . $cont_face_data_arr['email'] . '<br /><br /></div>
			<div style="font-family:verdana;font-size:18px;padding:10px;color:#10B050;text-align:center">Презентация</div>';
        $kp_content .= '<table width="675"  style="border:#CCCCCC solid 1px; border-collapse:collapse;background-color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;" valign="top">';
        $tr_td = '<tr><td style="border:#CCCCCC solid 1px;" width="300" valign="middle" align="center">';
        $td_tr = '</td></tr>';
        $td_td = '</td><td style="border:#CCCCCC solid 1px;padding:6px;" width="325" valign="top">';
        // этап создания контента меню
        // принцип следующий сортируем id в порядке возрастания, и считываем ряды из таблицы в порядке возрастания, при считывании
        // рядов первоначально считывается персонализация относящаяся к артикулу, записываем её данные в массив, когда доходим до            // ряда "article" или ряда "ordinary" проверям были ли созданна переменная содержащая информацию о нанесении если да
        // записываем данные по нанесению которые были считанны до этого в общую строку, предварительно развернув массив
        // с этими данными, затем переменную с данными о нанесении удаляем, если нет добавляем пустую запись
        // собранную сроку записываем в итоговый массив который перед записью в файл разворачиваем
        // если в конце всей обработки были считанны данные по нанесению но строка артикул в итоге не последовала
        // тогда эти данные добавляются в итоговый массив без данных об артикуле, на последнем шаге
        // перед разворотом массива и записью данных в файл
        foreach ($rows_data as $item) {
            if ($item['type'] == 'article') {
                $query = "SELECT*FROM `" . BASE_TBL . "` WHERE art = '" . $item['article'] . "'";
                $result = $mysqli->query($query) or die($mysqli->error);
                $row = $result->fetch_assoc();
                $id = $row['id'];
                $article_string = $tr_td;
                $art_img = new Art_Img($item['article']);
                // проверяем наличие изображения
                //$img_path = '../../img/'.$art_img->big;
                $img_path = 'http://www.apelburg.ru/img/' . $art_img->big;
                $img_src = checkImgExists($img_path);
                //$img_path = '';
                //$img_src = '../../skins/images/img_design/icon_index_2.jpg';
                // меняем размер изображения
                $size_arr = transform_img_size($img_src, 230, 300);
                //$size_arr = array(230,300);
                //$size_arr = array(100,100);
                // вставляем изображение
                $article_string .= '<img src="' . $img_src . '" height="' . $size_arr[0] . '" width="' . $img_src[1] . '">' . $td_td;
                // количество
                $quantity = $item['quantity'];
                // стоимость
                $price = $item['discount'] == 0 ? $item['price'] : $item['price'] + $item['price'] / 100 * $item['discount'];
                $summ = $quantity * $price;
                $article = $item['hide_article_marker'] == 'on' ? '' : 'арт.: <a href="/index.php?page=description&id=' . $id . '" target="_blank">' . $item['article'] . '</a>';
                // наименование сувенира
                $str_len = 40;
                $article_name = $item['name'];
                $article_name = nl2br($article_name);
                $article_name = iconv("UTF-8", "windows-1251//TRANSLIT", $article_name);
                if (strpos($article_name, '<br />') == true) {
                    $article_name = str_replace('<br />', '<br />', $article_name);
                }
                $article_name_arr = explode('<br />', $article_name);
                $new_line = '<br />&nbsp;&nbsp;&nbsp;';
                foreach ($article_name_arr as $key => $piece) {
                    if (strlen($piece) > $str_len) {
                        $piece = wordwrap($piece, $str_len, $new_line);
                        $article_name_arr[$key] = $piece;
                    } else {
                        $article_name_arr[$key] = trim($piece);
                    }
                }
                $article_name = implode($new_line, $article_name_arr);
                $article_name = iconv("windows-1251", "UTF-8//TRANSLIT", $article_name);
                //iconv_strlen($article_name,'UTF-8')
                $article_string .= '<b>Сувенир:</b><br />
				&nbsp;&nbsp;&nbsp;' . $article_name . '<br />
				&nbsp;&nbsp;&nbsp;' . $article . '<br />
				&nbsp;&nbsp;&nbsp;Тираж: ' . $item['quantity'] . ' шт.<br />
				&nbsp;&nbsp;&nbsp;1шт.: ' . number_format($price, 2, '.', ' ') . 'руб. / тираж: <nobr>' . number_format($summ, 2, '.', ' ') . 'руб.</nobr><br />';
                // формирование описания для коммерческого предложения помещается в списке КП-шек
                $description_str = strip_tags($article_name);
                $description_str = str_replace('<br />', ' ', $description_str);
                $description_str = str_replace('<br/>', ' ', $description_str);
                $description_str = str_replace('<br />', ' ', $description_str);
                $description_str = str_replace('&nbsp;', ' ', $description_str);
                $description_str = preg_replace('|[\\s]+|s', ' ', $description_str);
                $description_str = trim($description_str, ' ');
                $description_str = str_replace(' ', ',', $description_str);
                $com_offer_description = substr($description_str, 0, strpos($description_str, ','));
                $com_offer_description = strlen($com_offer_description) > $com_offer_description_length ? substr($com_offer_description, 0, $com_offer_description_length) : $com_offer_description;
                if (trim($com_offer_description) != '') {
                    $com_offer_descriptions[] = $com_offer_description;
                }
                if ($stock) {
                    $ostatok_update_time = substr($item_dop['ostatok_update_time'], 11, 5);
                    $ostatok_update_date = substr($item_dop['ostatok_update_time'], 8, 2) . substr($item_dop['ostatok_update_time'], 4, 4) . substr($item_dop['ostatok_update_time'], 0, 4);
                    $ostatok = $item_dop['ostatok'];
                    $ostatok_block = '<div style="font-size:10px;color:#669900;">
					 &nbsp;&nbsp;&nbsp;<span style="font-size:13px;font-family:Arial;">остаток - ' . $ostatok . '</span> шт. на&nbsp; 
					 <span style="font-size:11px;font-family:Arial;">' . $ostatok_update_time . ' &nbsp;' . $ostatok_update_date . '</span>
				  </div><br />';
                } else {
                    $ostatok_block = '<br />';
                }
                $short_space_str = '&nbsp;&nbsp;&nbsp;';
                $long_space_str = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                $quantity_for_division = $quantity == 0 ? 1 : $quantity;
                if (isset($print_rows)) {
                    $print_rows = array_reverse($print_rows);
                    $print_string = '<b>Лого:</b><br />';
                    $itog_string = '<br /><b>Стоимость сувенира + лого:</b><br />';
                    for ($i = 0; $i < count($print_rows); $i++) {
                        if (count($print_rows) == 1) {
                            $print_string .= $short_space_str . str_replace('{##}', $short_space_str, $print_rows[$i][1]);
                            $itog_string .= $short_space_str . '<span style="color:#00B050;font-weight:bold;">1шт. : ' . number_format(($summ + $print_rows[$i][0]) / $quantity_for_division, 2, '.', ' ') . ' руб. / тираж: <nobr>' . number_format($summ + $print_rows[$i][0], 2, '.', ' ') . 'руб.</nobr></span><br />';
                        } else {
                            $print_string .= '<br />' . $short_space_str . ($i + 1) . '. ' . str_replace('{##}', $long_space_str, $print_rows[$i][1]);
                            $itog_string .= $short_space_str . '<span style="color:#00B050;font-weight:bold;">' . ($i + 1) . '. 1шт. : ' . number_format(($summ + $print_rows[$i][0]) / $quantity_for_division, 2, '.', ' ') . ' руб. / тираж: <nobr>' . number_format($summ + $print_rows[$i][0], 2, '.', ' ') . 'руб.</nobr></span><br />';
                        }
                    }
                }
                $tbl_rows[] = $article_string . $ostatok_block . $print_string . $itog_string . $td_tr;
                unset($print_rows);
                $article_string = $print_string = $itog_string = '';
            } elseif ($item['type'] == 'ordinary') {
                // пустая ячейка
                $ordinary_string = $tr_td . '&nbsp;' . $td_td;
                // количество
                $quantity = $item['quantity'];
                // стоимость
                $price = $item['discount'] == 0 ? $item['price'] : $item['price'] + $item['price'] / 100 * $item['discount'];
                $summ = $quantity * $price;
                // наименование сувенира
                $str_len = 40;
                $article_name = $item['name'];
                $article_name = nl2br($article_name);
                $article_name = iconv("UTF-8", "windows-1251//TRANSLIT", $article_name);
                if (strpos($article_name, '<br />') == true) {
                    $article_name = str_replace('<br />', '<br />', $article_name);
                }
                $article_name_arr = explode('<br />', $article_name);
                $new_line = '<br />&nbsp;&nbsp;&nbsp;';
                foreach ($article_name_arr as $key => $piece) {
                    if (strlen($piece) > $str_len) {
                        $piece = wordwrap($piece, $str_len, $new_line);
                        $article_name_arr[$key] = $piece;
                    } else {
                        $article_name_arr[$key] = trim($piece);
                    }
                }
                $article_name = implode($new_line, $article_name_arr);
                $article_name = iconv("windows-1251", "UTF-8//TRANSLIT", $article_name);
                //iconv_strlen($article_name,'UTF-8')
                $ordinary_string .= '
				&nbsp;&nbsp;&nbsp;' . $article_name . '<br />
				&nbsp;&nbsp;&nbsp;Тираж: ' . $item['quantity'] . ' шт.<br />
				&nbsp;&nbsp;&nbsp;1шт.: ' . number_format($price, 2, '.', ' ') . 'руб. / тираж: <nobr>' . number_format($summ, 2, '.', ' ') . 'руб.</nobr><br /><br />';
                $short_space_str = '&nbsp;&nbsp;&nbsp;';
                $long_space_str = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                $quantity_for_division = $quantity == 0 ? 1 : $quantity;
                if (isset($print_rows)) {
                    $print_rows = array_reverse($print_rows);
                    $print_string = '<b>Лого:</b><br />';
                    $itog_string = '<br /><b>Стоимость сувенира + лого:</b><br />';
                    for ($i = 0; $i < count($print_rows); $i++) {
                        if (count($print_rows) == 1) {
                            $print_string .= $short_space_str . str_replace('{##}', $short_space_str, $print_rows[$i][1]);
                            $itog_string .= $short_space_str . '<span style="color:#00B050;font-weight:bold;">1шт. : ' . number_format(($summ + $print_rows[$i][0]) / $quantity_for_division, 2, '.', ' ') . ' руб. / тираж: <nobr>' . number_format($summ + $print_rows[$i][0], 2, '.', ' ') . 'руб.</nobr></span><br />';
                        } else {
                            $print_string .= '<br />' . $short_space_str . ($i + 1) . '. ' . str_replace('{##}', $long_space_str, $print_rows[$i][1]);
                            $itog_string .= $short_space_str . '<span style="color:#00B050;font-weight:bold;">' . ($i + 1) . '. 1шт. : ' . number_format(($summ + $print_rows[$i][0]) / $quantity_for_division, 2, '.', ' ') . ' руб. / тираж: <nobr>' . number_format($summ + $print_rows[$i][0], 2, '.', ' ') . 'руб.</nobr></span><br />';
                        }
                    }
                }
                $tbl_rows[] = $ordinary_string . $print_string . $itog_string . $td_tr;
                unset($print_rows);
                $ordinary_string = $print_string = $itog_string = '';
            } elseif ($item['type'] == 'print') {
                // количество
                $print_quantity = $item['quantity'];
                // стоимость
                $print_price = $item['discount'] == 0 ? $item['price'] : $item['price'] + $item['price'] / 100 * $item['discount'];
                $print_summ = $item['quantity'] * $print_price;
                // наименование нанесения
                $str_len = 38;
                $print_description = $item['name'];
                $print_description = nl2br($print_description);
                $print_description = iconv("UTF-8", "windows-1251//TRANSLIT", $print_description);
                if (strpos($print_description, '<br />') == true) {
                    $print_description = str_replace('<br />', '<br />', $print_description);
                }
                $print_description_arr = explode('<br />', $print_description);
                $new_line = '<br />{##}';
                foreach ($print_description_arr as $key => $piece) {
                    if (strlen($piece) > $str_len) {
                        $piece = wordwrap($piece, $str_len, $new_line);
                        $print_description_arr[$key] = $piece;
                    } else {
                        $print_description_arr[$key] = trim($piece);
                    }
                }
                $print_description = implode($new_line, $print_description_arr);
                $print_description = iconv("windows-1251", "UTF-8//TRANSLIT", $print_description);
                //iconv_strlen($print_description,'UTF-8')
                $string .= $print_description . '<br />
				{##}Тираж: ' . $item['quantity'] . ' шт.<br />
				{##}1шт.: ' . number_format($print_price, 2, '.', ' ') . 'руб. / тираж: <nobr>' . number_format($print_summ, 2, '.', ' ') . 'руб.</nobr><br />';
                // если предыдущий ряд был отмечен маркером marker_summ_print (объединить расчет нанесения) то объеденяем данные
                // внося их в созданный ранее эелемент массива, если нет добавляем новый элемент.
                if ($previos_marker_summ_print == 'on') {
                    $print_rows[count($print_rows) - 1] = array($print_rows[count($print_rows) - 1][0] + $print_summ, $string . '<br />{##}' . $print_rows[count($print_rows) - 1][1]);
                } else {
                    $print_rows[] = array($print_summ, $string);
                }
                $string = '';
                $previos_marker_summ_print = $item['marker_summ_print'];
            }
            /**/
        }
        //$tbl_rows[] = $tr_td.'proba'.$td_tr;
        // записываем все данные в строку предварительно развернув массив
        $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></div>';
        return $kp_content;
    }
Пример #3
0
		
		$main_window_tpl_name = ROOT.'/skins/tpl/clients/client_folder/business_offers/send_mail_window.tpl';
		$fd = fopen($main_window_tpl_name,'r');
		$main_window_tpl = fread($fd,filesize($main_window_tpl_name));
	    fclose($fd);
        
        // кодируем данные в формате HTML перед передачей в формате JSON
		$main_window_tpl = base64_encode($main_window_tpl); 
		
		
		$message_tpl_filenames = array('recalculation','new_kp_new_client','new_kp',);
		foreach($message_tpl_filenames as $tpl_filename){
			$tpl_path = ROOT.'/skins/tpl/common/mail_tpls/'.$tpl_filename.'.tpl';
			$fd = fopen($tpl_path,'r');
			$tpl = fread($fd,filesize($tpl_path));
			$tpl = str_replace('[MANAGER_DATA]',convert_bb_tags($manager->mail_signature),$tpl);
			fclose($fd);
			$message_tpls[] = '"'.$tpl_filename.'":"'.base64_encode($tpl).'"';
		}
		
		echo '{
		       "kp_filename":"'.$kp_filename.'",
		       "client_mails":[{"person":"менеджер - Наталья","mail":"*****@*****.**"},{"person":"директор - Елена","mail":"*****@*****.**"}],
			   "manager_mails":["'.$manager->email.'","'.$manager->email_2.'"],
			   "main_window_tpl":"'.$main_window_tpl.'",';
		if(isset($message_tpls)) echo '"message_tpls":{'.implode(',',$message_tpls).'}';
		echo '}';
	    exit;
	}
	
	if(isset($_POST['send_kp_by_mail_final_step'])){