public function getCost(Purchase $purchase)
 {
     $count = $purchase->getCount();
     $percent = 0;
     foreach ($this->stages as $cnt => $percent) {
         if ($count <= $cnt) {
             break;
         }
     }
     return $purchase->getCost() * (100 - $percent) / 100;
 }
 /**
  * @GET("profile/transactions", as="profile.transactions")
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  */
 public function index()
 {
     $user_id = \Auth::user()->id;
     $purchases = Purchase::where('user_id', $user_id)->get();
     $deposits = Deposit::where('user_id', $user_id)->get();
     $pulloffmoneys = PullOffMoney::where('user_id', $user_id)->get();
     return view('transactions.index', compact('purchases', 'deposits', 'pulloffmoneys'));
 }
Example #3
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Purchase::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'user_id' => $this->user_id, 'affiliate_id' => $this->affiliate_id, 'shop_id' => $this->shop_id, 'url_id' => $this->url_id, 'sum' => $this->sum, 'status' => $this->status, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]);
     return $dataProvider;
 }
Example #4
0
 public function edit(Request $request, $id)
 {
     if ($request->method() == 'POST') {
         $id = $request->input('id');
         $m = Billspay::find($id);
         $m->purchaseid = $request->input('purchaseid');
         $m->purchasedate = $request->input('purchasedate');
         $m->amount = $request->input('amount');
         $m->save();
         return Redirect('billspay');
     }
     $data['billspay'] = Billspay::find($id);
     $p = Purchase::get();
     return view('editbillspay', $data)->with('p', $p);
 }
Example #5
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Purchase::find();
     // add conditions that should always apply here
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => 10], 'sort' => ['defaultOrder' => ['updated_at' => SORT_DESC]]]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     // grid filtering conditions
     $query->andFilterWhere(['id' => $this->id, 'date' => $this->date, 'total' => $this->total, 'created_at' => $this->created_at, 'created_by' => $this->created_by, 'updated_at' => $this->updated_at, 'updated_by' => $this->updated_by]);
     $query->andFilterWhere(['like', 'code', $this->code])->andFilterWhere(['like', 'supplier', $this->supplier]);
     return $dataProvider;
 }
 public function save(Request $request)
 {
     $products = $request->get('products');
     $stockId = $request->get('stock_id');
     $purchase = Purchase::create(['stock_id' => $request->get('stock_id')]);
     /**
      * Precisa incrementar a quantidade de produtos no estoque pelo "ammount"
      */
     foreach ($products as $product) {
         $ammount = $request->get($product . '_ammount');
         $sp = StockProducts::query()->where('stock_id', $stockId)->where('product_id', $product)->first();
         PurchaseProducts::create(['purchase_id' => $purchase->id, 'stock_product_id' => $sp->id, 'ammount' => $ammount]);
         $sp->ammount += $ammount;
         $sp->save();
     }
     return view('pages.home');
 }
Example #7
0
 public function index()
 {
     $now = new \DateTime('now');
     $month = $now->format('m');
     $c = Purchase::get();
     $c1 = Physicalsale::get();
     $var = array($month);
     $spname = "salesreport";
     $c2 = Info::callinfo($var, $spname);
     $var1 = array($month - 1);
     $spname1 = "salesreportp";
     $c3 = Info::callinfo($var1, $spname1);
     $spname2 = "todaysales";
     $c4 = Combo::callcombo($spname2);
     $spname3 = "todaycash";
     $c5 = Combo::callcombo($spname3);
     $spname4 = "todaybankcollection";
     $c6 = Combo::callcombo($spname4);
     $spname5 = "todaycashcollection";
     $c7 = Combo::callcombo($spname5);
     $spname6 = "todaycontracollection";
     $c8 = Combo::callcombo($spname6);
     $spbkash = "todaybkashcollection";
     $bkash = Combo::callcombo($spbkash);
     $spsap = "todaysapcollection";
     $sap = Combo::callcombo($spsap);
     $spkcs = "todaykcscollection";
     $kcs = Combo::callcombo($spkcs);
     $spmbank = "todaymbankcollection";
     $mbank = Combo::callcombo($spmbank);
     // print_r($c4);
     $sales_info = Sale::orderBy('created_at', 'desc')->take(5)->get();
     $purchase_info = Purchase::orderBy('created_at', 'desc')->take(5)->get();
     $bankaccount_info = Bankaccount::orderBy('created_at', 'desc')->take(5)->get();
     return view('home', compact('c', 'c1', 'c2', 'c3', 'sales_info', 'purchase_info', 'bankaccount_info', 'c4', 'c5', 'c6', 'c7', 'c8', 'bkash', 'sap', 'kcs', 'mbank'));
 }
 public function delete(Purchase $purchaseModel, History $historyModel, $purchase_id, $product_id)
 {
     $purchaseModel->deletePurchase($purchase_id, $product_id);
     $historyModel->saveHistory('del_purchase', $product_id);
     Session::flash('message', GetMessages("SUCCESS_DELETE_PURCHASE"));
     return redirect($_SERVER['HTTP_REFERER']);
 }
Example #9
0
 public function cancel_status(Request $request)
 {
     if ($request->ajax()) {
         $sales_id = $request->input('sales_id');
         $sales = Purchase::find($sales_id);
         if (!empty($sales)) {
             $sales->cstatus = 1;
             $sales->save();
         } else {
             return response()->json(0);
         }
         return response()->json(1);
     }
 }
Example #10
0
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function show(Label $labelModel, History $historyModel, Purchase $purchaseModel, Provider $providerController, Brand $brandModel, Category $categoryModel, Product $productModel, $id)
 {
     $product = $productModel->getProduct($id);
     if (!$product) {
         abort(404);
     }
     $purchase = $purchaseModel->getPurchase($id);
     $historyProduct = $historyModel->getProductHistory($id);
     $historyPurchase = $historyModel->getPurchaseHistory($id);
     $historySite = $historyModel->getSiteHistory($id);
     $labels = $labelModel->getLabelsByProductsId([$id]);
     $arLabels = [];
     foreach ($labels as $label) {
         $arLabels[] = $label->label;
     }
     $strLabels = implode(',', $arLabels);
     if (!empty($product->childs)) {
         $product->childs = unserialize($product->childs);
     }
     $categories_list = $categoryModel->getFullCategoriesList();
     $brands_list = $brandModel->getFullBrandsList();
     $provider_list = $providerController->getProvedrsList();
     return view('products.show')->with('title', $product->category_name . ' ' . $product->name)->with('product', $product)->with('purchase', $purchase)->with('categories_list', $categories_list)->with('brands_list', $brands_list)->with('provider_list', $provider_list)->with('history_product', $historyProduct)->with('history_purchase', $historyPurchase)->with('history_site', $historySite)->with('labels', $strLabels);
 }
