/** * Store a newly created resource in storage. * * @return Response */ public function store(Stantion $depo, Product $product, StoreStation $request) { $products = $product->all(); DB::transaction(function () use($depo, $request, $products) { $lastInsertedDepo = $depo->create($request->all()); $pricesIdArr = []; foreach ($products as $prod) { $price = new Price(); $price->price = 0; $price->save(); $prod->price()->attach($price->id); $pricesIdArr[] = $price->id; } $lastInsertedDepo->price()->sync($pricesIdArr); }); return redirect('stations')->with('alert-warning', 'Депо успешно добавлено! Внимание! Не забудьте проставить цену товарам для этого депо'); }
/** * @param array|null $params * * @return ActiveDataProvider */ public function search($params) { $query = Price::find()->joinWith('invTypes'); $dataProvider = new ActiveDataProvider(['query' => $query]); if (!$this->load($params) && !$this->validate()) { return $dataProvider; } $query->andFilterWhere(['typeID' => $this->typeID])->andFilterWhere(['type' => $this->type])->andFilterWhere(['like', 'typeName', $this->getAttribute('typeName')]); return $dataProvider; }
/** * @param \SimpleXMLElement $row * * @return bool */ private function update(\SimpleXMLElement $row) { $return = true; $type = AbstractCall::getXmlAttr($row); // buy /** @var Price $price */ $price = Price::findOne(['typeID' => $type['id'], 'type' => Price::TYPE_BUY]); if (!$price) { $price = new Price(); $price->typeID = $type['id']; $price->type = Price::TYPE_BUY; } $price->volume = (string) $row->buy->volume; $price->average = (string) $row->buy->avg; $price->min = (string) $row->buy->min; $price->max = (string) $row->buy->max; $price->stdDev = (string) $row->buy->stddev; $price->median = (string) $row->buy->median; $price->percentile = (string) $row->buy->percentile; $return = $price->save() && $return; // sell /** @var Price $price */ $price = Price::findOne(['typeID' => $type['id'], 'type' => Price::TYPE_SELL]); if (!$price) { $price = new Price(); $price->typeID = $type['id']; $price->type = Price::TYPE_SELL; } $price->volume = (string) $row->sell->volume; $price->average = (string) $row->sell->avg; $price->min = (string) $row->sell->min; $price->max = (string) $row->sell->max; $price->stdDev = (string) $row->sell->stddev; $price->median = (string) $row->sell->median; $price->percentile = (string) $row->sell->percentile; $return = $price->save() && $return; return $return; }
/** * observe product event deleting * 1. delete varian * 2. delete price * 3. delete category(and tag) * 4. delete label * 5. delete image * 6. act, accept or refuse * * @param $model * @return bool */ public function deleting($model) { $errors = new MessageBag(); //1. delete product's varian $varians = Varian::where('product_id', $model->id)->get(); foreach ($varians as $varian) { if (!$varian->delete()) { $errors->add('varian', $varian->getError()); } } //2. delete product's price $prices = Price::where('product_id', $model->id)->get(); foreach ($prices as $price) { if (!$price->delete()) { $errors->add('price', $price->getError()); } } //3. delete product's categories $categories = CategoryProduct::where('product_id', $model->id)->get(); foreach ($categories as $category) { if (!$category->delete()) { $errors->add('category', $category->getError()); } } //4. delete product's label $labels = ProductLabel::where('product_id', $model->id)->get(); foreach ($labels as $label) { if (!$label->delete()) { $errors->add('label', $label->getError()); } } //5. delete product's image $images = Image::where('imageable_type', 'App\\Models\\Product')->where('imageable_id', $model->id)->get(); foreach ($images as $image) { if (!$image->delete()) { $errors->add('image', $image->getError()); } } if ($errors->count()) { $model['errors'] = $errors; return false; } return true; }
/** * Updates the dvd record in the database * @param array $input * @param App\Models\DVDInfo $dvd */ public function update(DVDInfo $dvd, array $input) { $dvd->fill($input); $dvd->save(); if (!$dvd->dvds->isEmpty()) { $price = Price::firstOrCreate(['price_whole' => $input['price_whole'], 'price_cents' => $input['price_cents'], 'late_fee_whole' => $input['late_fee_whole'], 'late_fee_cents' => $input['late_fee_cents'], 'points' => $input['points']]); $dvd->dvds()->update(['price_id' => $price->id, 'age_restriction' => $input['age_restriction']]); } $stockChange = $dvd->totalStock() - $input['stock']; // Reduce stock if ($stockChange > 0) { $unrented = $dvd->getUnrented(); $unrented = $unrented->take($stockChange); $ids = array_keys($unrented->getDictionary()); DVD::destroy($ids); } // Increase stock if ($stockChange < 0) { $newDvds = []; while ($stockChange < 0) { array_push($newDvds, new DVD(['price_id' => $price->id, 'age_restriction' => $input['age_restriction']])); $stockChange += 1; } $dvd->dvds()->saveMany($newDvds); } }
public function actionPrice() { if (isset($_POST['p'])) { $modelPrice = new Price(); $modelPrice->price = $_POST['p']['p_price']; $modelPrice->tax = $_POST['p']['p_tax']; $modelPrice->total = $_POST['p']['p_total']; $modelPrice->calculate(); echo $modelPrice->getAjaxValue(); } else { throw new Exception(Yii::t('error', 'Bad request')); } }
/** * Add new book to database. * @param [array] $data array data from request * @return [type] $book object book model which has just created */ public function addNewBook($data) { $book = Book::create(['title' => $data['title'], 'bookurl' => $data['bookurl'], 'language_id' => 1, 'avatar' => 'question-mark.png', 'diravatar' => 'question-mark.png']); DB::table('book_author')->insert(['book_id' => $book->id, 'author_id' => Auth::user()->id, 'is_main' => 1, 'is_accepted' => 1]); Price::create(['item_id' => 'bo|' . $book->id, 'minimumprice' => 0, 'suggestedprice' => 0]); return $book; }
/** * Store a product * * 1. Save Product * 2. Save Varian * 3. Save Price * 4. Save Category * 5. Save Tag * 6. Save Label * 7. Save Image * * @return Response */ public function store() { if (!Input::has('product')) { return new JSend('error', (array) Input::all(), 'Tidak ada data produk.'); } $errors = new MessageBag(); DB::beginTransaction(); //1. Validate Product Parameter $product = Input::get('product'); //1a. Get original data if (is_null($product['id'])) { $product_data = new \App\Models\Product(); $is_new = true; } else { $product_data = \App\Models\Product::findornew($product['id']); $is_new = false; } if (isset($product['description'])) { $product['description'] = json_decode($product['description'], true); } $product_rules = ['name' => 'required|max:255', 'upc' => 'required|max:255|unique:products,upc,' . (!is_null($product['id']) ? $product['id'] : ''), 'slug' => 'max:255|unique:products,slug,' . (!is_null($product['id']) ? $product['id'] : ''), 'description.description' => 'max:512', 'description.fit' => 'max:512']; //1b. Validate Basic Product Parameter $validator = Validator::make($product, $product_rules); if (!$validator->passes()) { $errors->add('Product', $validator->errors()); } else { //if validator passed, save product if (isset($product['description'])) { $product['description'] = json_encode($product['description']); } else { $product['description'] = json_encode(['description' => '', 'fit' => '']); } $product_data = $product_data->fill($product); if (!$product_data->save()) { $errors->add('Product', $product_data->getError()); } } //End of validate product //2. Validate Product Varian Parameter if (!$errors->count() && isset($product['varians']) && is_array($product['varians'])) { $varian_current_ids = []; foreach ($product['varians'] as $key => $value) { if (!$errors->count()) { $varian_data = \App\Models\Varian::findornew($value['id']); $varian_rules = ['product_id' => 'exists:products,id|' . ($is_new ? '' : 'in:' . $product_data['id']), 'sku' => 'required|max:255|unique:varians,sku,' . (!is_null($value['id']) ? $value['id'] : ''), 'size' => 'required|max:255']; $validator = Validator::make($value, $varian_rules); //if there was varian and validator false if (!$validator->passes()) { $errors->add('Varian', $validator->errors); } else { $value['product_id'] = $product_data['id']; $varian_data = $varian_data->fill($value); if (!$varian_data->save()) { $errors->add('Varian', $varian_data->getError()); } else { $varian_current_ids[] = $varian_data['id']; } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $varians = \App\Models\Varian::productid($product['id'])->get(['id'])->toArray(); $varian_should_be_ids = []; foreach ($varians as $key => $value) { $varian_should_be_ids[] = $value['id']; } $difference_varian_ids = array_diff($varian_should_be_ids, $varian_current_ids); if ($difference_varian_ids) { foreach ($difference_varian_ids as $key => $value) { $varian_data = \App\Models\Varian::find($value); if (!$varian_data->delete()) { $errors->add('Varian', $varian_data->getError()); } } } } } //End of validate product varian //3. Validate Product Price Parameter if (!$errors->count() && isset($product['prices']) && is_array($product['prices'])) { $price_current_ids = []; foreach ($product['prices'] as $key => $value) { if (!$errors->count()) { $price_data = \App\Models\Price::findornew($value['id']); $price_rules = ['product_id' => 'exists:products,id|' . ($is_new ? '' : 'in:' . $product_data['id']), 'price' => 'required|numeric', 'promo_price' => 'numeric|max:price', 'started_at' => 'required|date_format:"Y-m-d H:i:s"']; $validator = Validator::make($value, $price_rules); //if there was price and validator false if (!$validator->passes()) { $errors->add('Price', $validator->errors()); } else { $value['product_id'] = $product_data['id']; $price_data = $price_data->fill($value); if (!$price_data->save()) { $errors->add('Price', $price_data->getError()); } else { $price_current_ids[] = $price_data['id']; } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $prices = \App\Models\Price::productid($product['id'])->get(['id'])->toArray(); $price_should_be_ids = []; foreach ($prices as $key => $value) { $price_should_be_ids[] = $value['id']; } $difference_price_ids = array_diff($price_should_be_ids, $price_current_ids); if ($difference_price_ids) { foreach ($difference_price_ids as $key => $value) { $price_data = \App\Models\Price::find($value); if (!$price_data->delete()) { $errors->add('Price', $price_data->getError()); } } } } } //End of validate product price $cluster_current_ids = []; //4. Validate Product Category Parameter if (!$errors->count() && isset($product['categories']) && is_array($product['categories'])) { $category_current_ids = []; foreach ($product['categories'] as $key => $value) { $category = \App\Models\Category::find($value['id']); if ($category) { $category_current_ids[] = $value['id']; $cluster_current_ids[] = $value['id']; } elseif (isset($value['name'])) { $category_data = new \App\Models\Category(); $category_data = $category_data->fill(['name' => $value['name']]); if (!$category_data->save()) { $errors->add('Category', $category_data->getError()); } else { $category_current_ids[] = $category_data['id']; $cluster_current_ids[] = $category_data['id']; } } } // if(!$errors->count()) // { // if(!$product_data->categories()->sync($category_current_ids)) // { // $errors->add('Category', 'Kategori produk tidak tersimpan.'); // } // } } //End of validate product category //5. Validate Product Tag Parameter if (!$errors->count() && isset($product['tags']) && is_array($product['tags'])) { $tag_current_ids = []; foreach ($product['tags'] as $key => $value) { $tag = \App\Models\Tag::find($value['id']); if ($tag) { $tag_current_ids[] = $value['id']; $cluster_current_ids[] = $value['id']; } elseif (isset($value['name'])) { $tag_data = new \App\Models\Tag(); $tag_data = $tag_data->fill(['name' => $value['name']]); if (!$tag_data->save()) { $errors->add('Tag', $tag_data->getError()); } else { $tag_current_ids[] = $tag_data['id']; $cluster_current_ids[] = $tag_data['id']; } } } // if(!$errors->count()) // { // if(!$product_data->tags()->sync($tag_current_ids)) // { // $errors->add('Tag', 'Tag produk tidak tersimpan.'); // } // } } if (!$errors->count() && isset($cluster_current_ids)) { if (!$product_data->clusters()->sync($cluster_current_ids)) { $errors->add('Product', 'Tag/Kategori produk tidak tersimpan.'); } } //End of validate product category //6. Validate Product Label Parameter if (!$errors->count() && isset($product['labels']) && is_array($product['labels'])) { $label_current_ids = []; foreach ($product['labels'] as $key => $value) { if (!$errors->count()) { $label_data = \App\Models\ProductLabel::findornew($value['id']); $label_rules = ['product_id' => 'exists:products,id|' . ($is_new ? '' : 'in:' . $product_data['id']), 'label' => 'max:255', 'started_at' => 'required|date_format:"Y-m-d H:i:s"', 'ended_at' => 'date_format:"Y-m-d H:i:s"']; if (!isset($value['ended_at']) || !strtotime($value['ended_at'])) { unset($value['ended_at']); } $validator = Validator::make($value, $label_rules); //if there was label and validator false if (!$validator->passes()) { $errors->add('ProductLabel', $validator->errors()); } else { $value['product_id'] = $product_data['id']; if (isset($value['label'])) { $value['lable'] = $value['label']; } $label_data = $label_data->fill($value); if (!$label_data->save()) { $errors->add('ProductLabel', $label_data->getError()); } else { $label_current_ids[] = $label_data['id']; } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $labels = \App\Models\ProductLabel::productid($product['id'])->get(['id'])->toArray(); $label_should_be_ids = []; foreach ($labels as $key => $value) { $label_should_be_ids[] = $value['id']; } $difference_label_ids = array_diff($label_should_be_ids, $label_current_ids); if ($difference_label_ids) { foreach ($difference_label_ids as $key => $value) { $label_data = \App\Models\ProductLabel::find($value); if (!$label_data->delete()) { $errors->add('ProductLabel', $label_data->getError()); } } } } } //End of validate product label //7. Validate Product Image Parameter if (!$errors->count() && isset($product['images']) && is_array($product['images'])) { $image_current_ids = []; foreach ($product['images'] as $key => $value) { if (!$errors->count()) { $image_data = \App\Models\Image::findornew($value['id']); $image_rules = ['imageable_id' => 'exists:products,id|' . ($is_new ? '' : 'in:' . $product_data['id']), 'imageable_type' => $is_new ? '' : 'in:' . get_class($product_data), 'thumbnail' => 'required|max:255', 'image_xs' => 'required|max:255', 'image_sm' => 'required|max:255', 'image_md' => 'required|max:255', 'image_lg' => 'required|max:255', 'is_default' => 'boolean']; $validator = Validator::make($value, $image_rules); //if there was image and validator false if (!$validator->passes()) { $errors->add('Image', $validator->errors()); } else { $value['imageable_id'] = $product_data['id']; $value['imageable_type'] = get_class($product_data); $image_data = $image_data->fill($value); if (!$image_data->save()) { $errors->add('Image', $image_data->getError()); } else { $image_current_ids[] = $image_data['id']; } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $images = \App\Models\Image::imageableid($product['id'])->imageabletype(get_class($product_data))->get(['id'])->toArray(); $image_should_be_ids = []; foreach ($images as $key => $value) { $image_should_be_ids[] = $value['id']; } $difference_image_ids = array_diff($image_should_be_ids, $image_current_ids); if ($difference_image_ids) { foreach ($difference_image_ids as $key => $value) { $image_data = \App\Models\Image::find($value); if (!$image_data->delete()) { $errors->add('Image', $image_data->getError()); } } } } } //End of validate product image if ($errors->count()) { DB::rollback(); return new JSend('error', (array) Input::all(), $errors); } DB::commit(); $final_product = \App\Models\Product::id($product_data['id'])->with(['varians', 'categories', 'tags', 'labels', 'images', 'prices'])->first()->toArray(); return new JSend('success', (array) $final_product); }
/** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update(Request $request, $id) { // try{ // $productCartItem = ProductCart::findOrFail($id); // } catch(ModelNotFoundException $e) { // return redirect('fatalError'); // } // $productCartItem->product_count = $request->value; // $productCartItem->save(); try { $productCartItem = ProductCart::findOrFail($id); $price = Price::with('product')->where('id', $productCartItem->price_id)->first(); $currentAmount = $price->amount; } catch (ModelNotFoundException $e) { return redirect('fatalError'); } DB::transaction(function () use($id, $price, $productCartItem, $request, &$currentAmount) { if ((int) $currentAmount >= (int) $request->value) { // $price->amount -= (int) $request->value; // $price->save(); $productCartItem->product_count = $request->value; $productCartItem->save(); $currentAmount = 0; } }); echo $currentAmount; }
/** * boot * */ public static function boot() { parent::boot(); Price::observe(new PriceObserver()); }
/** * @return \yii\db\ActiveQuery */ public function getPrice() { return $this->hasOne(Price::className(), ['id' => 'price_id']); }
/** * Store a newly created resource in storage. * * @return Response */ public function store(Product $product, Request $request) { //$id = $request->route('products'); //dd($id); $validationRules = ['name' => 'required|alpha_spaces_numbers|max:35|unique:products', 'article' => 'required|alpha_spaces_numbers|max:15', 'description' => 'required|alpha_spaces_numbers', 'condition_id' => 'required|integer']; $depos = Stantion::all(); foreach ($depos as $depo) { $validationRules['price' . $depo->id] = 'required|numeric'; $validationRules['amount' . $depo->id] = 'required|numeric'; $validationRules['vat' . $depo->id] = 'required|numeric'; } $v = Validator::make($request->all(), $validationRules); if ($v->fails()) { return redirect()->back()->withErrors($v->errors())->withInput(); } DB::transaction(function () use($product, $request, $depos) { $product->article = $request->article; $product->name = $request->name; $product->description = $request->description; $product->condition_id = $request->condition_id; if (!(int) $request->category_id) { $product->category_id = null; } else { $product->category_id = $request->category_id; } $product->save(); $priceIdArr = []; foreach ($depos as $depo) { $price = new Price(); $priceInputName = 'price' . $depo->id; $priceInputAmount = 'amount' . $depo->id; $priceInputVAT = 'vat' . $depo->id; $price->price = $request->{$priceInputName}; $price->amount = $request->{$priceInputAmount}; $price->nds = $request->{$priceInputVAT}; $price->save(); $depo->price()->attach($price->id); $priceIdArr[] = $price->id; } $product->price()->sync($priceIdArr); }); return redirect('products')->with('alert-success', 'Товар успешно добавлен!'); }
/** * @return null|Price */ public function getPriceSell() { return Price::findOne(['typeID' => $this->typeID, 'type' => Price::TYPE_SELL]); }
/** * @return \yii\db\ActiveQuery */ public function getPrice() { return $this->hasOne(Price::className(), ['typeID' => 'typeID']); }
/** * Creates a new Bill model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Bill(); if (Yii::$app->session['carPartTotal'] <= 0.0) { return; } if (isset($_POST['mode'], $_POST['discount'])) { $result = []; if ($_POST['mode'] == 0 || $_POST['mode'] == 1) { $transaction = $model->getDb()->beginTransaction(); try { $discount = (double) $_POST['discount']; if ($discount > Yii::$app->session['carPartTotal']) { $discount = 0.0; } $modelPrice = new Price(); $modelPrice->price = (double) Yii::$app->session['carPartTotal'] - (double) $discount; $modelPrice->calculate(); if (!$modelPrice->save(false)) { throw new Exception(Yii::t('app', 'Error saving {model}: {msj}', ['model' => Yii::t('app', ucfirst($modelPrice->tableName())), 'msj' => print_r($modelPrice->getErrors(), true)]), 500); } $model->price_id = $modelPrice->id; $model->discount = $discount; if (isset($_POST['draft']) && !empty($_POST['draft'])) { $model->draft = 1; } if (isset($_POST['Vehicle'])) { $vehicle = new Vehicle(); $vehicle->attributes = $_POST['Vehicle']; if (!empty($vehicle->brand) || !empty($vehicle->model) || !empty($vehicle->color) || !empty($vehicle->plaque)) { if (!$vehicle->save(false)) { throw new Exception(Yii::t('app', 'Error saving {model}: {msj}', ['model' => Yii::t('app', ucfirst($vehicle->tableName())), 'msj' => print_r($vehicle->getErrors(), true)]), 500); } $model->vehicle_id = $vehicle->id; } } if (isset($_POST['Customer'])) { $customer = new Customer(); $customer->attributes = $_POST['Customer']; if (!empty($customer->name) || !empty($customer->serial)) { if (!$customer->save(false)) { throw new Exception(Yii::t('app', 'Error saving {model}: {msj}', ['model' => Yii::t('app', ucfirst($customer->tableName())), 'msj' => print_r($customer->getErrors(), true)]), 500); } $model->customer_id = $customer->id; } } if ($model->save()) { $result['message'] = Yii::t('app', '{modelClass} saved', ['modelClass' => Yii::t('app', ucfirst($model->tableName()))]); } else { $result['message'] = Yii::t('app', 'Error saving {model}: {msj}', ['model' => Yii::t('app', ucfirst($model->tableName())), 'msj' => print_r($model->errors, true)]); } $transaction->commit(); } catch (\Exception $e) { $transaction->rollBack(); $result['message'] = Yii::t('app', 'Error saving {model}: {msj}', ['model' => Yii::t('app', ucfirst($model->tableName())), 'msj' => $e]); } } echo json_encode($result); } else { if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', ['model' => $model]); } } }
/** * 1. check product * 2. Price Changed * 2.*. Art of discount1 : if there were discount amount, prices will be reduced by certain amount * 2.*. Art of discount2 : if there were discount amount, prices will be reduced by certain amount * 2.*. Art of discount3 : if there were discount percentage, prices will be reduced by certain percentage * * @return true * @author **/ public function broadcastdiscount($id) { $queue = new Queue(); $pending = $queue->find($id); $parameters = json_decode($pending->parameter, true); $messages = json_decode($pending->message, true); //1. Check product $products = new \App\Models\Product(); $products = $products->sellable(true); //1a. Only for certain category if (isset($parameters['category_ids'])) { $products = $products->categoriesid($parameters['category_ids']); } elseif (isset($parameters['tag_ids'])) { $products = $products->tagsid($parameters['tag_ids']); } $products = $products->get(); //2. Price Changed foreach ($products as $idx => $product) { $errors = new MessageBag(); //2a. Check price on that end period //if there were setup price right after end date, do nothing //if there were setup price after end date, but not precisely duplicated latest and expand right after //if there were no setup price right after end date, duplicate latest price with right after end date $price = \App\Models\Price::productid($product['id'])->where('started_at', '>', date('Y-m-d H:i:s', strtotime($parameters['ended_at'])))->orderby('started_at', 'desc')->first(); $promo = 0; if ($price) { if (date('Y-m-d H:i:s', strtotime($parameters['ended_at'] . ' + 1 second')) != $price['started_at']->format('Y-m-d H:i:s')) { $prev = $price->toArray(); $price = new \App\Models\Price(); $price->fill($prev); $price->started_at = date('Y-m-d H:i:s', strtotime($parameters['ended_at'] . ' + 1 second')); if (!$price->save()) { $errors->add('Price', $price->getError()); } } } else { $price = \App\Models\Price::productid($product['id'])->ondate($parameters['ended_at'])->orderby('started_at', 'desc')->first(); if ($price) { $prev = $price->toArray(); $price = new \App\Models\Price(); $price->fill($prev); $price->started_at = date('Y-m-d H:i:s', strtotime($parameters['ended_at'] . ' + 1 second')); if (!$price->save()) { $errors->add('Price', $price->getError()); } } } //2b. Check price on that start day //if there were setup price right after start date, create new one //if there were setup price exactly in time, update promo price $price = \App\Models\Price::productid($product['id'])->ondate($parameters['started_at'])->orderby('started_at', 'desc')->first(); $promo = 0; if ($price) { if (isset($parameters['discount_amount']) && isset($parameters['discount_percentage']) && $parameters['discount_percentage'] != 0) { $promo = $price['price'] - $parameters['discount_amount'] - ($price['price'] - $parameters['discount_amount']) * $parameters['discount_percentage'] / 100; } elseif (isset($parameters['discount_amount'])) { $promo = $price['price'] - $parameters['discount_amount']; } elseif (isset($parameters['discount_percentage']) && $parameters['discount_percentage'] != 0) { $promo = $price['price'] - $price['price'] * $parameters['discount_percentage'] / 100; } if ($parameters['started_at'] == $price['started_at']->format('Y-m-d H:i:s')) { $price->promo_price = "{$promo}"; } else { $prev = $price->toArray(); $price = new \App\Models\Price(); $price->fill($prev); $price->started_at = $parameters['started_at']; $price->promo_price = "{$promo}"; } if (!$price->save()) { $errors->add('Price', $price->getError()); } } //2c. Check price on that period //if there were setup price during period, update promo price $prices = \App\Models\Price::productid($product['id'])->ondate([date('Y-m-d H:i:s', strtotime($parameters['started_at'] . ' + 1 second')), $parameters['ended_at']])->orderby('started_at', 'desc')->get(); foreach ($prices as $key => $value) { $price = \App\Models\Price::id($value['id'])->first(); if ($price) { if (isset($parameters['discount_amount']) && isset($parameters['discount_percentage']) && $parameters['discount_percentage'] != 0) { $promo = $price['price'] - $parameters['discount_amount'] - ($price['price'] - $parameters['discount_amount']) * $parameters['discount_percentage'] / 100; } elseif (isset($parameters['discount_amount'])) { $promo = $price['price'] - $parameters['discount_amount']; } elseif (isset($parameters['discount_percentage']) && $parameters['discount_percentage'] != 0) { $promo = $price['price'] - $price['price'] * $parameters['discount_percentage'] / 100; } $price->promo_price = "{$promo}"; if (!$price->save()) { $errors->add('Price', $price->getError()); } } } if (!$errors->count()) { $pnumber = $pending->process_number + 1; $messages['message'][$pnumber] = 'Sukses Menyimpan Perubahan Harga ' . (isset($product['name']) ? $product['name'] : ''); $pending->fill(['process_number' => $pnumber, 'message' => json_encode($messages)]); } else { $pnumber = $pending->process_number + 1; $messages['message'][$pnumber] = 'Gagal Menyimpan Perubahan Harga ' . (isset($product['name']) ? $product['name'] : ''); $messages['errors'][$pnumber] = $errors; $pending->fill(['process_number' => $pnumber, 'message' => json_encode($messages)]); } $pending->save(); } return true; }