Example #1
0
 /** 
  * observe payment event saving
  * 1. check haven't been paid
  * 2. recalculate shipping_cost
  * 3. act, accept or refuse
  * 
  * @param $model
  * @return bool
  */
 public function saving($model)
 {
     $errors = new MessageBag();
     if ($model->package == '') {
         $model->package = 'regular';
     }
     //1. check haven't been paid
     if ($model->sale()->count() && !in_array($model->sale->status, ['na', 'cart', 'wait']) && isset($model->getDirty()['address_id'])) {
         $errors->add('Shipment', 'Tidak dapat mengubah destinasi pengiriman.');
     }
     //2. recalculate shipping_cost
     if ($model->address()->count()) {
         $shippingcost = ShippingCost::courierid($model->courier_id)->postalcode($model->address->zipcode)->first();
         if ($shippingcost && $model->sale()->count() && $model->sale->transactiondetails()->count()) {
             $shipping_cost = $model->CountShippingCost($model->sale->transactiondetails, $shippingcost['cost']);
             $sale = Sale::findorfail($model->transaction_id);
             $sale->fill(['shipping_cost' => $shipping_cost]);
             if (!$sale->save()) {
                 $errors->add('Shipment', $sale->getError());
             }
         } else {
             $errors->add('Shipment', 'Tidak ada kurir ke tempat anda (Silahkan periksa kembali kode pos anda).');
         }
     } elseif ($model->sale()->count()) {
         $sale = Sale::findorfail($model->transaction_id);
         $sale->fill(['shipping_cost' => 0]);
         if (!$sale->save()) {
             $errors->add('Shipment', $sale->getError());
         }
     }
     if ($errors->count()) {
         $model['errors'] = $errors;
         return false;
     }
     return true;
 }
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getShippingCosts()
 {
     return $this->hasMany(ShippingCost::className(), ['kind_of_goods_kind_of_goods_id' => 'kind_of_goods_id']);
 }