Example #11
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  Request $request
  * @return Response
  */
 public function store(Request $request, History $historyModel, Cloud $cloudModel, Product $productModel, Purchase $purchaseModel)
 {
     if (isset($_POST['delete_all_flags'])) {
         if (!right('Import')) {
             abort(404);
         }
         $productModel->deleteAllFlags();
         Session::flash('message', GetMessages("SUCCESS_DELETE_FLAGS"));
         return redirect()->route('cloud.index');
     }
     if (isset($_POST['delete_all_export_list'])) {
         if (!right('Import')) {
             abort(404);
         }
         $productModel->deleteAllExport();
         Session::flash('message', GetMessages("SUCCESS_DELETE_FLAGS"));
         return redirect()->route('cloud.index');
     }
     if (isset($_POST['ajax'])) {
         if (!right('Import')) {
             abort(404);
         }
         Session::forget('idsNewProducts');
     }
     if (isset($_POST['export_site'])) {
         if (!right('Import')) {
             abort(404);
         }
         //pr($_POST);
         if (isset($_POST['field'])) {
             $products = $productModel->getProductFromExportToSite();
             if (count($products) > 0) {
                 $res = array();
                 $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'ВП ID');
                 $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Производитель');
                 $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Наменование');
                 if (isset($_POST['field']['GK'])) {
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'ID ГК');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Цена ГК');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Валюта ГК');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Активность ГК');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Яндекс ГК');
                 }
                 if (isset($_POST['field']['TV'])) {
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'ID ТВ');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Цена ТВ');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Валюта ТВ');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Активность ТВ');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Яндекс ТВ');
                 }
                 if (isset($_POST['field']['MK'])) {
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'ID МК');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Цена МК');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Валюта МК');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Активность МК');
                     $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Яндекс МК');
                 }
                 $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Наличие');
                 $i = 1;
                 foreach ($products as $product) {
                     $res[$i][] = $product->id;
                     $res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $product->brand);
                     $res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $product->name);
                     if (isset($_POST['field']['GK'])) {
                         if (strpos($product->GK_price, '.')) {
                             $product->GK_price = str_replace('.', ',', $product->GK_price);
                             //заменяем точку на запятую, ибо эксель ебанутый((
                         }
                         if ($product->GK_currency == 'RUB') {
                             $product->GK_price = intval($product->GK_price);
                             //округляем, если валюта RUB
                         }
                         $res[$i][] = $product->GK_id;
                         $res[$i][] = $product->GK_price;
                         $res[$i][] = $product->GK_currency;
                         $res[$i][] = $product->GK_enabled;
                         $res[$i][] = $product->GK_yandex_enabled;
                     }
                     if (isset($_POST['field']['TV'])) {
                         if (strpos($product->TV_price, '.')) {
                             $product->TV_price = str_replace('.', ',', $product->TV_price);
                             //заменяем точку на запятую, ибо эксель ебанутый((
                         }
                         if ($product->TV_currency == 'RUB') {
                             $product->TV_price = intval($product->TV_price);
                             //округляем, если валюта RUB
                         }
                         $res[$i][] = $product->TV_id;
                         $res[$i][] = $product->TV_price;
                         $res[$i][] = $product->TV_currency;
                         $res[$i][] = $product->TV_enabled;
                         $res[$i][] = $product->TV_yandex_enabled;
                     }
                     if (isset($_POST['field']['MK'])) {
                         if (strpos($product->MK_price, '.')) {
                             $product->MK_price = str_replace('.', ',', $product->MK_price);
                             //заменяем точку на запятую, ибо эксель ебанутый((
                         }
                         if ($product->MK_currency == 'RUB') {
                             $product->MK_price = intval($product->MK_price);
                             //округляем, если валюта RUB
                         }
                         $res[$i][] = $product->MK_id;
                         $res[$i][] = $product->MK_price;
                         $res[$i][] = $product->MK_currency;
                         $res[$i][] = $product->MK_enabled;
                         $res[$i][] = $product->MK_yandex_enabled;
                     }
                     $res[$i][] = $product->in_stock;
                     $i++;
                 }
                 $this->saveToCSV($res);
                 Session::flash('message', GetMessages("SUCCESS_EXPORT"));
                 return redirect()->route('cloud.index');
             } else {
                 return redirect()->route('cloud.index');
             }
         } else {
             return redirect()->route('cloud.index');
         }
     }
     if (isset($_POST['export_prod'])) {
         if (!right('Import')) {
             abort(404);
         }
         //pr($_POST);
         $fields = array();
         $fields[] = 'products.id';
         !isset($_POST['field']['prod']['status']) ?: ($fields[] = 'products.status');
         !isset($_POST['field']['prod']['name']) ?: ($fields[] = 'products.name');
         !isset($_POST['field']['prod']['category']) ?: ($fields[] = 'products.category_id');
         !isset($_POST['field']['prod']['category']) ?: ($fields[] = 'PC.name as category_name');
         !isset($_POST['field']['prod']['brand']) ?: ($fields[] = 'products.brand_id');
         !isset($_POST['field']['prod']['brand']) ?: ($fields[] = 'PB.name as brand_name');
         !isset($_POST['field']['prod']['article']) ?: ($fields[] = 'products.article');
         !isset($_POST['field']['prod']['ean']) ?: ($fields[] = 'products.ean');
         !isset($_POST['field']['prod']['mrc']) ?: ($fields[] = 'products.mrc');
         !isset($_POST['field']['prod']['mrc']) ?: ($fields[] = 'products.mrc_currency');
         !isset($_POST['field']['prod']['price']) ?: ($fields[] = 'products.price');
         !isset($_POST['field']['prod']['price']) ?: ($fields[] = 'products.price_currency');
         !isset($_POST['field']['prod']['target_margin']) ?: ($fields[] = 'products.target_margin');
         !isset($_POST['field']['prod']['in_stock']) ?: ($fields[] = 'products.in_stock');
         !isset($_POST['field']['site']['id']) ?: ($fields[] = 'GK.site_id as GK_id');
         !isset($_POST['field']['site']['enabled']) ?: ($fields[] = 'GK.enabled as GK_enabled');
         !isset($_POST['field']['site']['yandex_enabled']) ?: ($fields[] = 'GK.yandex_enabled as GK_yandex_enabled');
         !isset($_POST['field']['site']['currency']) ?: ($fields[] = 'GK.currency as GK_currency');
         !isset($_POST['field']['site']['price']) ?: ($fields[] = 'GK.price as GK_price');
         !isset($_POST['field']['site']['id']) ?: ($fields[] = 'TV.site_id as TV_id');
         !isset($_POST['field']['site']['enabled']) ?: ($fields[] = 'TV.enabled as TV_enabled');
         !isset($_POST['field']['site']['yandex_enabled']) ?: ($fields[] = 'TV.yandex_enabled as TV_yandex_enabled');
         !isset($_POST['field']['site']['currency']) ?: ($fields[] = 'TV.currency as TV_currency');
         !isset($_POST['field']['site']['price']) ?: ($fields[] = 'TV.price as TV_price');
         !isset($_POST['field']['site']['id']) ?: ($fields[] = 'MK.site_id as MK_id');
         !isset($_POST['field']['site']['enabled']) ?: ($fields[] = 'MK.enabled as MK_enabled');
         !isset($_POST['field']['site']['yandex_enabled']) ?: ($fields[] = 'MK.yandex_enabled as MK_yandex_enabled');
         !isset($_POST['field']['site']['currency']) ?: ($fields[] = 'MK.currency as MK_currency');
         !isset($_POST['field']['site']['price']) ?: ($fields[] = 'MK.price as MK_price');
         $products = $productModel->getProductFromExport($fields);
         if (count($products) > 0) {
             $res = array();
             $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP01 Id товара');
             !isset($_POST['field']['prod']['status']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP02 Статус'));
             !isset($_POST['field']['prod']['name']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP03 Наименование'));
             !isset($_POST['field']['prod']['category']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Категория'));
             !isset($_POST['field']['prod']['category']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP04 ID категории'));
             !isset($_POST['field']['prod']['brand']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Производитель'));
             !isset($_POST['field']['prod']['brand']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP05 ID производителя'));
             !isset($_POST['field']['prod']['article']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP06 Артикул'));
             !isset($_POST['field']['prod']['ean']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP07 Штрих-код'));
             !isset($_POST['field']['prod']['mrc']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP08 МРЦ'));
             !isset($_POST['field']['prod']['mrc']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP09 МРЦ валюта'));
             !isset($_POST['field']['prod']['price']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP10 Прайс'));
             !isset($_POST['field']['prod']['price']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP11 Прайс валюта'));
             !isset($_POST['field']['prod']['target_margin']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP12 Маржинальность'));
             !isset($_POST['field']['prod']['in_stock']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'VP13 Наличие'));
             !isset($_POST['field']['site']['id']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'GK01 ID на ГК'));
             !isset($_POST['field']['site']['enabled']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'GK02 Статус ГК'));
             !isset($_POST['field']['site']['yandex_enabled']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'GK03 Маркет ГК'));
             !isset($_POST['field']['site']['currency']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'GK04 Валюта ГК'));
             !isset($_POST['field']['site']['price']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'GK05 Цена ГК'));
             !isset($_POST['field']['site']['id']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'TV01 ID на ТВ'));
             !isset($_POST['field']['site']['enabled']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'TV02 Статус ТВ'));
             !isset($_POST['field']['site']['yandex_enabled']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'TV03 Маркет ТВ'));
             !isset($_POST['field']['site']['currency']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'TV04 Валюта ТВ'));
             !isset($_POST['field']['site']['price']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'TV05 Цена ТВ'));
             !isset($_POST['field']['site']['id']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'MK01 ID на МК'));
             !isset($_POST['field']['site']['enabled']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'MK02 Статус МК'));
             !isset($_POST['field']['site']['yandex_enabled']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'MK03 Маркет МК'));
             !isset($_POST['field']['site']['currency']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'MK04 Валюта МК'));
             !isset($_POST['field']['site']['price']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'MK05 Цена МК'));
             $i = 1;
             foreach ($products as $product) {
                 $res[$i][] = $product->id;
                 !isset($_POST['field']['prod']['status']) ?: ($res[$i][] = $product->status);
                 !isset($_POST['field']['prod']['name']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $product->name));
                 !isset($_POST['field']['prod']['category']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $product->category_name));
                 !isset($_POST['field']['prod']['category']) ?: ($res[$i][] = $product->category_id);
                 !isset($_POST['field']['prod']['brand']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $product->brand_name));
                 !isset($_POST['field']['prod']['brand']) ?: ($res[$i][] = $product->brand_id);
                 !isset($_POST['field']['prod']['article']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $product->article));
                 !isset($_POST['field']['prod']['ean']) ?: ($res[$i][] = $product->ean);
                 if (isset($_POST['field']['prod']['mrc'])) {
                     if (strpos($product->mrc, '.')) {
                         $product->mrc = str_replace('.', ',', $product->mrc);
                         //заменяем точку на запятую, ибо эксель ебанутый((
                     }
                     $res[$i][] = $product->mrc;
                 }
                 !isset($_POST['field']['prod']['mrc']) ?: ($res[$i][] = $product->mrc_currency);
                 if (isset($_POST['field']['prod']['price'])) {
                     if (strpos($product->price, '.')) {
                         $product->price = str_replace('.', ',', $product->price);
                         //заменяем точку на запятую, ибо эксель ебанутый((
                     }
                     $res[$i][] = $product->price;
                 }
                 !isset($_POST['field']['prod']['price']) ?: ($res[$i][] = $product->price_currency);
                 !isset($_POST['field']['prod']['target_margin']) ?: ($res[$i][] = $product->target_margin);
                 !isset($_POST['field']['prod']['in_stock']) ?: ($res[$i][] = $product->in_stock);
                 !isset($_POST['field']['site']['id']) ?: ($res[$i][] = $product->GK_id);
                 !isset($_POST['field']['site']['enabled']) ?: ($res[$i][] = $product->GK_enabled);
                 !isset($_POST['field']['site']['yandex_enabled']) ?: ($res[$i][] = $product->GK_yandex_enabled);
                 !isset($_POST['field']['site']['currency']) ?: ($res[$i][] = $product->GK_currency);
                 if (isset($_POST['field']['site']['price'])) {
                     if (strpos($product->GK_price, '.')) {
                         $product->GK_price = str_replace('.', ',', $product->GK_price);
                         //заменяем точку на запятую, ибо эксель ебанутый((
                     }
                     $res[$i][] = $product->GK_price;
                 }
                 !isset($_POST['field']['site']['id']) ?: ($res[$i][] = $product->TV_id);
                 !isset($_POST['field']['site']['enabled']) ?: ($res[$i][] = $product->TV_enabled);
                 !isset($_POST['field']['site']['yandex_enabled']) ?: ($res[$i][] = $product->TV_yandex_enabled);
                 !isset($_POST['field']['site']['currency']) ?: ($res[$i][] = $product->TV_currency);
                 if (isset($_POST['field']['site']['price'])) {
                     if (strpos($product->TV_price, '.')) {
                         $product->TV_price = str_replace('.', ',', $product->TV_price);
                         //заменяем точку на запятую, ибо эксель ебанутый((
                     }
                     $res[$i][] = $product->TV_price;
                 }
                 !isset($_POST['field']['site']['id']) ?: ($res[$i][] = $product->MK_id);
                 !isset($_POST['field']['site']['enabled']) ?: ($res[$i][] = $product->MK_enabled);
                 !isset($_POST['field']['site']['yandex_enabled']) ?: ($res[$i][] = $product->MK_yandex_enabled);
                 !isset($_POST['field']['site']['currency']) ?: ($res[$i][] = $product->MK_currency);
                 if (isset($_POST['field']['site']['price'])) {
                     if (strpos($product->MK_price, '.')) {
                         $product->MK_price = str_replace('.', ',', $product->MK_price);
                         //заменяем точку на запятую, ибо эксель ебанутый((
                     }
                     $res[$i][] = $product->MK_price;
                 }
                 $i++;
             }
             $this->saveToCSV($res);
             Session::flash('message', GetMessages("SUCCESS_EXPORT"));
             return redirect()->route('cloud.index');
         } else {
             return redirect()->route('cloud.index');
         }
     }
     if (isset($_POST['export_purch'])) {
         if (!right('Import')) {
             abort(404);
         }
         $fields = array();
         $fields[] = 'purchase.id as purchase_id';
         $fields[] = 'P.id as product_id';
         !isset($_POST['field']['purch']['name']) ?: ($fields[] = 'P.name as product_name');
         !isset($_POST['field']['purch']['article']) ?: ($fields[] = 'P.article as article');
         !isset($_POST['field']['purch']['price']) ?: ($fields[] = 'P.price as price');
         !isset($_POST['field']['purch']['price']) ?: ($fields[] = 'P.price_currency as price_currency');
         !isset($_POST['field']['purch']['ean']) ?: ($fields[] = 'P.ean as ean');
         !isset($_POST['field']['purch']['category']) ?: ($fields[] = 'PC.name as category');
         !isset($_POST['field']['purch']['brand']) ?: ($fields[] = 'PB.name as brand');
         !isset($_POST['field']['purch']['provider']) ?: ($fields[] = 'PROV.name as provider');
         !isset($_POST['field']['purch']['provider']) ?: ($fields[] = 'PROV.id as provider_id');
         !isset($_POST['field']['purch']['base_price']) ?: ($fields[] = 'purchase.base_price');
         !isset($_POST['field']['purch']['currency']) ?: ($fields[] = 'purchase.currency');
         !isset($_POST['field']['purch']['raise']) ?: ($fields[] = 'purchase.raise');
         !isset($_POST['field']['purch']['discount_price']) ?: ($fields[] = 'purchase.discount_price');
         !isset($_POST['field']['purch']['discount_bulk']) ?: ($fields[] = 'purchase.discount_bulk');
         $purchases = $purchaseModel->getPurchaseFromExport($fields);
         if (count($purchases) > 0) {
             $res = array();
             $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'PU01 Id закупки');
             $res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'PU02 Id товара');
             !isset($_POST['field']['purch']['name']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Наименование'));
             !isset($_POST['field']['purch']['article']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Артикул'));
             !isset($_POST['field']['purch']['price']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Прайс'));
             !isset($_POST['field']['purch']['price']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Валюта прайса'));
             !isset($_POST['field']['purch']['ean']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Штрих-код'));
             !isset($_POST['field']['purch']['category']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Категория'));
             !isset($_POST['field']['purch']['brand']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Производитель'));
             !isset($_POST['field']['purch']['provider']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'Поставщик'));
             !isset($_POST['field']['purch']['provider']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'PU03 ID поставщика'));
             !isset($_POST['field']['purch']['base_price']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'PU04 Базовая цена'));
             !isset($_POST['field']['purch']['currency']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'PU05 Валюта'));
             !isset($_POST['field']['purch']['raise']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'PU06 Поправка к ЦБ'));
             !isset($_POST['field']['purch']['discount_price']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'PU07 Скидка'));
             !isset($_POST['field']['purch']['discount_bulk']) ?: ($res[0][] = iconv('UTF-8', 'cp1251//TRANSLIT', 'PU08 Доп.скидка'));
             $i = 1;
             foreach ($purchases as $purchase) {
                 $res[$i][] = $purchase->purchase_id;
                 $res[$i][] = $purchase->product_id;
                 !isset($_POST['field']['purch']['name']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $purchase->product_name));
                 !isset($_POST['field']['purch']['article']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $purchase->article));
                 !isset($_POST['field']['purch']['price']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', str_replace('.', ',', $purchase->price)));
                 !isset($_POST['field']['purch']['price']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $purchase->price_currency));
                 !isset($_POST['field']['purch']['ean']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $purchase->ean));
                 !isset($_POST['field']['purch']['category']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $purchase->category));
                 !isset($_POST['field']['purch']['brand']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $purchase->brand));
                 !isset($_POST['field']['purch']['provider']) ?: ($res[$i][] = iconv('UTF-8', 'cp1251//TRANSLIT', $purchase->provider));
                 !isset($_POST['field']['purch']['provider']) ?: ($res[$i][] = $purchase->provider_id);
                 if (isset($_POST['field']['purch']['base_price'])) {
                     if (strpos($purchase->base_price, '.')) {
                         $purchase->base_price = str_replace('.', ',', $purchase->base_price);
                         //заменяем точку на запятую, ибо эксель ебанутый((
                     }
                     $res[$i][] = $purchase->base_price;
                 }
                 !isset($_POST['field']['purch']['currency']) ?: ($res[$i][] = $purchase->currency);
                 !isset($_POST['field']['purch']['raise']) ?: ($res[$i][] = $purchase->raise);
                 if (isset($_POST['field']['purch']['discount_price'])) {
                     if (strpos($purchase->discount_price, '.')) {
                         $purchase->discount_price = str_replace('.', ',', $purchase->discount_price);
                         //заменяем точку на запятую, ибо эксель ебанутый((
                     }
                     $res[$i][] = $purchase->discount_price;
                 }
                 if (isset($_POST['field']['purch']['discount_bulk'])) {
                     if (strpos($purchase->discount_bulk, '.')) {
                         $purchase->discount_bulk = str_replace('.', ',', $purchase->discount_bulk);
                         //заменяем точку на запятую, ибо эксель ебанутый((
                     }
                     $res[$i][] = $purchase->discount_bulk;
                 }
                 $i++;
             }
             $this->saveToCSV($res);
             Session::flash('message', GetMessages("SUCCESS_EXPORT"));
             return redirect()->route('cloud.index');
         } else {
             return redirect()->route('cloud.index');
         }
     }
     if (isset($_POST['import_csv'])) {
         if (!right('Import')) {
             abort(404);
         }
         if (isset($request['file_csv'])) {
             $file = Input::file('file_csv');
             $extension = $file->getClientOriginalExtension();
             //получаем расширение
             if ($extension == 'csv') {
                 $filename = $file->getClientOriginalName();
                 //оригинальное название файла
                 $real_filename = date("Y_m_d_H_i_s") . '_' . RuslugFacade::make(mb_strtolower($file->getClientOriginalName()));
                 //преобразованное название файла
                 $file->move(base_path() . '/public/storage/import/', $real_filename);
                 //перемещаем файл
                 $header = NULL;
                 $data = array();
                 if (($handle = fopen(base_path() . cloud_path() . '/import/' . $real_filename, "r")) !== FALSE) {
                     while (($row = fgetcsv($handle, 1000, ';')) !== FALSE) {
                         if (!$header) {
                             $header = $row;
                         } else {
                             $data[] = array_combine($header, $row);
                         }
                     }
                     fclose($handle);
                     $res = [];
                     //pr($data);
                     $i = 0;
                     foreach ($data as $row) {
                         if (array_key_exists(to1251('VP01 Id товара'), $row)) {
                             //это товар
                             if (!empty($row[to1251('VP01 Id товара')])) {
                                 //товар уже существует, будем обновлять
                                 !array_key_exists(to1251('VP02 Статус'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.status'] = import_field($row[to1251('VP02 Статус')], 'bool', 1));
                                 !array_key_exists(to1251('VP03 Наименование'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.name'] = import_field(toUTF($row[to1251('VP03 Наименование')]), 'string', ''));
                                 !array_key_exists(to1251('VP04 ID категории'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.category_id'] = import_field($row[to1251('VP04 ID категории')], 'int', 0));
                                 !array_key_exists(to1251('VP05 ID производителя'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.brand_id'] = import_field($row[to1251('VP05 ID производителя')], 'int', 0));
                                 !array_key_exists(to1251('VP06 Артикул'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.article'] = import_field(toUTF($row[to1251('VP06 Артикул')]), 'string', ''));
                                 !array_key_exists(to1251('VP07 Штрих-код'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.ean'] = import_field($row[to1251('VP07 Штрих-код')], 'string', ''));
                                 !array_key_exists(to1251('VP08 МРЦ'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.mrc'] = import_field($row[to1251('VP08 МРЦ')], 'float', 0));
                                 !array_key_exists(to1251('VP09 МРЦ валюта'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.mrc_currency'] = import_field($row[to1251('VP09 МРЦ валюта')], 'string', 'RUB'));
                                 !array_key_exists(to1251('VP10 Прайс'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.price'] = import_field($row[to1251('VP10 Прайс')], 'float', 0));
                                 !array_key_exists(to1251('VP11 Прайс валюта'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.price_currency'] = import_field($row[to1251('VP11 Прайс валюта')], 'string', 'RUB'));
                                 !array_key_exists(to1251('VP12 Маржинальность'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.target_margin'] = import_field($row[to1251('VP12 Маржинальность')], 'float', 0));
                                 !array_key_exists(to1251('VP13 Наличие'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.in_stock'] = import_field($row[to1251('VP13 Наличие')], 'bool', 0));
                                 if (isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.status']) or isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.name']) or isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.category_id']) or isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.brand_id']) or isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.article']) or isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.ean']) or isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.min_retail_price']) or isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.rec_retail_price']) or isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.target_margin']) or isset($res['update_prod'][$row[to1251('VP01 Id товара')]]['products.in_stock'])) {
                                     $res['update_prod'][$row[to1251('VP01 Id товара')]]['products.id'] = $row[to1251('VP01 Id товара')];
                                     $res['update_prod'][$row[to1251('VP01 Id товара')]]['products.updated_at'] = date('Y-m-d H:i:s');
                                     $res['update_prod'][$row[to1251('VP01 Id товара')]]['products.user_id'] = Auth::User()->id;
                                 }
                                 if (array_key_exists(to1251('GK01 ID на ГК'), $row)) {
                                     //есть поле Гаранта
                                     if (stristr($row[to1251('GK01 ID на ГК')], 'add')) {
                                         $row[to1251('GK01 ID на ГК')] = str_replace('add', '', $row[to1251('GK01 ID на ГК')]);
                                         //добавляем новый
                                         $productModel->deleteWithSite('GK', $row[to1251('VP01 Id товара')]);
                                         //сперва удаяем все, что связано с этим товаром (если есть)
                                         $res['add_to_GK'][$i]['product_id'] = $row[to1251('VP01 Id товара')];
                                         !array_key_exists(to1251('GK01 ID на ГК'), $row) ? $res['add_to_GK'][$i]['site_id'] = 1 : ($res['add_to_GK'][$i]['site_id'] = import_field($row[to1251('GK01 ID на ГК')], 'int', 1));
                                         !array_key_exists(to1251('GK02 Статус ГК'), $row) ? $res['add_to_GK'][$i]['enabled'] = 1 : ($res['add_to_GK'][$i]['enabled'] = import_field($row[to1251('GK02 Статус ГК')], 'bool', 1));
                                         !array_key_exists(to1251('GK03 Маркет ГК'), $row) ? $res['add_to_GK'][$i]['yandex_enabled'] = 0 : ($res['add_to_GK'][$i]['yandex_enabled'] = import_field($row[to1251('GK03 Маркет ГК')], 'bool', 0));
                                         !array_key_exists(to1251('GK04 Валюта ГК'), $row) ? $res['add_to_GK'][$i]['currency'] = 'RUB' : ($res['add_to_GK'][$i]['currency'] = import_field($row[to1251('GK04 Валюта ГК')], 'string', 'RUB'));
                                         !array_key_exists(to1251('GK05 Цена ГК'), $row) ? $res['add_to_GK'][$i]['price'] = 0 : ($res['add_to_GK'][$i]['price'] = import_field($row[to1251('GK05 Цена ГК')], 'float', 0));
                                         $res['add_to_GK'][$i]['created_at'] = date('Y-m-d H:i:s');
                                         $res['add_to_GK'][$i]['updated_at'] = date('Y-m-d H:i:s');
                                         $res['add_to_GK'][$i]['user_id'] = Auth::User()->id;
                                     } else {
                                         if (count($productModel->checkProductOnSiteId('GK', $row[to1251('VP01 Id товара')])) > 0) {
                                             //убеждаемся, что на этот товар уже привязан
                                             //если товар есть на сайте, будем обновлять
                                             !array_key_exists(to1251('GK01 ID на ГК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['GK.site_id'] = import_field($row[to1251('GK01 ID на ГК')], 'int', 0));
                                             !array_key_exists(to1251('GK02 Статус ГК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['GK.enabled'] = import_field($row[to1251('GK02 Статус ГК')], 'bool', 1));
                                             !array_key_exists(to1251('GK03 Маркет ГК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['GK.yandex_enabled'] = import_field($row[to1251('GK03 Маркет ГК')], 'bool', 0));
                                             !array_key_exists(to1251('GK04 Валюта ГК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['GK.currency'] = import_field($row[to1251('GK04 Валюта ГК')], 'string', 'RUB'));
                                             !array_key_exists(to1251('GK05 Цена ГК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['GK.price'] = import_field($row[to1251('GK05 Цена ГК')], 'float', 0));
                                             $res['update_prod'][$row[to1251('VP01 Id товара')]]['GK.updated_at'] = date('Y-m-d H:i:s');
                                             $res['update_prod'][$row[to1251('VP01 Id товара')]]['GK.user_id'] = Auth::User()->id;
                                         }
                                     }
                                 }
                                 if (array_key_exists(to1251('TV01 ID на ТВ'), $row)) {
                                     //есть поле Таваго
                                     if (stristr($row[to1251('TV01 ID на ТВ')], 'add')) {
                                         $row[to1251('TV01 ID на ТВ')] = str_replace('add', '', $row[to1251('TV01 ID на ТВ')]);
                                         //добавляем новый
                                         $productModel->deleteWithSite('TV', $row[to1251('VP01 Id товара')]);
                                         //сперва удаяем все, что связано с этим товаром (если есть)
                                         $res['add_to_TV'][$i]['product_id'] = $row[to1251('VP01 Id товара')];
                                         !array_key_exists(to1251('TV01 ID на ТВ'), $row) ? $res['add_to_TV'][$i]['site_id'] = 1 : ($res['add_to_TV'][$i]['site_id'] = import_field($row[to1251('TV01 ID на ТВ')], 'int', 1));
                                         !array_key_exists(to1251('TV02 Статус ТВ'), $row) ? $res['add_to_TV'][$i]['enabled'] = 1 : ($res['add_to_TV'][$i]['enabled'] = import_field($row[to1251('TV02 Статус ТВ')], 'bool', 1));
                                         !array_key_exists(to1251('TV03 Маркет ТВ'), $row) ? $res['add_to_TV'][$i]['yandex_enabled'] = 0 : ($res['add_to_TV'][$i]['yandex_enabled'] = import_field($row[to1251('TV03 Маркет ТВ')], 'bool', 0));
                                         !array_key_exists(to1251('TV04 Валюта ТВ'), $row) ? $res['add_to_TV'][$i]['currency'] = 'RUB' : ($res['add_to_TV'][$i]['currency'] = import_field($row[to1251('TV04 Валюта ТВ')], 'string', 'RUB'));
                                         !array_key_exists(to1251('TV05 Цена ТВ'), $row) ? $res['add_to_TV'][$i]['price'] = 0 : ($res['add_to_TV'][$i]['price'] = import_field($row[to1251('TV05 Цена ТВ')], 'float', 0));
                                         $res['add_to_TV'][$i]['created_at'] = date('Y-m-d H:i:s');
                                         $res['add_to_TV'][$i]['updated_at'] = date('Y-m-d H:i:s');
                                         $res['add_to_TV'][$i]['user_id'] = Auth::User()->id;
                                     } else {
                                         if (count($productModel->checkProductOnSiteId('TV', $row[to1251('VP01 Id товара')])) > 0) {
                                             //убеждаемся, что на этот товар уже привязан
                                             //если товар есть на сайте, будем обновлять
                                             !array_key_exists(to1251('TV01 ID на ТВ'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['TV.site_id'] = import_field($row[to1251('TV01 ID на ТВ')], 'int', 0));
                                             !array_key_exists(to1251('TV02 Статус ТВ'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['TV.enabled'] = import_field($row[to1251('TV02 Статус ТВ')], 'bool', 1));
                                             !array_key_exists(to1251('TV03 Маркет ТВ'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['TV.yandex_enabled'] = import_field($row[to1251('TV03 Маркет ТВ')], 'bool', 0));
                                             !array_key_exists(to1251('TV04 Валюта ТВ'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['TV.currency'] = import_field($row[to1251('TV04 Валюта ТВ')], 'string', 'RUB'));
                                             !array_key_exists(to1251('TV05 Цена ТВ'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['TV.price'] = import_field($row[to1251('TV05 Цена ТВ')], 'float', 0));
                                             $res['update_prod'][$row[to1251('VP01 Id товара')]]['TV.updated_at'] = date('Y-m-d H:i:s');
                                             $res['update_prod'][$row[to1251('VP01 Id товара')]]['TV.user_id'] = Auth::User()->id;
                                         }
                                     }
                                 }
                                 if (array_key_exists(to1251('MK01 ID на МК'), $row)) {
                                     //есть поле МаксКлимат
                                     if (stristr($row[to1251('MK01 ID на МК')], 'add')) {
                                         $row[to1251('MK01 ID на МК')] = str_replace('add', '', $row[to1251('MK01 ID на МК')]);
                                         //добавляем новый
                                         $productModel->deleteWithSite('MK', $row[to1251('VP01 Id товара')]);
                                         //сперва удаяем все, что связано с этим товаром (если есть)
                                         $res['add_to_MK'][$i]['product_id'] = $row[to1251('VP01 Id товара')];
                                         !array_key_exists(to1251('MK01 ID на МК'), $row) ? $res['add_to_MK'][$i]['site_id'] = 1 : ($res['add_to_MK'][$i]['site_id'] = import_field($row[to1251('MK01 ID на МК')], 'int', 1));
                                         !array_key_exists(to1251('MK02 Статус МК'), $row) ? $res['add_to_MK'][$i]['enabled'] = 1 : ($res['add_to_MK'][$i]['enabled'] = import_field($row[to1251('MK02 Статус МК')], 'bool', 1));
                                         !array_key_exists(to1251('MK03 Маркет МК'), $row) ? $res['add_to_MK'][$i]['yandex_enabled'] = 0 : ($res['add_to_MK'][$i]['yandex_enabled'] = import_field($row[to1251('MK03 Маркет МК')], 'bool', 0));
                                         !array_key_exists(to1251('MK04 Валюта МК'), $row) ? $res['add_to_MK'][$i]['currency'] = 'RUB' : ($res['add_to_MK'][$i]['currency'] = import_field($row[to1251('MK04 Валюта МК')], 'string', 'RUB'));
                                         !array_key_exists(to1251('MK05 Цена МК'), $row) ? $res['add_to_MK'][$i]['price'] = 0 : ($res['add_to_MK'][$i]['price'] = import_field($row[to1251('MK05 Цена МК')], 'float', 0));
                                         $res['add_to_MK'][$i]['created_at'] = date('Y-m-d H:i:s');
                                         $res['add_to_MK'][$i]['updated_at'] = date('Y-m-d H:i:s');
                                         $res['add_to_MK'][$i]['user_id'] = Auth::User()->id;
                                     } else {
                                         if (count($productModel->checkProductOnSiteId('MK', $row[to1251('VP01 Id товара')])) > 0) {
                                             //убеждаемся, что на этот товар уже привязан
                                             //если товар есть на сайте, будем обновлять
                                             !array_key_exists(to1251('MK01 ID на МК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['MK.site_id'] = import_field($row[to1251('MK01 ID на МК')], 'int', 0));
                                             !array_key_exists(to1251('MK02 Статус МК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['MK.enabled'] = import_field($row[to1251('MK02 Статус МК')], 'bool', 1));
                                             !array_key_exists(to1251('MK03 Маркет МК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['MK.yandex_enabled'] = import_field($row[to1251('MK03 Маркет МК')], 'bool', 0));
                                             !array_key_exists(to1251('MK04 Валюта МК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['MK.currency'] = import_field($row[to1251('MK04 Валюта МК')], 'string', 'RUB'));
                                             !array_key_exists(to1251('MK05 Цена МК'), $row) ?: ($res['update_prod'][$row[to1251('VP01 Id товара')]]['MK.price'] = import_field($row[to1251('MK05 Цена МК')], 'float', 0));
                                             $res['update_prod'][$row[to1251('VP01 Id товара')]]['MK.updated_at'] = date('Y-m-d H:i:s');
                                             $res['update_prod'][$row[to1251('VP01 Id товара')]]['MK.user_id'] = Auth::User()->id;
                                         }
                                     }
                                 }
                             } else {
                                 //такого товара нет, будем добавлять
                                 !array_key_exists(to1251('VP02 Статус'), $row) ? $res['add_prod'][$i]['products.status'] = 1 : ($res['add_prod'][$i]['products.status'] = import_field($row[to1251('VP02 Статус')], 'bool', 1));
                                 !array_key_exists(to1251('VP03 Наименование'), $row) ? $res['add_prod'][$i]['products.name'] = '' : ($res['add_prod'][$i]['products.name'] = import_field(toUTF($row[to1251('VP03 Наименование')]), 'string', ''));
                                 !array_key_exists(to1251('VP04 ID категории'), $row) ? $res['add_prod'][$i]['products.category_id'] = 1 : ($res['add_prod'][$i]['products.category_id'] = import_field($row[to1251('VP04 ID категории')], 'int', 1));
                                 !array_key_exists(to1251('VP05 ID производителя'), $row) ? $res['add_prod'][$i]['products.brand_id'] = 1 : ($res['add_prod'][$i]['products.brand_id'] = import_field($row[to1251('VP05 ID производителя')], 'int', 1));
                                 !array_key_exists(to1251('VP06 Артикул'), $row) ? $res['add_prod'][$i]['products.article'] = '' : ($res['add_prod'][$i]['products.article'] = import_field(toUTF($row[to1251('VP06 Артикул')]), 'string', ''));
                                 !array_key_exists(to1251('VP07 Штрих-код'), $row) ? $res['add_prod'][$i]['products.ean'] = '' : ($res['add_prod'][$i]['products.ean'] = import_field($row[to1251('VP07 Штрих-код')], 'string', ''));
                                 !array_key_exists(to1251('VP08 МРЦ'), $row) ? $res['add_prod'][$i]['products.mrc'] = 0 : ($res['add_prod'][$i]['products.mrc'] = import_field($row[to1251('VP08 МРЦ')], 'float', 0));
                                 !array_key_exists(to1251('VP09 МРЦ валюта'), $row) ? $res['add_prod'][$i]['products.mrc_currency'] = 'RUB' : ($res['add_prod'][$i]['products.mrc_currency'] = import_field($row[to1251('VP09 МРЦ валюта')], 'string', 'RUB'));
                                 !array_key_exists(to1251('VP10 Прайс'), $row) ? $res['add_prod'][$i]['products.price'] = 0 : ($res['add_prod'][$i]['products.price'] = import_field($row[to1251('VP10 Прайс')], 'float', 0));
                                 !array_key_exists(to1251('VP11 Прайс валюта'), $row) ? $res['add_prod'][$i]['products.price_currency'] = 'RUB' : ($res['add_prod'][$i]['products.price_currency'] = import_field($row[to1251('VP11 Прайс валюта')], 'string', 'RUB'));
                                 !array_key_exists(to1251('VP12 Маржинальность'), $row) ? $res['add_prod'][$i]['products.target_margin'] = 0 : ($res['add_prod'][$i]['products.target_margin'] = import_field($row[to1251('VP12 Маржинальность')], 'float', 0));
                                 !array_key_exists(to1251('VP13 Наличие'), $row) ? $res['add_prod'][$i]['products.in_stock'] = 0 : ($res['add_prod'][$i]['products.in_stock'] = import_field($row[to1251('VP13 Наличие')], 'bool', 0));
                                 $res['add_prod'][$i]['products.created_at'] = date('Y-m-d H:i:s');
                                 $res['add_prod'][$i]['products.updated_at'] = date('Y-m-d H:i:s');
                                 $res['add_prod'][$i]['products.user_id'] = Auth::User()->id;
                             }
                         } elseif (array_key_exists(to1251('PU01 Id закупки'), $row)) {
                             //это условия
                             if (!array_key_exists(to1251('PU02 Id товара'), $row) or empty($row[to1251('PU02 Id товара')])) {
                                 //нет обязательного поля с ID товара
                                 Session::flash('message', GetMessages("ERROR_NO_REQUIRED_FIELD"));
                                 return redirect()->route('cloud.index');
                             }
                             if (!empty($row[to1251('PU01 Id закупки')])) {
                                 //такое уcловие существует - будем обновлять
                                 !array_key_exists(to1251('PU03 ID поставщика'), $row) ?: ($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.vendor_id'] = import_field($row[to1251('PU03 ID поставщика')], 'int', 1));
                                 !array_key_exists(to1251('PU04 Базовая цена'), $row) ?: ($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.base_price'] = import_field($row[to1251('PU04 Базовая цена')], 'float', 0));
                                 !array_key_exists(to1251('PU05 Валюта'), $row) ?: ($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.currency'] = import_field($row[to1251('PU05 Валюта')], 'string', 'RUB'));
                                 !array_key_exists(to1251('PU06 Поправка к ЦБ'), $row) ?: ($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.raise'] = import_field($row[to1251('PU06 Поправка к ЦБ')], 'float', 0));
                                 !array_key_exists(to1251('PU07 Скидка'), $row) ?: ($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.discount_price'] = import_field($row[to1251('PU07 Скидка')], 'float', 0));
                                 !array_key_exists(to1251('PU08 Доп.скидка'), $row) ?: ($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.discount_bulk'] = import_field($row[to1251('PU08 Доп.скидка')], 'float', 0));
                                 if (isset($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.vendor_id']) or isset($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.base_price']) or isset($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.currency_id']) or isset($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.raise']) or isset($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.discount_price']) or isset($res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.discount_bulk'])) {
                                     $res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.id'] = $row[to1251('PU01 Id закупки')];
                                     $res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.product_id'] = $row[to1251('PU02 Id товара')];
                                     $res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.updated_at'] = date('Y-m-d H:i:s');
                                     $res['update_purch'][$row[to1251('PU01 Id закупки')]]['purchase.user_id'] = Auth::User()->id;
                                 }
                             } else {
                                 //такого условия нет - будем добавлять
                                 !array_key_exists(to1251('PU03 ID поставщика'), $row) ? $res['add_purch'][$i]['purchase.vendor_id'] = 1 : ($res['add_purch'][$i]['purchase.vendor_id'] = import_field($row[to1251('PU03 ID поставщика')], 'int', 1));
                                 !array_key_exists(to1251('PU04 Базовая цена'), $row) ? $res['add_purch'][$i]['purchase.base_price'] = 0 : ($res['add_purch'][$i]['purchase.base_price'] = import_field($row[to1251('PU04 Базовая цена')], 'float', 0));
                                 !array_key_exists(to1251('PU05 Валюта'), $row) ? $res['add_purch'][$i]['purchase.currency'] = 'RUB' : ($res['add_purch'][$i]['purchase.currency'] = import_field($row[to1251('PU05 Валюта')], 'string', 'RUB'));
                                 !array_key_exists(to1251('PU06 Поправка к ЦБ'), $row) ? $res['add_purch'][$i]['purchase.raise'] = 0 : ($res['add_purch'][$i]['purchase.raise'] = import_field($row[to1251('PU06 Поправка к ЦБ')], 'float', 0));
                                 !array_key_exists(to1251('PU07 Скидка'), $row) ? $res['add_purch'][$i]['purchase.discount_price'] = 0 : ($res['add_purch'][$i]['purchase.discount_price'] = import_field($row[to1251('PU07 Скидка')], 'float', 0));
                                 !array_key_exists(to1251('PU08 Доп.скидка'), $row) ? $res['add_purch'][$i]['purchase.discount_bulk'] = 0 : ($res['add_purch'][$i]['purchase.discount_bulk'] = import_field($row[to1251('PU08 Доп.скидка')], 'float', 0));
                                 $res['add_purch'][$i]['purchase.product_id'] = $row[to1251('PU02 Id товара')];
                                 $res['add_purch'][$i]['purchase.created_at'] = date('Y-m-d H:i:s');
                                 $res['add_purch'][$i]['purchase.updated_at'] = date('Y-m-d H:i:s');
                                 $res['add_purch'][$i]['purchase.user_id'] = Auth::User()->id;
                             }
                         } else {
                             Session::flash('message', GetMessages("ERROR_NO_REQUIRED_FIELD"));
                             return redirect()->route('cloud.index');
                         }
                         //pr($res);
                         $i++;
                     }
                     //pr($res);
                     $count = [];
                     if (isset($res['update_prod'])) {
                         $count['update_prod'] = count($res['update_prod']);
                     }
                     if (isset($res['add_prod'])) {
                         $count['add_prod'] = count($res['add_prod']);
                     }
                     if (isset($res['add_to_GK'])) {
                         $count['add_to_GK'] = count($res['add_to_GK']);
                     }
                     if (isset($res['add_to_TV'])) {
                         $count['add_to_TV'] = count($res['add_to_TV']);
                     }
                     if (isset($res['add_to_MK'])) {
                         $count['add_to_MK'] = count($res['add_to_MK']);
                     }
                     if (isset($res['update_purch'])) {
                         $count['update_purch'] = count($res['update_purch']);
                     }
                     if (isset($res['add_purch'])) {
                         $count['add_purch'] = count($res['add_purch']);
                     }
                     Session::put('count', $count);
                     Session::put('res', $res);
                     //pr($res);
                     $cloudModel->addFile('import', $filename, $real_filename);
                     return redirect()->route('cloud.index');
                 }
             } else {
                 Session::flash('message', GetMessages("ERROR_NO_CSV_FILE"));
                 return redirect()->route('cloud.index');
             }
         } else {
             Session::flash('message', GetMessages("ERROR_NO_CSV_FILE"));
             return redirect()->route('cloud.index');
         }
     }
     if (isset($_POST['end_import'])) {
         if (!right('Import')) {
             abort(404);
         }
         $count = Session::pull('count', null);
         $res = Session::pull('res', null);
         //pr($res);
         //pr($count);
         if (isset($res['update_prod']) and count($res['update_prod']) > 0) {
             $productModel->updatingListProducts($res['update_prod']);
         }
         if (isset($res['add_prod']) and count($res['add_prod']) > 0) {
             $idsNewProducts = $productModel->createProducts($res['add_prod']);
             Session::put('idsNewProducts', $idsNewProducts);
         }
         if (isset($res['add_to_GK']) and count($res['add_to_GK']) > 0) {
             $productModel->addsToSite($res['add_to_GK'], 'GK');
         }
         if (isset($res['add_to_TV']) and count($res['add_to_TV']) > 0) {
             $productModel->addsToSite($res['add_to_TV'], 'TV');
         }
         if (isset($res['add_to_MK']) and count($res['add_to_MK']) > 0) {
             $productModel->addsToSite($res['add_to_MK'], 'MK');
         }
         if (isset($res['update_purch']) and count($res['update_purch']) > 0) {
             $purchaseModel->updatePurchase($res['update_purch']);
         }
         if (isset($res['add_purch']) and count($res['add_purch']) > 0) {
             $purchaseModel->addPurchases($res['add_purch']);
         }
         $historyModel->saveHistory('import', $count);
         Session::flash('message', GetMessages("SUCCESS_IMPORT_COMPLETED"));
         return redirect()->route('cloud.index');
     }
     if (isset($_POST['send_to_site'])) {
         if (!right('Import')) {
             abort(404);
         }
         //pr($_POST);
         if (isset($_POST['sent_to_'])) {
             $externalModel = new External();
             if (isset($_POST['sent_to_']['GK'])) {
                 $externalModel->send('GK');
             }
             if (isset($_POST['sent_to_']['TV'])) {
                 $externalModel->send('TV');
             }
             if (isset($_POST['sent_to_']['GK'])) {
                 $externalModel->send('MK');
             }
         }
         if (isset($_POST['clear_list'])) {
             $productModel->deleteAllExport();
         }
         Session::flash('message', GetMessages("SUCCESS_EXTERNAL_EXPORT"));
         return redirect()->route('cloud.index');
     }
 }
Example #12
0
 /**
  * boot
  * observing model
  *
  */
 public static function boot()
 {
     parent::boot();
     Purchase::observe(new PurchaseObserver());
 }
 public function getCost(Purchase $purchase)
 {
     return $purchase->getCost() * (100 - $this->percent) / 100;
 }
 /**
  * @GET("/requests/finished", as="admin.requests.finished")
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  */
 public function finishedTransactions()
 {
     $requests = Purchase::where('status_admin', 1)->get();
     return view('admin.requests.finished', compact('requests'));
 }
 /**
  * Update the specified resource in storage.
  *
  * @param  Request  $request
  * @param  int  $id
  * @return Response
  */
 public function update(Request $request, $id, Category $categoryModel, History $historyModel, Label $labelModel)
 {
     if (isset($_POST['rename_category'])) {
         if (!right('EditCategory')) {
             abort(404);
         }
         if (strlen($request->input('name')) > 0) {
             $categoryModel->renameCategory($id, $request->input('name'));
             $historyModel->saveHistory('rename_category', $request->input('name'));
             Session::flash('message', GetMessages("SUCCESS_RENAME_CATEGORY"));
             return redirect($_SERVER['HTTP_REFERER']);
         } else {
             Session::flash('message', GetMessages("ERROR_EMPTY_NAME_CATEGORY"));
             return redirect($_SERVER['HTTP_REFERER']);
         }
     }
     if (isset($_POST['move_category'])) {
         if (!right('EditCategory')) {
             abort(404);
         }
         $categoryModel->moveCategory($id, $request->input('new_parent_id'));
         $historyModel->saveHistory('move_category', $id);
         Session::flash('message', GetMessages("SUCCESS_MOVE_CATEGORY"));
         return redirect($_SERVER['HTTP_REFERER']);
     }
     if (isset($_POST['create_category'])) {
         if (!right('EditCategory')) {
             abort(404);
         }
         if (strlen($request->input('name')) > 0) {
             $categoryModel->createCategory($id, $request->input('name'));
             $historyModel->saveHistory('create_category', $request->input('name'));
             Session::flash('message', GetMessages("SUCCESS_CREATE_NEW_CATEGORY"));
             return redirect()->route('category.show', ['id' => $id]);
         } else {
             Session::flash('message', GetMessages("ERROR_EMPTY_NAME_CATEGORY"));
             return redirect($_SERVER['HTTP_REFERER']);
         }
     }
     if (isset($_POST['status_category'])) {
         if (!right('EditCategory')) {
             abort(404);
         }
         $categoryModel->changeStatus($id, $request->input('status'));
         $historyModel->saveHistory('status_category', $id, $request->input('status'));
         Session::flash('message', GetMessages("SUCCESS_CHANGE_STATUS_CATEGORY"));
         return redirect($_SERVER['HTTP_REFERER']);
     }
     if (isset($_POST['set_sort_provider'])) {
         if (!right('EditPurchase')) {
             abort(404);
         }
         $purchaseModel = new Purchase();
         $ids = $categoryModel->getChild($id);
         foreach ($_POST['sort_provider'] as $key => $provider_id) {
             if ($provider_id != 0) {
                 $purchaseModel->setSortByCategoryId($ids, $provider_id, $key);
             }
         }
         Session::flash('message', GetMessages("SUCCESS_UPDATE"));
         return redirect($_SERVER['HTTP_REFERER']);
     }
     if (isset($_POST['labels'])) {
         if (!right('EditCategory')) {
             abort(404);
         }
         $products = $categoryModel->getProducts($id);
         foreach ($products as $product) {
             //$labelModel->joinLabels($product, explode(',', $_POST['name']));
         }
         Session::flash('message', GetMessages("SUCCESS_DATA_PRODUCTS_UPDATE"));
         return redirect($_SERVER['HTTP_REFERER']);
     }
 }
Example #16
0
 /**
  * Delete a purchase
  *
  * @return Response
  */
 public function delete($id = null)
 {
     //
     $purchase = \App\Models\Purchase::id($id)->with(['transactionlogs', 'supplier', 'transactiondetails', 'transactiondetails.varian', 'transactiondetails.varian.product'])->first();
     $result = $purchase;
     if ($purchase->delete()) {
         return new JSend('success', (array) $result);
     }
     return new JSend('error', (array) $result, $purchase->getError());
 }
Example #17
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getPurchase()
 {
     return $this->hasOne(Purchase::className(), ['id' => 'purchase_id']);
 }
Example #18
0
 public function changeStatus($id, $status)
 {
     $purchaseModel = new Purchase();
     $purchaseModel->changeStatusByProviderId($id, $status);
     $this->where('id', $id)->update(array('status' => $status, 'updated_at' => date('Y-m-d H:i:s'), 'user_id' => Auth::User()->id));
 }
Example #19
0
 /**
  * @POST("/purchase", as="purchase.store")
  * @param Purchase $purchase
  * @param Request $request
  * @return \Illuminate\Http\RedirectResponse
  */
 public function store(Purchase $purchase, Request $request)
 {
     $data = $request->all();
     if ((int) $data['amount'] <= 0) {
         return redirect()->route('profile.index')->with('message', 'Некорректная сумма вклада!');
     }
     $type1 = TypePurchase::where('id', 1)->first();
     $type2 = TypePurchase::where('id', 2)->first();
     $type3 = TypePurchase::where('id', 3)->first();
     $user = User::where('id', $request->input('user_id'))->first();
     $course = Course::where('currency_id', $request->input('currency_id'))->first();
     $data['course'] = $course->course_purchase;
     if ($request->input('status_trust') === 'true') {
         $data['status_trust'] = 1;
         $purchase->fill($data);
         $purchase->type()->associate($type2);
         $purchase->user()->associate($user);
         $purchase->course()->associate($course);
         $purchase->save();
     } elseif (!$request->input('total')) {
         $data['total'] = $request->input('amount');
         $purchase->fill($data);
         $purchase->type()->associate($type3);
         $purchase->user()->associate($user);
         $purchase->course()->associate($course);
         $purchase->save();
     } else {
         $purchase->fill($data);
         $purchase->type()->associate($type1);
         $purchase->user()->associate($user);
         $purchase->course()->associate($course);
         $purchase->save();
     }
     return redirect()->route('profile.index')->with('message', 'Заявка сделана! Свои оперции Вы можете
     посмотреть в разделе "Мои операции"');
 }
Example #20
0
 /**
  * переход по реф ссылке
  * @param type $affiliate_id
  * @param type $url
  */
 public function purchase($affiliate_id, $url)
 {
     if (static::findOne($affiliate_id) === null) {
         $affiliate_id = null;
     }
     $purchase = new Purchase();
     if ($this->id != $affiliate_id) {
         $purchase->affiliate_id = $affiliate_id;
     }
     $purchase->user_id = $this->id;
     $purchase->url_id = $url->id;
     if ($url->shop_id) {
         $purchase->shop_id = $url->shop_id;
     } elseif (isset($url->user->profile)) {
         //$purchase->shop_id = $url->user->profile->user_id;
     }
     $purchase->status = Paylog::STATUS_PENDING;
     $purchase->url = $url->link;
     $purchase->save(false);
     Yii::$app->mailer->compose('user/purchase', ['user' => $this, 'url' => $url])->setFrom(Yii::$app->params['emailFrom'])->setTo($url->user->email)->setSubject('Переход по ссылке')->send();
 }
Example #21
0
 public function actionComplaint()
 {
     $purchase = Purchase::findOne(Yii::$app->request->post('id'));
     if (!$purchase || !isset($purchase->shop)) {
         return;
     }
     Yii::$app->mailer->compose('complaint', ['purchase' => $purchase, 'user' => Yii::$app->user->identity])->setFrom(Yii::$app->params['emailFrom'])->setTo([$purchase->shop->email])->setSubject('Жалоба')->send();
 }
Example #22
0
 /**
  * Finds the Purchase model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  * @param integer $id
  * @return Purchase the loaded model
  * @throws NotFoundHttpException if the model cannot be found
  */
 protected function findModel($id)
 {
     if (($model = Purchase::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
Example #23
0
 /**
  * Update the specified resource in storage.
  *
  * @param  \Illuminate\Http\Request $request
  * @param  int $id
  * @return \Illuminate\Http\Response
  */
 public function update(Request $request, $id)
 {
     if (!$request->input('items')) {
         Session()->flash('error_message', 'Purchases Update has not been Completed');
         return redirect('purchases');
     }
     try {
         DB::transaction(function () use($request, $id) {
             $time = time();
             $workspace_id = Auth::user()->workspace_id;
             $balance_type = Config::get('common.balance_type_intermediate');
             $transaction_type = Config::get('common.transaction_type.purchase');
             $person_type_supplier = Config::get('common.person_type_supplier');
             $year = CommonHelper::get_current_financial_year();
             $user_id = Auth::user()->id;
             $old_main_purchase = Purchase::findOrFail($id);
             $purchase = Purchase::findOrFail($id);
             $purchase->supplier_id = $request->input('supplier_id');
             $purchase->purchase_date = $request->input('purchase_date');
             $purchase->transportation_cost = $request->input('transportation_cost');
             $purchase->paid = $request->input('paid');
             $purchase->total = $request->input('total');
             $purchase->updated_at = time();
             $purchase->updated_by = $user_id;
             $purchase->update();
             //get all old items
             $arrange_old_items = [];
             $old_purchases = PurchaseDetail::where('purchase_id', $id)->get();
             foreach ($old_purchases as $old_purchase) {
                 $arrange_old_items[$old_purchase['material_id']] = $old_purchase;
             }
             foreach ($request->input('items') as $item) {
                 if (isset($arrange_old_items[$item['material_id']])) {
                     // update old data
                     $PurchaseDetail = PurchaseDetail::findOrFail($arrange_old_items[$item['material_id']]['id']);
                     $PurchaseDetail->quantity = $item['quantity'];
                     $PurchaseDetail->received_quantity = $item['received_quantity'];
                     $PurchaseDetail->unit_price = $item['unit_price'];
                     $PurchaseDetail->status = 1;
                     $PurchaseDetail->updated_at = time();
                     $PurchaseDetail->updated_by = $user_id;
                     $PurchaseDetail->update();
                     //update stock info
                     if ($arrange_old_items[$item['material_id']]['received_quantity'] < $item['received_quantity']) {
                         $add_amount = $item['received_quantity'] - $arrange_old_items[$item['material_id']]['received_quantity'];
                         RawStock::where(['material_id' => $item['material_id'], 'year' => $year, 'stock_type' => $balance_type])->increment('quantity', $add_amount, ['updated_at' => $time, 'updated_by' => $user_id]);
                     } elseif ($arrange_old_items[$item['material_id']]['received_quantity'] > $item['received_quantity']) {
                         $sub_amount = $arrange_old_items[$item['material_id']]['received_quantity'] - $item['received_quantity'];
                         RawStock::where(['material_id' => $item['material_id'], 'year' => $year, 'stock_type' => $balance_type])->decrement('quantity', $sub_amount, ['updated_at' => $time, 'updated_by' => $user_id]);
                     }
                     unset($arrange_old_items[$item['material_id']]);
                 } else {
                     //purchase details
                     $item['purchase_id'] = $id;
                     $item['status'] = 1;
                     $item['created_at'] = time();
                     $item['created_by'] = $user_id;
                     PurchaseDetail::create($item);
                     //update stock info
                     RawStock::where(['material_id' => $item['material_id'], 'year' => $year, 'stock_type' => $balance_type])->increment('quantity', $item['received_quantity'], ['updated_at' => $time, 'updated_by' => $user_id]);
                 }
             }
             //delete old data
             foreach ($arrange_old_items as $old_item) {
                 //reduce the stock info
                 RawStock::where(['material_id' => $item['material_id'], 'year' => $year, 'stock_type' => $balance_type])->decrement('quantity', $old_item['received_quantity'], ['updated_at' => $time, 'updated_by' => $user_id]);
                 //update the purchase info
                 $PurchaseDetail = PurchaseDetail::findOrFail($old_item['id']);
                 $PurchaseDetail->delete();
             }
             /*
              * Account management
              *
              */
             $input = $request->input();
             if ($old_main_purchase['transportation_cost'] != $input['transportation_cost']) {
                 if ($old_main_purchase['transportation_cost'] > $input['transportation_cost']) {
                     $deviation = $old_main_purchase['transportation_cost'] - $input['transportation_cost'];
                     // Update Workspace Ledger
                     $workspace = WorkspaceLedger::where(['account_code' => 24000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                     $workspace->balance -= $input['transportation_cost'];
                     $workspace->updated_by = $user_id;
                     $workspace->updated_at = $time;
                     $workspace->save();
                     $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                     $workspace->balance += $input['transportation_cost'];
                     $workspace->updated_by = $user_id;
                     $workspace->updated_at = $time;
                     $workspace->save();
                     //Update General Journal
                     $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 24000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                     $general_journal->amount -= $deviation;
                     $general_journal->updated_by = $user_id;
                     $general_journal->updated_at = $time;
                     $general_journal->save();
                     $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 11000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                     $general_journal->amount -= $deviation;
                     $general_journal->updated_by = $user_id;
                     $general_journal->updated_at = $time;
                     $general_journal->save();
                 } elseif ($old_main_purchase['transportation_cost'] < $input['transportation_cost']) {
                     $deviation = $input['transportation_cost'] - $old_main_purchase['transportation_cost'];
                     // Update Workspace Ledger
                     $workspace = WorkspaceLedger::where(['account_code' => 24000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                     $workspace->balance += $input['transportation_cost'];
                     $workspace->updated_by = $user_id;
                     $workspace->updated_at = $time;
                     $workspace->save();
                     $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                     $workspace->balance -= $input['transportation_cost'];
                     $workspace->updated_by = $user_id;
                     $workspace->updated_at = $time;
                     $workspace->save();
                     //Update General Journal
                     $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 24000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                     $general_journal->amount += $deviation;
                     $general_journal->updated_by = $user_id;
                     $general_journal->updated_at = $time;
                     $general_journal->save();
                     $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 11000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                     $general_journal->amount += $deviation;
                     $general_journal->updated_by = $user_id;
                     $general_journal->updated_at = $time;
                     $general_journal->save();
                 }
             }
             if ($input['paid'] && $old_main_purchase['paid'] < $input['paid']) {
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $new_remain_paid_amount = $input['paid'] - $old_main_purchase['paid'];
                 if ($new_remain_paid_amount > $workspace->balance) {
                     Session()->flash('warning_message', 'Low Balance!! New Purchase paid amount(' . $new_remain_paid_amount . ') is greater than Balance (' . $workspace->balance . ')');
                     throw new \Exception('error');
                 }
             }
             //update the accounting tables
             $workspace_id = Auth::user()->workspace_id;
             $balance_type = Config::get('common.balance_type_intermediate');
             $transaction_type = Config::get('common.transaction_type.purchase');
             $person_type_supplier = Config::get('common.person_type_supplier');
             $user_id = Auth::user()->id;
             $time = time();
             //update general journal for raw material purchase
             $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 25000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
             $general_journal->amount = $input['total'];
             $general_journal->updated_by = $user_id;
             $general_journal->updated_at = $time;
             $general_journal->save();
             //update Workspace for raw material purchase
             $new_total_amount = $input['total'];
             $old_total_amount = $old_main_purchase['total'];
             if ($new_total_amount > $old_total_amount) {
                 $workspace = WorkspaceLedger::where(['account_code' => 25000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $new_total_amount - $old_total_amount;
                 //add material purchase
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
             } elseif ($new_total_amount < $old_total_amount) {
                 $workspace = WorkspaceLedger::where(['account_code' => 25000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $old_total_amount - $new_total_amount;
                 //sub material purchase
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
             }
             //update cash amount
             $new_paid_amount = $input['paid'];
             $old_paid_amount = $old_main_purchase['paid'];
             //                throw new \Exception($new_paid_amount.'='.$old_paid_amount);
             if (!$new_paid_amount && $old_paid_amount) {
                 $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 11000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                 $general_journal->delete();
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $old_paid_amount;
                 //sub Cash
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
             } elseif (!$old_paid_amount && $new_paid_amount) {
                 //Insert data into General Journal
                 $journal = new GeneralJournal();
                 $journal->date = $time;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $id;
                 $journal->year = $year;
                 $journal->account_code = 11000;
                 //Cash
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $new_paid_amount;
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $new_paid_amount;
                 //sub Cash
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
             } elseif ($new_paid_amount > $old_paid_amount) {
                 $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 11000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                 $general_journal->amount = $new_paid_amount;
                 $general_journal->updated_by = $user_id;
                 $general_journal->updated_at = $time;
                 $general_journal->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $new_paid_amount - $old_paid_amount;
                 //sub Cash
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
             } elseif ($new_paid_amount < $old_paid_amount) {
                 $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 11000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                 $general_journal->amount = $new_paid_amount;
                 $general_journal->updated_by = $user_id;
                 $general_journal->updated_at = $time;
                 $general_journal->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $old_paid_amount - $new_paid_amount;
                 //add Cash
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
             }
             //DUE management (liabilities)
             $new_due_amount = $input['total'] - $input['paid'];
             $old_due_amount = $old_main_purchase['total'] - $old_main_purchase['paid'];
             if ($new_due_amount && !$old_due_amount) {
                 $journal = new GeneralJournal();
                 $journal->date = $time;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $id;
                 $journal->year = $year;
                 $journal->account_code = 41000;
                 //Account Payable
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $new_due_amount;
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 41000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $new_due_amount;
                 //add account payable credit
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 // Update Personal Account
                 $personal = PersonalAccount::where('person_id', $input['supplier_id'])->where('person_type', $person_type_supplier)->first();
                 $personal->balance += $new_due_amount;
                 $personal->updated_by = $user_id;
                 $personal->updated_at = $time;
                 $personal->save();
             } elseif ($old_due_amount && !$new_due_amount) {
                 $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 41000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                 $general_journal->delete();
                 $workspace = WorkspaceLedger::where(['account_code' => 41000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $old_due_amount;
                 //add account payable debit
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 // Update Personal Account
                 $personal = PersonalAccount::where('person_id', $input['supplier_id'])->where('person_type', $person_type_supplier)->first();
                 $personal->balance -= $old_due_amount;
                 $personal->updated_by = $user_id;
                 $personal->updated_at = $time;
                 $personal->save();
             } elseif ($new_due_amount > $old_due_amount) {
                 $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 41000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                 $general_journal->amount = $new_due_amount;
                 $general_journal->updated_by = $user_id;
                 $general_journal->updated_at = $time;
                 $general_journal->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 41000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $new_due_amount - $old_due_amount;
                 //add account payable debit
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 // Update Personal Account
                 $personal = PersonalAccount::where('person_id', $input['supplier_id'])->where('person_type', $person_type_supplier)->first();
                 $personal->balance += $new_due_amount - $old_due_amount;
                 $personal->updated_by = $user_id;
                 $personal->updated_at = $time;
                 $personal->save();
             } elseif ($new_due_amount < $old_due_amount) {
                 $general_journal = GeneralJournal::where(['transaction_type' => $transaction_type, 'reference_id' => $id, 'account_code' => 41000, 'year' => $year, 'workspace_id' => $workspace_id])->first();
                 $general_journal->amount = $new_due_amount;
                 $general_journal->updated_by = $user_id;
                 $general_journal->updated_at = $time;
                 $general_journal->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 41000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $old_due_amount - $new_due_amount;
                 //add account payable debit
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 // Update Personal Account
                 $personal = PersonalAccount::where('person_id', $input['supplier_id'])->where('person_type', $person_type_supplier)->first();
                 $personal->balance -= $old_due_amount - $new_due_amount;
                 $personal->updated_by = $user_id;
                 $personal->updated_at = $time;
                 $personal->save();
             }
         });
     } catch (\Exception $e) {
         Session()->flash('error_message', $e->getMessage());
         //            Session()->flash('error_message','Purchases Update has not been Completed');
         return Redirect::back();
     }
     Session()->flash('flash_message', 'Purchases Update has been Completed');
     return redirect('purchases');
 }