/**
  * @Get("/{product_id:[0-9]+}/{params:[0-9a-zA-Z\-\_\.\:\,]+}", name="show-product")
  */
 public function indexAction()
 {
     $product_id = $this->filter->sanitize($this->dispatcher->getParam('product_id'), 'int');
     $lang = $this->filter->sanitize($this->dispatcher->getParam("lang"), 'string');
     // Selected product
     // Check if the product exists. Redirect to page 404 if not
     if (!($this->view->product = $product = PProductMain::findFirst($product_id))) {
         return $this->response->redirect('route404');
     }
     // Currency rate for selected currency
     $this->view->curr_rate = $curr_rate = PCrosscurrency::findFirst("title='{$this->currency}'")->currencyrate;
     // Delivery
     $expected_delivery = $product->oneProductTime + 25;
     $this->view->expected_delivery = date("d.m.Y", strtotime("now + {$expected_delivery} days"));
     //        $this->view->delivery = $delivery = $this->prodInfoService->deliveryCost($product, $delivery_zone);
     // List of categories to which the product belongs to
     $cat_tree = PCategory::getProductCatTree($product_id, $this->lang)->toArray();
     $cats = [];
     foreach ($cat_tree as $cat) {
         $cats[] = ['title' => $cat['title0'], 'catid' => $cat['catid0'], 'uri' => $cat['uri0']];
         $cats[] = ['title' => $cat['title1'], 'catid' => $cat['catid1'], 'uri' => $cat['uri1']];
         if (isset($cat['title2'])) {
             $cats[] = ['title' => $cat['title2'], 'catid' => $cat['catid2'], 'uri' => $cat['uri2']];
         }
         break;
     }
     $this->view->categories = $cats;
     // More from maker
     $params = ['index' => 'mhdev_' . $lang, 'type' => 'products', 'body' => ['query' => ['function_score' => ['query' => ['match' => ['maker_id' => $product->maker_id]], 'random_score' => new stdClass()]], 'size' => 6]];
     $this->view->maker_products = $this->elasticsearch->search($params)['hits']['hits'];
     // Most saleable
     $params = ['index' => 'mhdev_' . $lang, 'type' => 'products', 'body' => ['size' => 6, 'sort' => ['rating' => ['order' => 'desc']]]];
     $this->view->most_saleable = $this->elasticsearch->search($params)['hits']['hits'];
     $this->view->productId = "/" . $product_id;
     // Discount rate
     $this->view->discount = isset($product->productdiscount) ? $product->productdiscount : null;
     // URL of the page
     $this->view->current_url = $current_url = $this->request->getScheme() . '://' . $this->request->getHttpHost() . $this->request->getURI();
     // Shortened URL (goo.gl)
     $this->view->short_url = $this->prodInfoService->shortUrl($current_url);
     // Product title in respective language
     $this->view->prod_title = $product->getsingleInfo("lang='{$lang}'")->title;
     // Product availability (hold=1)
     $this->view->is_available = $product->hold == 1;
     //---------------------------------------------------------
     $router = $this->di['router'];
     $router->handle();
     //        var_dump($router->getMatchedRoute()->getpaths());
     $routeName = $router->getMatchedRoute()->getname();
     //        $langsAct = PLangs::find(["act=1 AND alias != '{$lang}'", 'order' => 'id']);
     $catUrls = PProdInfo::find("product_id={$product_id} AND coder_status=5 AND lang != '{$lang}'");
     $langsUrls = [];
     foreach ($catUrls as $l) {
         $langsUrls[$l->lang] = $this->url->get(array('for' => $routeName, 'lang' => $l->lang, 'product_id' => $product_id, 'params' => $l->url . '.html'));
     }
     $this->view->langs = $langsUrls;
     //---------------------------------------------------------
 }
 public function indexAction($product_id = null)
 {
     if ($product_id != null) {
         if ($product = PProductMain::findFirst($product_id)) {
             $this->view->product = $product;
         } else {
             return $this->response->redirect('infopanel');
         }
     }
 }
 public function index2Action($maker_id = null)
 {
     if ($maker_id != null) {
         $maker_id = $this->filter->sanitize($maker_id, 'int');
         if ($maker = PMaker::findFirst($maker_id)) {
             $this->view->products = $products = PProductMain::find("maker_id={$maker_id}");
             $this->view->maker = $maker;
             $this->view->count = PProductMain::count("maker_id={$maker_id}");
             if ($this->request->isPost()) {
                 $args = ['main_comment' => ['filter' => FILTER_SANITIZE_STRING], 'title' => ['filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_REQUIRE_ARRAY], 'oldprice' => ['filter' => FILTER_SANITIZE_NUMBER_FLOAT, 'flags' => FILTER_REQUIRE_ARRAY], 'comment' => ['filter' => FILTER_SANITIZE_STRING, 'flags' => FILTER_REQUIRE_ARRAY]];
                 $inpData = filter_input_array(INPUT_POST, $args);
                 $main_comment = $inpData['main_comment'];
                 $title = $inpData['title'];
                 $oldprice = $inpData['oldprice'];
                 $comment = $inpData['comment'];
                 $body = "";
                 if (!empty($main_comment)) {
                     $body = "Комментарий: {$main_comment}<br><br>";
                 }
                 $body .= "<table width='100%' border='1' cellpadding='2' cellspacing='1'>";
                 $body .= "<tr><td>ID</td><td>Название</td><td>Старая цена</td><td>Комментарий</td></tr>";
                 foreach ($comment as $product_id => $value) {
                     if (!$value) {
                         continue;
                     }
                     $body .= "<tr>\n                        <td>{$product_id}</td>\n                        <td>{$title[$product_id]}</td>\n                        <td>{$oldprice[$product_id]} {$maker->currencystr}</td>\n                        <td>{$value}</td>\n                      </tr>";
                 }
                 $body .= "</table>";
                 // Compose a message
                 $msg = ['To' => $this->config->emails->usercab2, 'From' => $this->config->POSTMARK->POSTMARK_FROM, 'Subject' => "Комментарии от мастера - {$maker->name}", 'HtmlBody' => "<html><body>{$body}</body></html>"];
                 try {
                     $client = new PostmarkClient($this->config->POSTMARK->POSTMARK_API);
                     $send = $client->sendEmailBatch([$msg]);
                     $this->flash->success('Сохранено!');
                 } catch (PostmarkException $ex) {
                     if ($ex) {
                         $this->flash->error('Произошла ошибка!');
                     }
                 }
             }
         } else {
             $this->flash->error('Мастер с таким ID не найден!');
             $this->response->redirect('usercab/index2');
         }
     }
 }
Example #4
0
 public function addByIDAction()
 {
     $request = $this->request;
     $response = $this->response;
     $flash = $this->flash;
     if ($request->isPost()) {
         $product_id = $request->getPost('product_id', 'int');
         $mplace_id = $request->getPost('mplace_id', 'int');
         $lang = $request->getPost('lang', 'string');
         $product = PProductMain::findFirst($product_id);
         $mplace = Marketplace::findFirst($mplace_id);
         // Validations
         if (!$product) {
             $flash->error('Ошибка: товар не найден!');
             return $response->redirect('seller/addbyid');
         }
         if ($product->hold == 1) {
             $flash->error('Ошибка: товар на холде!');
             return $response->redirect('seller/addbyid');
         }
         if (!$mplace) {
             $flash->error('Ошибка: площадка не найдена!');
             return $response->redirect('seller/addbyid');
         }
         if (!preg_match("/{$lang}/", $mplace->prefs)) {
             $flash->error('Ошибка: язык не соответствует площадке!');
             return $response->redirect('seller/addbyid');
         }
         // Check for appropriate marketseller
         $marketseller = Marketseller::findFirst("user_id={$this->auth->id} AND marketplace_id={$mplace_id} AND tmaterial_id={$product->tmaterial_id} AND langcode LIKE '%{$lang}%'");
         // If there is no marketseller or if the product is already placed create a new marketseller
         if (!$marketseller or MPlacement::findFirst("marketseller_id={$marketseller->id} AND product_id={$product->id}")) {
             $mseller = new Marketseller();
             $mseller->id = $mseller->id();
             $mseller->created = time();
             $mseller->updated = time();
             $mseller->fio = "{$product->PCategoryGroup->title} на {$mplace->title}";
             $mseller->user_id = $this->auth->id;
             $mseller->marketplace_id = $mplace_id;
             $mseller->tmaterial_id = $product->tmaterial_id;
             $mseller->langcode = $mplace->prefs;
             if (!$mseller->create()) {
                 $flash->error('Ошибка при создании нового виртуального магазина!');
                 return $response->redirect('seller/addbyid');
             } else {
                 return $response->redirect("seller/product/{$mseller->id}/{$product_id}/{$lang}");
             }
         } else {
             return $response->redirect("seller/product/{$marketseller->id}/{$product_id}/{$lang}");
         }
     }
 }
 public function saveBulkAction()
 {
     $this->view->disable();
     if ($this->request->isAjax()) {
         $status = 1;
         $list_of_ids = $this->request->get('list');
         $input = $this->request->get('input');
         $pernum = $this->request->get('pernum');
         $curr = $this->request->get('curr');
         $list_of_ids = json_decode($list_of_ids, true);
         $curr_rate = PCrosscurrency::findFirst("title='{$curr}'")->currencyrate;
         foreach ($list_of_ids as $id) {
             $products = PProductMain::find("id={$id} OR parent={$id}");
             foreach ($products as $product) {
                 $info = "{$product->oneProductPrice} {$product->holdpriceusd} {$product->priceUSD}";
                 if ($pernum == 'number') {
                     // Maker price in maker currency
                     $new_maker_price = round($product->oneProductPrice + $input);
                     // Maker price USD
                     $new_maker_price_usd = round($new_maker_price / $curr_rate, 2);
                     // Export price USD
                     $new_export_price_usd = $this->modelService->calcProductPrice($new_maker_price_usd);
                 } elseif ($pernum == 'percent') {
                     // Maker price in maker currency
                     $new_maker_price = round($product->oneProductPrice + $product->oneProductPrice / 100 * $input);
                     // Maker price USD
                     $new_maker_price_usd = round($new_maker_price / $curr_rate, 2);
                     // Export price USD
                     $new_export_price_usd = $this->modelService->calcProductPrice($new_maker_price_usd);
                 }
                 // Save new prices
                 $product->oneProductPrice = $new_maker_price;
                 $product->holdpriceusd = $new_maker_price_usd;
                 $product->priceUSD = $new_export_price_usd;
                 if (!$product->save()) {
                     $status = 0;
                 } else {
                     $this->modelService->setStat('price_changed', 'priceMaker', 'ru', $product->id, null, $info);
                     $this->modelService->syncElastic(['product_id' => $product->id]);
                 }
             }
         }
         $status == 1 ? $this->flash->success('Цены успешно изменены!') : $this->flash->error('Произошла ошибка при изменении цен!');
         echo $status;
     }
 }
Example #6
0
 /**
  * Table of moderated products grouped by languages and statuses
  */
 public function moderatedAction()
 {
     $stats['done'] = PProdInfo::count(["coder_status = 5", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['done_hold'] = PStats::count(["coder_status = 5 AND hold = 1", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['inmoder'] = PProdInfo::count(["coder_status = 3", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['inmoder_hold'] = PStats::count(["coder_status = 3 AND hold = 1", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['returned'] = PProdInfo::count(["coder_status = 6", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['returned_hold'] = PStats::count(["coder_status = 6 AND hold = 1", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['todo_hold'] = PStats::count(["coder_status < 3 AND hold = 1", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['translator'] = PProdInfo::count(["coder_status = 1", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['translator_hold'] = PStats::count(["coder_status = 1 AND hold = 1", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['hold_total'] = PStats::count(["hold = 1", 'group' => 'lang', 'order' => 'id'])->toArray();
     $stats['langs'] = PProdInfo::count(['group' => 'lang', 'order' => 'id'])->toArray();
     $this->view->total_ru = PStats::count("coder_status = 5 AND lang = 'ru'");
     $this->view->total = PProductMain::count();
     $this->view->total_hold = PProductMain::count("hold=1");
     $this->view->total_hold_photocoder = PProductMain::count("hold=1 AND status<4");
     $this->view->stats = $stats;
     $this->view->current_date = date('H:i:s d.m.Y');
 }
Example #7
0
 /**
  * Main processing script
  *
  * @throws Exception
  */
 public function processAction()
 {
     $this->view->disable();
     if ($this->request->isAjax()) {
         // Set transaction manager
         $transactionManager = new TransactionManager();
         $transaction = $transactionManager->get();
         $root = $this->root;
         $upload_dir_full = $this->upload_dir_full;
         $processed_dir = $this->processed_dir;
         // Create processed folder if it doesn't exist
         if (!file_exists($processed_dir)) {
             mkdir($processed_dir, 0777, true);
         }
         $qrs = $this->persistent->qrs;
         $errors = $this->persistent->errors;
         $created_prods_counter = $this->persistent->created_prods_counter;
         $created_prods_ids = $this->persistent->created_prods_ids;
         $id = $this->request->get('id');
         $item = self::filter($upload_dir_full, "{$id}")[$id];
         // A product must have a minimum of 3 photos
         if (count($item, true) - 1 < 4) {
             $this->errorExit($errors, $id, "У товара должно быть минимум три фотографии!");
         }
         // Check for file name (should not contain alphabetic characters)
         foreach ($item as $i => $f) {
             if (preg_match_all('/[A-Za-z]+\\d*\\./', "{$upload_dir_full}/{$f}")) {
                 $this->errorExit($errors, $id, "Неправильное название файла ({$f})");
             }
         }
         // QR code image
         $qrcode_img = $item[0];
         // Get scanned QR code
         if ($qrs[$id] != false) {
             $code = $qrs[$id];
         } else {
             $this->errorExit($errors, $id, "Не удалось отсканировать QR код ({$qrcode_img})");
         }
         // Check for product existence
         if (PProductMain::findFirst($code)) {
             $this->errorExit($errors, $id, "Товар с таким QR кодом уже внесен в базу ({$code})");
         }
         // -----------------------------------------------------------
         // QR code processing
         $qrcode_info = pathinfo($qrcode_img);
         $qrcode_name = "{$qrcode_info['filename']}qr{$code}";
         $qrcode_folder = rand(111, 999) . "/" . rand(1111111, 99999999) . "/";
         $width = getimagesize("{$upload_dir_full}/{$qrcode_img}")[0];
         $height = getimagesize("{$upload_dir_full}/{$qrcode_img}")[1];
         $filesize = filesize("{$upload_dir_full}/{$qrcode_img}");
         // Create folders for a QR code
         mkdir($root . $this->config->upload->media_qrcodeimage_folder . "/" . $qrcode_folder, 0777, true);
         mkdir($root . $this->config->upload->media_qrcodeimage_nail_folder . "/" . $qrcode_folder, 0777, true);
         // Copy QR code image to the respective folder
         if (!copy("{$upload_dir_full}/{$qrcode_img}", $root . $this->config->upload->media_qrcodeimage_folder . "/" . $qrcode_folder . $qrcode_name . "." . $qrcode_info['extension'])) {
             $this->errorExit($errors, $id, "Ошибка при копировании изображения QR кода ({$qrcode_img})");
         }
         $qrimg = new SimpleImage("{$upload_dir_full}/{$qrcode_img}");
         // Resize QR code image for a thumbnail (100 px) and copy it to nail folder
         if (!$qrimg->fit_to_width(100)->save($root . $this->config->upload->media_qrcodeimage_nail_folder . "/" . $qrcode_folder . $qrcode_name . "." . $qrcode_info['extension'])) {
             $this->errorExit($errors, $id, "Ошибка при копировании изображения (nail) QR кода ({$qrcode_img})");
         }
         // Add QR code to the db
         $qrcode = new PProdQrcodeimage();
         $qrcode->setTransaction($transaction);
         $qrcode->product_id = $code;
         $qrcode->uri = $qrcode_name;
         $qrcode->ext = $qrcode_info['extension'];
         $qrcode->width = $width;
         $qrcode->height = $height;
         $qrcode->filesize = $filesize;
         $qrcode->folder = $qrcode_folder;
         $qrcode->thumbnail = "/thumb/qrcodeimage/nail/{$qrcode_folder}{$qrcode_name}.{$qrcode_info['extension']}";
         $qrcode->ordered = $qrcode->ordered();
         $qrcode->created = time();
         $qrcode->updated = time();
         if (!$qrcode->create()) {
             $transactionManager->collectTransactions();
             // Clear transactions
             $this->errorExit($errors, $id, "Ошибка при добавлении QR кода в базу данных ({$qrcode_img})");
         }
         // Remove QR code from the array
         array_shift($item);
         // -----------------------------------------------------------
         // Photos processing
         $photo_counter = 1;
         foreach ($item as $img) {
             // A product can have a maximum of 5 photos
             if ($photo_counter > 5) {
                 break;
             }
             // Change photo orientation if needed
             //                self::changeOrientation("$upload_dir_full/$img");
             $img_info = pathinfo($img);
             $rand = rand(1111, 9999);
             $width = getimagesize("{$upload_dir_full}/{$img}")[0];
             $height = getimagesize("{$upload_dir_full}/{$img}")[1];
             $filesize = filesize("{$upload_dir_full}/{$img}");
             $img_name = "IMG_{$rand}_{$height}";
             $img_folder = rand(111, 999) . "/" . rand(1111111, 99999999) . "/";
             // Create folders
             mkdir($root . $this->config->upload->media_productphoto_folder . "/" . $img_folder, 0777, true);
             mkdir($root . $this->config->upload->media_productphoto_thumb_folder . "/" . $img_folder, 0777, true);
             mkdir($root . $this->config->upload->media_productphoto_nail_folder . "/" . $img_folder, 0777, true);
             // Resave an image to remove EXIF data
             if (self::removeExif("{$upload_dir_full}/{$img}") == false) {
                 $this->errorExit($errors, $id, "Ошибка при обработке фотографии ({$img})");
             }
             // Copy an image to the respective folder
             if (!copy("{$upload_dir_full}/{$img}", $root . $this->config->upload->media_productphoto_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии ({$img})");
             }
             // Resize an image for a thumbnail (500 px) and copy it to thumb folder
             $thumb_img = new SimpleImage("{$upload_dir_full}/{$img}");
             if (!$thumb_img->fit_to_width(500)->save($root . $this->config->upload->media_productphoto_thumb_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии (thumb) ({$img})");
             }
             // Resize an image for a thumbnail (100 px) and copy it to nail folder
             $nail_img = new SimpleImage("{$upload_dir_full}/{$img}");
             if (!$nail_img->fit_to_width(100)->save($root . $this->config->upload->media_productphoto_nail_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии (nail) ({$img})");
             }
             // Add image to the db
             $imgdb = new PProdPhoto();
             $imgdb->setTransaction($transaction);
             $imgdb->uri = $img_name;
             $imgdb->ext = $img_info['extension'];
             $imgdb->width = $width;
             $imgdb->height = $height;
             $imgdb->filesize = $filesize;
             $imgdb->folder = $img_folder;
             $imgdb->thumbnail = "/thumb/productphoto/nail/{$img_folder}{$img_name}.{$img_info['extension']}";
             $imgdb->product_id = $code;
             $imgdb->ordered = $photo_counter;
             $imgdb->created = time();
             $imgdb->updated = time();
             if (!$imgdb->create()) {
                 $transactionManager->collectTransactions();
                 // Clear transactions
                 $this->errorExit($errors, $id, "Ошибка при добавлении фотографий в базу данных ({$img})");
             }
             $photo_counter++;
         }
         // Create a new product
         $product = new PProductMain();
         $product->setTransaction($transaction);
         $product->id = $code;
         $product->created = time();
         $product->updated = time();
         $product->new = 1;
         $product->hasphoto = 1;
         $product->qrcodeimage_id = $qrcode->id;
         $product->status = 0;
         if (!$product->create()) {
             $transactionManager->collectTransactions();
             // Clear transactions
             $this->errorExit($errors, $id, "Ошибка при создании товара (QR - {$code})");
         }
         // Complete the transaction
         if (!$transaction->commit()) {
             $this->errorExit($errors, $id, "Ошибка транзакции (QR - {$code})");
         }
         // Set stats
         $this->ProdInfoService->setStat('product_created', 'photoUploader', 'ru', $code);
         // Move QR code image
         rename("{$upload_dir_full}/{$qrcode_img}", "{$processed_dir}/{$qrcode_name}.{$qrcode_info['extension']}");
         // Clear thumb for QR code img
         //            if (file_exists("$upload_dir_full/thumbs/$qrcode_img")) unlink("$upload_dir_full/thumbs/$qrcode_img");
         foreach ($item as $img) {
             // Move images
             rename("{$upload_dir_full}/{$img}", "{$processed_dir}/{$img}");
             // Clear thumbs
             //                if (file_exists("$upload_dir_full/thumbs/$img")) unlink("$upload_dir_full/thumbs/$img");
         }
         // Remove the id from QRs list
         $qrs = $this->persistent->qrs;
         unset($qrs[$id]);
         // Update counter and list of ids
         $created_prods_counter++;
         $created_prods_ids[] = $code;
         $this->persistent->qrs = $qrs;
         $this->persistent->created_prods_counter = $created_prods_counter;
         $this->persistent->created_prods_ids = $created_prods_ids;
         // Hooray!
         echo "success";
     }
 }
Example #8
0
    public function moderAction()
    {
        $stats = [];
        $stats['done'] = PProdInfo::count(["coder_status = 5", 'group' => 'lang', 'order' => 'id']);
        $stats['done_hold'] = PStats::count(["coder_status = 5 AND hold = 1", 'group' => 'lang', 'order' => 'id']);
        $stats['inmoder'] = PProdInfo::count(["coder_status = 3", 'group' => 'lang', 'order' => 'id']);
        $stats['inmoder_hold'] = PStats::count(["coder_status = 3 AND hold = 1", 'group' => 'lang', 'order' => 'id']);
        $stats['returned'] = PProdInfo::count(["coder_status = 6", 'group' => 'lang', 'order' => 'id']);
        $stats['returned_hold'] = PStats::count(["coder_status = 6 AND hold = 1", 'group' => 'lang', 'order' => 'id']);
        $stats['todo_hold'] = PStats::count(["coder_status < 3 AND hold = 1", 'group' => 'lang', 'order' => 'id']);
        $stats['hold_total'] = PStats::count(["hold = 1", 'group' => 'lang', 'order' => 'id']);
        $langs = PProdInfo::count(['group' => 'lang', 'order' => 'id']);
        $total_ru = PStats::count("coder_status = 5 AND lang = 'ru'");
        $total = PProductMain::count();
        $date = date('d.m.Y');
        $titles = ["Сделано (5) (из них на холде)", "На модерации (3) (из них на холде)", "Возвращено (6) (из них на холде)", "Не обработано еще (0) (из них на холде)", "Замороженые товары (hold), всего"];
        $stat_titles = ["done", "inmoder", "returned"];
        $text = <<<TEXT
<p style="margin-bottom: 20px">Всего товаров: <span id="total">{$total}</span></p>
<p style="margin-bottom: 20px">Отчет на {$date}</p>
<table border='1'>
<tr>
<th></th>
TEXT;
        foreach ($langs as $lang => $stat) {
            $text .= "<th width='110px'>{$stat['lang']}</th>";
        }
        $text .= "</tr>";
        for ($i = 0; $i < 3; $i++) {
            $text .= "<tr><td>{$titles[$i]}</td>";
            foreach ($langs as $lang => $stat) {
                $text .= "<td>";
                foreach ($stats[$stat_titles[$i]] as $lang_total => $stat_total) {
                    if ($stat_total['lang'] == $stat['lang']) {
                        $text .= $stat_total['rowcount'] . " ";
                        foreach ($stats[$stat_titles[$i] . '_hold'] as $lang_hold => $stat_hold) {
                            if ($stat_hold['lang'] == $stat['lang']) {
                                $text .= "({$stat_hold['rowcount']})";
                            }
                        }
                    }
                }
                $text .= "</td>";
            }
            $text .= "</tr>";
        }
        $text .= "<tr><td>{$titles[3]}</td>";
        foreach ($langs as $lang => $stat) {
            $text .= "<td>";
            if ($stat['lang'] == 'ru') {
                $text .= $total - $stat['rowcount'];
            } else {
                $text .= $total_ru - $stat['rowcount'];
            }
            foreach ($stats['todo_hold'] as $lang_hold => $stat_hold) {
                if ($stat_hold['lang'] == $stat['lang']) {
                    $text .= "({$stat_hold['rowcount']})";
                }
            }
            $text .= "</td>";
        }
        $text .= "</tr>";
        $text .= "<tr><td>{$titles[4]}</td>";
        foreach ($langs as $lang => $stat) {
            $text .= "<td>";
            foreach ($stats['hold_total'] as $lang_hold => $stat_hold) {
                if ($stat_hold['lang'] == $stat['lang']) {
                    $text .= "{$stat_hold['rowcount']}";
                }
            }
            $text .= "</td>";
        }
        $text .= "</tr></table>";
        $text .= <<<TEXT
<br><br><b>Описание</b>
<p>Сделано (5) - товары со статусом перевода на данный язык == 5 ( в случае с RU статус копирайта == 5)</p>
<p>На модерации (3) - товары со статусом перевода на данный язык == 3 ( в случае с RU статус копирайта == 3)</p>
<p>Возвращено (6) - товары со статусом перевода на данный язык == 6 ( в случае с RU статус копирайта == 6)</p>
<p>Не обработано еще (0) - товары со статусом перевода на данный язык == 0 ( в случае с RU статус копирайта == 0)</p>
<p>Замороженые товары (hold) - товары со статусом hold == Да</p>
TEXT;
        $message[] = ['To' => '*****@*****.**', 'From' => POSTMARK_FROM, 'Subject' => "Количество отмодерированных товаров. Отчет за {$date}", 'HtmlBody' => $text];
        $client = new PostmarkClient(POSTMARK_API);
        //        var_dump($message);
        $send = $client->sendEmailBatch($message);
    }
Example #9
-1
 /**
  * Export selected category in Excel
  *
  * @param $category
  * @param $lang
  * @param $currency
  * @param $location
  */
 public function exportAction($category, $lang, $currency, $location)
 {
     $this->view->disable();
     $cats = PCategory::getCatTree($category, $lang);
     $currency = strtoupper($currency);
     $rate = PCrosscurrency::findFirst("title='{$currency}'")->currencyrate;
     $prods = PProductMain::find(["hold = 0\n            AND notforsale = 0\n            AND category_id IN ({$cats})"]);
     //        var_dump($prods->toArray());
     // Create files directory if it doesn't exist
     if (!file_exists(ROOT . "/public/files")) {
         mkdir(ROOT . "/public/files", 0777);
     }
     $rnd = $currency == 'UAH' || $currency == 'RUB' ? 0 : 2;
     $list = [];
     $list[] = ['ID', 'Название', "Цена, {$currency}", "Доставка, {$currency}", 'URL'];
     $i = 1;
     foreach ($prods as $prod) {
         $list[$i] = [$prod->id, htmlspecialchars_decode($prod->getsingleInfo("lang='{$lang}'")->title), round($prod->priceUSD * $rate, $rnd), $this->unitConvert->deliveryCost($prod, $location) * $rate, "https://madeheart.com/{$lang}/{$prod->id}/" . htmlspecialchars_decode($prod->getsingleInfo("lang='{$lang}'")->url) . ".html"];
         $i++;
     }
     //        var_dump($list);
     $random = rand(111111, 999999);
     $csv_file = "files/csv_{$random}.csv";
     $excel_file = "files/excel_{$random}.xls";
     $csv = fopen($csv_file, 'w');
     foreach ($list as $item) {
         fputcsv($csv, $item);
     }
     fclose($csv);
     $excel = new SimpleExcel('csv');
     $excel->parser->loadFile($csv_file);
     $excel->convertTo('xml');
     $excel->writer->saveFile('file', $excel_file);
     readfile($excel_file);
     header('Content-Disposition: attachment; filename=list.xls');
     unlink($csv_file);
     unlink($excel_file);
 }