/**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Shipment();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Shipment'])) {
         $model->attributes = $_POST['Shipment'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->shipkey));
         }
     }
     $this->render('create', array('model' => $model));
 }
Beispiel #2
0
 public function order_save($indata, $api_key, $transaction_id)
 {
     date_default_timezone_set('Asia/Jakarta');
     $args = '';
     //$api_key = $this->get('key');
     //$transaction_id = $this->get('trx');
     if (is_null($api_key)) {
         $result = json_encode(array('status' => 'ERR:NOKEY', 'timestamp' => now()));
         return $result;
     } else {
         $app = \Prefs::get_key_info(trim($api_key));
         if ($app == false) {
             $result = json_encode(array('status' => 'ERR:INVALIDKEY', 'timestamp' => now()));
             return $result;
         } else {
             //$in = $this->input->post('transaction_detail');
             //$in = file_get_contents('php://input');
             $in = $indata;
             //print $in;
             $buyer_id = 1;
             $args = 'p=' . $in;
             $in = json_decode($in);
             //print "order input to save: \r\n";
             //print_r($in);
             $is_new = false;
             $in->phone = isset($in->phone) && $in->phone != '' ? \Prefs::normalphone($in->phone) : '';
             $in->mobile1 = isset($in->mobile1) && $in->mobile1 != '' ? \Prefs::normalphone($in->mobile1) : '';
             $in->mobile2 = isset($in->mobile2) && $in->mobile2 != '' ? \Prefs::normalphone($in->mobile2) : '';
             if (isset($in->buyer_id) && $in->buyer_id != '' && $in->buyer_id > 1) {
                 $buyer_id = $in->buyer_id;
                 $is_new = false;
             } else {
                 if ($in->email == '' || $in->email == '-' || !isset($in->email) || $in->email == 'noemail') {
                     $in->email = 'noemail';
                     $is_new = true;
                     if (trim($in->phone . $in->mobile1 . $in->mobile2) != '') {
                         if ($buyer = \Prefs::check_phone($in->phone, $in->mobile1, $in->mobile2)) {
                             $buyer_id = $buyer['id'];
                             $is_new = false;
                         }
                     }
                 } else {
                     if ($buyer = \Prefs::check_email($in->email)) {
                         $buyer_id = $buyer['id'];
                         $is_new = false;
                     } else {
                         if ($buyer = \Prefs::check_phone($in->phone, $in->mobile1, $in->mobile2)) {
                             $buyer_id = $buyer['id'];
                             $is_new = false;
                         }
                     }
                 }
             }
             if (isset($in->merchant_trans_id) && $in->merchant_trans_id != "") {
                 $transaction_id = $in->merchant_trans_id;
             }
             if ($is_new) {
                 $random_string = str_random(5);
                 $buyer_username = substr(strtolower(str_replace(' ', '', $in->buyer_name)), 0, 6) . $random_string;
                 $dataset['username'] = $buyer_username;
                 $dataset['email'] = $in->email;
                 $dataset['phone'] = $in->phone;
                 $dataset['mobile1'] = $in->mobile1;
                 $dataset['mobile2'] = $in->mobile2;
                 $dataset['fullname'] = $in->buyer_name;
                 $password = str_random(8);
                 $dataset['password'] = $password;
                 $dataset['created'] = date('Y-m-d H:i:s', time());
                 /*
                 $dataset['province'] =
                 $dataset['mobile']
                 */
                 $dataset['street'] = $in->shipping_address;
                 $dataset['district'] = $in->buyerdeliveryzone;
                 $dataset['city'] = $in->buyerdeliverycity;
                 $dataset['country'] = 'Indonesia';
                 $dataset['zip'] = isset($in->zip) ? $in->zip : '';
                 //$buyer_id = $this->register_buyer($dataset);
                 $is_new = true;
             }
             $order['created'] = date('Y-m-d H:i:s', time());
             $order['ordertime'] = date('Y-m-d H:i:s', time());
             $order['application_id'] = $app->id;
             $order['application_key'] = $app->key;
             $order['buyer_id'] = $buyer_id;
             $order['merchant_id'] = $app->merchant_id;
             $order['merchant_trans_id'] = trim($transaction_id);
             $order['buyer_name'] = $in->buyer_name;
             $order['recipient_name'] = $in->recipient_name;
             $order['email'] = $in->email;
             $order['directions'] = $in->directions;
             //$order['dir_lat'] = $in->dir_lat;
             //$order['dir_lon'] = $in->dir_lon;
             $order['buyerdeliverytime'] = $in->buyerdeliverytime;
             $order['buyerdeliveryslot'] = $in->buyerdeliveryslot;
             $order['buyerdeliveryzone'] = $in->buyerdeliveryzone;
             $order['buyerdeliverycity'] = is_null($in->buyerdeliverycity) || $in->buyerdeliverycity == '' ? 'Jakarta' : $in->buyerdeliverycity;
             $order['currency'] = $in->currency;
             $order['total_price'] = isset($in->total_price) ? $in->total_price : 0;
             $order['total_discount'] = isset($in->total_discount) ? $in->total_discount : 0;
             $order['total_tax'] = isset($in->total_tax) ? $in->total_tax : 0;
             if (in_array(strtoupper(trim($in->delivery_type)), array('COD', 'CCOD', 'PS', 'DO', 'DELIVERY ONLY'))) {
                 $in->delivery_type = 'COD';
             }
             $order['delivery_type'] = $in->delivery_type;
             if ($in->delivery_type == 'DO' || $in->delivery_type == 'Delivery Only') {
                 $order['cod_cost'] = 0;
             } else {
                 $order['cod_cost'] = \Prefs::get_cod_tariff($order['total_price'], $app->id);
             }
             $order['box_count'] = isset($in->box_count) ? $in->box_count : 1;
             $order['pending_count'] = isset($in->pending_count) ? $in->pending_count : 0;
             $order['delivery_note'] = isset($in->delivery_note) ? $in->delivery_note : '';
             $order['shipping_address'] = $in->shipping_address;
             $order['shipping_zip'] = $in->shipping_zip;
             $order['phone'] = $in->phone;
             $order['mobile1'] = $in->mobile1;
             $order['mobile2'] = $in->mobile2;
             $order['status'] = $in->status;
             $order['width'] = $in->width;
             $order['height'] = $in->height;
             $order['length'] = $in->length;
             $order['weight'] = isset($in->weight) ? $in->weight : 0;
             $order['actual_weight'] = isset($in->actual_weight) ? $in->actual_weight : 0;
             $order['delivery_cost'] = $order['weight'];
             $order['cod_bearer'] = isset($in->cod_bearer) ? $in->cod_bearer : 'merchant';
             $order['delivery_bearer'] = isset($in->delivery_bearer) ? $in->delivery_bearer : 'merchant';
             $order['cod_method'] = isset($in->cod_method) ? $in->cod_method : 'cash';
             $order['ccod_method'] = isset($in->ccod_method) ? $in->ccod_method : 'full';
             $order['fulfillment_code'] = isset($in->fulfillment_code) ? $in->fulfillment_code : '';
             // check out who is bearing the cost
             if ($order['delivery_type'] == 'COD' || $order['delivery_type'] == 'CCOD') {
                 if ($order['delivery_bearer'] == 'merchant') {
                     $dcost = 0;
                 } else {
                     $dcost = $order['delivery_cost'];
                 }
                 if ($order['cod_bearer'] == 'merchant') {
                     $codcost = 0;
                 } else {
                     $codcost = $order['cod_cost'];
                 }
                 $order['chargeable_amount'] = $order['total_price'] + $dcost + $codcost;
             } else {
                 if ($order['delivery_bearer'] == 'merchant') {
                     $dcost = 0;
                 } else {
                     $dcost = $order['delivery_cost'];
                 }
                 $order['chargeable_amount'] = $dcost;
             }
             if (isset($in->show_shop)) {
                 $order['show_shop'] = $in->show_shop;
             }
             if (isset($in->show_merchant)) {
                 $order['show_merchant'] = $in->show_merchant;
             }
             $order['is_api'] = 1;
             $ship = new \Shipment();
             foreach ($order as $k => $v) {
                 $ship->{$k} = $v;
             }
             $ship->save();
             $sequence = $ship->id;
             if (isset($in->delivery_id)) {
                 if (is_null($in->delivery_id) || $in->delivery_id == '') {
                     $delivery_id = \Prefs::get_delivery_id($sequence, $app->merchant_id);
                 } else {
                     $delivery_id = \Prefs::get_delivery_id($sequence, $app->merchant_id, $in->delivery_id);
                 }
             } else {
                 $delivery_id = \Prefs::get_delivery_id($sequence, $app->merchant_id);
             }
             $ship->delivery_id = $delivery_id;
             //print_r($ship);
             $ship->save();
             //die();
             if (isset($in->box_count)) {
                 $box_count = $in->box_count;
             } else {
                 $box_count = 1;
             }
             \Prefs::save_box($delivery_id, trim($transaction_id), $order['fulfillment_code'], $box_count);
             $nedata['fullname'] = $in->buyer_name;
             $nedata['merchant_trx_id'] = trim($transaction_id);
             $nedata['delivery_id'] = $delivery_id;
             $nedata['merchantname'] = $app->application_name;
             $nedata['app'] = $app;
             $order['delivery_id'] = $delivery_id;
             $buyer_id = \Prefs::save_buyer($order);
             /*
             $this->db->where('id',$sequence)->update($this->config->item('incoming_delivery_table'),array('delivery_id'=>$delivery_id));
             */
             /*
                 $this->table_tpl = array(
                     'table_open' => '<table border="0" cellpadding="4" cellspacing="0" class="dataTable">'
                 );
                 $this->table->set_template($this->table_tpl);
             
             
                 $this->table->set_heading(
                     'No.',
                     'Description',
                     'Quantity',
                     'Total'
                     ); // Setting headings for the table
             */
             $d = 0;
             $gt = 0;
             if ($in->trx_detail) {
                 $seq = 0;
                 foreach ($in->trx_detail as $it) {
                     $item = new \Deliverydetail();
                     $item->ordertime = $order['ordertime'];
                     $item->delivery_id = $delivery_id;
                     $item->unit_sequence = $seq++;
                     $item->unit_description = $it->unit_description;
                     $item->unit_price = $it->unit_price;
                     $item->unit_quantity = $it->unit_quantity;
                     $item->unit_total = $it->unit_total;
                     $item->unit_discount = $it->unit_discount;
                     $item->save();
                     /*
                     $this->table->add_row(
                         (int)$item['unit_sequence'] + 1,
                         $item['unit_description'],
                         $item['unit_quantity'],
                         $item['unit_total']
                     );
                     
                     $u_total = str_replace(array(',','.'), '', $item['unit_total']);
                     $u_discount = str_replace(array(',','.'), '', $item['unit_discount']);
                     $gt += (int)$u_total;
                     $d += (int)$u_discount;
                     */
                 }
                 $total = isset($in->total_price) && $in->total_price > 0 ? $in->total_price : 0;
                 $total = str_replace(array(',', '.'), '', $total);
                 $total = (int) $total;
                 $gt = $total < $gt ? $gt : $total;
                 $disc = isset($in->total_discount) ? $in->total_discount : 0;
                 $tax = isset($in->total_tax) ? $in->total_tax : 0;
                 $cod = isset($in->cod_cost) ? $in->cod_cost : 'Paid by merchant';
                 $disc = str_replace(array(',', '.'), '', $disc);
                 $tax = str_replace(array(',', '.'), '', $tax);
                 $cod = str_replace(array(',', '.'), '', $cod);
                 $disc = (int) $disc;
                 $tax = (int) $tax;
                 $cod = (int) $cod;
                 $chg = $gt - $disc + $tax + $cod;
                 /*
                 $this->table->add_row(
                     '',
                     '',
                     'Total Price',
                     number_format($gt,2,',','.')
                 );
                 
                 $this->table->add_row(
                     '',
                     '',
                     'Total Discount',
                     number_format($disc,2,',','.')
                 );
                 
                 $this->table->add_row(
                     '',
                     '',
                     'Total Tax',
                     number_format($tax,2,',','.')
                 );
                 
                 
                 if($cod == 0){
                     $this->table->add_row(
                         '',
                         '',
                         'COD Charges',
                         'Paid by Merchant'
                     );
                 }else{
                     $this->table->add_row(
                         '',
                         '',
                         'COD Charges',
                         number_format($cod,2,',','.')
                     );
                 }
                 
                 
                 $this->table->add_row(
                     '',
                     '',
                     'Total Charges',
                     number_format($chg,2,',','.')
                 );
                 
                 $nedata['detail'] = $this->table;
                 
                 
                 $result = json_encode(array('status'=>'OK:ORDERPOSTED','timestamp'=>now(),'delivery_id'=>$delivery_id,'buyer_id'=>$buyer_id));
                 */
                 //return $ship->toArray();
             } else {
                 //$nedata['detail'] = false;
                 //$result = json_encode(array('status'=>'OK:ORDERPOSTEDNODETAIL','timestamp'=>now(),'delivery_id'=>$delivery_id));
                 //return $order;
             }
             return $ship->toArray();
             //print_r($app);
             /*
             
                             if($app->notify_on_new_order == 1){
                                 send_notification('New Delivery Order - Jayon Express COD Service',$in->email,$app->cc_to,$app->reply_to,'order_submit',$nedata,null);
                             }
             
                             if($is_new == true){
                                 $edata['fullname'] = $dataset['fullname'];
                                 $edata['username'] = $buyer_username;
                                 $edata['password'] = $password;
                                 if($app->notify_on_new_member == 1 && $in->email != 'noemail'){
                                     send_notification('New Member Registration - Jayon Express COD Service',$in->email,null,null,'new_member',$edata,null);
                                 }
             
                             }*/
         }
     }
     //$this->log_access($api_key, __METHOD__ ,$result,$args);
 }
 public function actionRequestOrder()
 {
     if (!isset($_POST['Shipment'])) {
         echo CJSON::encode($this->statusError('Must be in POST method'));
         Yii::app()->end();
     }
     $shipment = new Shipment('api-requestpickup');
     $shipment->attributes = $_POST['Shipment'];
     $shipment->created = time();
     $routing_code = IntraCityRouting::model()->findByAttributes(array('postcode' => $shipment->shipper_postal));
     if ($routing_code instanceof IntraCityRouting) {
         $shipment->origin_code = $routing_code->code;
     }
     $price = 0;
     $price_vendor = 0;
     $trans = Yii::app()->db->beginTransaction();
     try {
         if ($this->token instanceof Token) {
             $customer = Customer::model()->findByPk($this->token->customer_id);
             if (!$customer instanceof Customer) {
                 throw new ServiceControllerException('You have to login first');
             }
             if (!!$customer->accountnr) {
                 $shipment->awb = '70' . rand(10000000, 99999999);
                 while (!$shipment->validate()) {
                     $shipment->awb = '70' . rand(10000000, 99999999);
                 }
             }
             $shipment->customer_id = $this->token->customer_id;
         } else {
             $email = '';
             $shipment->setScenario('cekemail');
             if ($shipment->validate()) {
                 if ($shipment->payer == 'shipper' && $shipment->shipper_email) {
                     $email = Contact::model()->findByAttributes(array('email' => $shipment->shipper_email));
                 } elseif ($shipment->payer == 'consignee' && $shipment->receiver_email) {
                     $email = Contact::model()->findByAttributes(array('email' => $shipment->receiver_email));
                 }
             } else {
                 throw new ServiceControllerException($shipment->getErrors());
             }
             $shipment->setScenario('api-requestpickup');
             if (!$email instanceof Contact) {
                 $customer = new Customer();
                 if ($shipment->payer == 'shipper') {
                     $customer->name = $shipment->shipper_name;
                 } elseif ($shipment->payer == 'consignee') {
                     $customer->name = $shipment->receiver_name;
                 }
                 $customer->type = 'personal';
                 $customer->accountnr = 'WEB' . time();
                 if ($customer->save()) {
                     $contact = new Contact();
                     $contact->parent_id = $customer->id;
                     $contact->parent_model = 'Customer';
                     if ($shipment->payer == 'shipper') {
                         $contact->full_name = $shipment->shipper_name;
                         $contact->address = $shipment->shipper_address;
                         $contact->country = $shipment->shipper_country;
                         $contact->city = $shipment->shipper_city;
                         $contact->postal = $shipment->shipper_postal;
                         $contact->email = $shipment->shipper_email;
                     } elseif ($shipment->payer == 'consignee') {
                         $contact->full_name = $shipment->receiver_name;
                         $contact->address = $shipment->receiver_address;
                         $contact->country = $shipment->receiver_country;
                         $contact->city = $shipment->receiver_city;
                         $contact->postal = $shipment->receiver_postal;
                         $contact->email = $shipment->receiver_email;
                     }
                     if ($contact->save()) {
                         $shipment->customer_id = $customer->id;
                     } else {
                         throw new ServiceControllerException($contact->getErrors());
                     }
                 } else {
                     throw new ServiceControllerException($customer->getErrors());
                 }
             } else {
                 throw new ServiceControllerException('Your email is currently registered as a member, please login to create order');
             }
         }
         if ($shipment->validate()) {
             $customer_rate = CustomerDiscount::getCustomerDiscountRate($shipment->service_id, $shipment->customer_id);
             switch ($shipment->service_type) {
                 case 'City Courier':
                     $rate = RateCity::model()->findByAttributes(array('service_id' => $shipment->service_id));
                     if ($rate instanceof RateCity) {
                         if ($customer_rate['harga_invoice'] != 0) {
                             $price = $customer_rate['harga_invoice'] * RateCity::increment($shipment->package_weight, $rate->weight_inc);
                         } else {
                             $price = ($rate->price - $rate->price * ($customer_rate['discount'] / 100)) * RateCity::increment($shipment->package_weight, $rate->weight_inc);
                         }
                         $price_vendor = ($rate->price - $rate->price * ($customer_rate['vendor_discount'] / 100)) * RateCity::increment($shipment->package_weight, $rate->weight_inc);
                     } else {
                         $area = Area::getZoneID($shipment->receiver_postal);
                         if (!$area) {
                             throw new ServiceControllerException('No services available');
                         }
                         $price = RateDomestic::getRatePrice($shipment->service_id, 1, $area['district_id'], $area['zone_id'], $shipment->package_weight, $customer_rate['discount']);
                         $price_vendor = RateDomestic::getRatePrice($shipment->service_id, 1, $area['district_id'], $area['zone_id'], $shipment->package_weight, $customer_rate['vendor_discount']);
                     }
                     break;
                 case 'Domestic':
                     $area = Area::getZoneID($shipment->receiver_postal);
                     if (!$area) {
                         throw new ServiceControllerException('No services available');
                     }
                     $price = RateDomestic::getRatePrice($shipment->service_id, 1, $area['district_id'], $area['zone_id'], $shipment->package_weight, $customer_rate['discount']);
                     $price_vendor = RateDomestic::getRatePrice($shipment->service_id, 1, $area['district_id'], $area['zone_id'], $shipment->package_weight, $customer_rate['vendor_discount']);
                     break;
                 case 'International':
                     $zone = FALSE;
                     if ($shipment->service_code == 'IEX') {
                         $country = $shipment->receiver_country;
                     } else {
                         if ($shipment->service_code == 'IMX') {
                             $country = $shipment->shipper_country;
                         }
                     }
                     $zone = ZoneInternational::getZoneCountryData($country);
                     if (!!$zone) {
                         $price = RateInternational::getRatePrice($shipment->service_id, $shipment->package_weight, $shipment->type, $zone, $customer_rate['discount']);
                         $price_vendor = RateInternational::getRatePrice($shipment->service_id, $shipment->package_weight, $shipment->type, $zone, $customer_rate['vendor_discount']);
                     }
                     break;
                 case '':
                     continue;
             }
             $shipment->shipping_charges = $price;
             $shipment->vendor_charge = $price_vendor;
             if (!$shipment->save()) {
                 throw new ServiceControllerException($shipment->getErrors());
             }
             $sum_add_cost = ShipmentAdditionalCharge::initSurcharges($shipment);
             /**
              * temporary disabling additional cost
              */
             $sum_add_cost = 0;
             $shipment->charges = $shipment->shipping_charges + $sum_add_cost;
             $list_add_cost = $shipment->getAdditionalCharges();
             if (!$shipment->save()) {
                 throw new ServiceControllerException($shipment->getErrors());
             }
         } else {
             throw new ServiceControllerException($shipment->getErrors());
         }
         if (isset($_GET['confirm']) && $_GET['confirm'] == 1) {
             $trans->commit();
             $data = array('shipment_id' => $shipment->id, 'status' => $shipment->shipping_status, 'time' => date('Y-m-d H:i:s', $shipment->created), 'charges' => $shipment->charges, 'awb' => $shipment->awb);
         } elseif (isset($_GET['confirm']) && $_GET['confirm'] == 0 || !isset($_GET['confirm'])) {
             $data = array('confirm' => 0, 'additional_cost' => $list_add_cost, 'shipping_charges' => $shipment->shipping_charges, 'total' => $shipment->charges, 'shipper_name' => $shipment->shipper_name, 'shipper_address' => $shipment->shipper_address, 'shipper_city' => $shipment->shipper_city, 'shipper_postal' => $shipment->shipper_postal, 'shipper_country' => $shipment->shipper_country, 'receiver_name' => $shipment->receiver_name, 'receiver_address' => $shipment->receiver_address, 'receiver_city' => $shipment->receiver_city, 'receiver_postal' => $shipment->receiver_postal, 'receiver_country' => $shipment->receiver_country, 'goods_desc' => $shipment->goods_desc, 'shipment_value' => $shipment->package_value, 'weight' => $shipment->package_weight, 'pieces' => $shipment->pieces, 'pay_bay' => $shipment->pay_by, 'payer' => $shipment->payer, 'customer_id' => $customer->id);
             $trans->rollback();
         }
     } catch (ServiceControllerException $e) {
         $errors = $e->errors;
         $trans->rollback();
         echo CJSON::encode($this->statusError($errors));
         Yii::app()->end();
     } catch (CDbException $e) {
         $trans->rollback();
         echo CJSON::encode($this->statusError($e));
         Yii::app()->end();
     }
     echo CJSON::encode($this->statusSuccess($data));
     Yii::app()->end();
 }
        /**
         * insert shipment
         * @return Object
         * @throws ShopException
         */
        public function procShopToolInsertShipment(){
            $order_srl = Context::get('order_srl');
            $orderRepository = $this->model->getOrderRepository();
            $shipmentRepository = $this->model->getShipmentRepository();
            $order = $orderRepository->getOrderBySrl($order_srl);
            $args = Context::getRequestVars();
            $args->order_srl = $order_srl;
            $args->module_srl = $order->module_srl;
            $shipment = new Shipment($args);
            $shipment->order = $order;
            if(!isset($shipment->shipment_srl)) $insert = TRUE;
            try{
                if($insert) {
                    $productsEmptyStocks = $shipment->checkAndUpdateStocks();
                    $product_srls = array();
                    foreach($productsEmptyStocks as $product){
                        $products_srls[] = $product->product_srl;
                    }
                    $products_srls = implode(', ',$product_srls);
                }
                $shipment->save();
            }
            catch(Exception $e) {
                return new Object(-1, $e->getMessage());
            }
            if($shipment->shipment_srl){
                if(isset($order->invoice)) $order->order_status = Order::ORDER_STATUS_COMPLETED;
                else $order->order_status = Order::ORDER_STATUS_PROCESSING;
                try{
                    $order->save();
                }
                catch(Exception $e) {
                    return new Object(-1, $e->getMessage());
                }
                if($insert){
                    $this->setMessage("Shipment has been created. " . (isset($products_srls) ? "Stock empty for products: $products_srls":''));
                    $return_url = getNotEncodedUrl('', 'act','dispShopToolViewOrder','order_srl',$order_srl);
                    $this->setRedirectUrl($return_url);
                } else {
                    $this->setMessage("Shipment has been updated");
                    $return_url = getNotEncodedUrl('', 'act','dispShopToolManageShipments','order_srl',$order_srl);
                    $this->setRedirectUrl($return_url);
                }

            } else {
                throw new ShopException('Something whent wrong when adding shipment');
            }
        }
Beispiel #5
0
 public static function bulkOrder($rawdatas, $customer, $contact, $routing_code)
 {
     $failed = array();
     $success = array();
     $line_error = array();
     $counter = 0;
     $column = array();
     foreach ($rawdatas as $data) {
         $valid_area = true;
         if ($counter++ == 0) {
             continue;
         }
         $column = explode(',', $data);
         $shipment = new Shipment();
         if (count($column) == 21) {
             //account detail
             $shipment->setAttribute('customer_id', $customer->id);
             $shipment->setAttribute('origin_code', $routing_code);
             //shipper_detail
             $shipment->setAttribute('shipper_name', trim($column[2]));
             $shipment->setAttribute('shipper_company_name', trim($column[1]));
             $shipment->setAttribute('shipper_address', trim($column[3]));
             $shipment->setAttribute('shipper_city', trim($column[5]));
             $shipment->setAttribute('shipper_country', trim($column[6]));
             $shipment->setAttribute('shipper_postal', trim($column[7]));
             $shipment->setAttribute('shipper_phone', trim($column[4]));
             //receiver_detail
             $shipment->setAttribute('receiver_name', trim($column[9]));
             $shipment->setAttribute('receiver_company_name', trim($column[8]));
             $shipment->setAttribute('receiver_address', trim($column[10]));
             $shipment->setAttribute('receiver_city', trim($column[12]));
             $shipment->setAttribute('receiver_country', trim($column[13]));
             $shipment->setAttribute('receiver_postal', trim($column[14]));
             $shipment->setAttribute('receiver_phone', trim($column[11]));
             //shipment_detail
             $shipment->setAttribute('type', 'document');
             $shipment->setAttribute('payer', 'shipper');
             $shipment->setAttribute('payby', 'account');
             $shipment->setAttribute('pieces', trim($column[15]));
             $shipment->setAttribute('package_weight', trim($column[16]));
             $shipment->setAttribute('package_value', trim($column[17]));
             $shipment->setAttribute('service_type', trim($column[18]));
             $shipment->setAttribute('service_id', trim($column[19]));
             $shipment->setAttribute('service_code', trim($column[20]));
             $shipment->setAttribute('destination_code', trim($column[0]));
             $customer_rate = CustomerDiscount::getCustomerDiscountRate($shipment->service_id, $shipment->customer_id);
             if (!!$customer_rate) {
                 if ($customer_rate['discount'] == null) {
                     $customer_rate['discount'] = 0;
                 }
                 switch ($shipment->service_type) {
                     case 'City Courier':
                         $rate = RateCity::model()->findByAttributes(array('service_id' => $shipment->service_id));
                         if ($rate instanceof RateCity) {
                             if ($customer_rate['harga_invoice'] != 0) {
                                 $price = $customer_rate['harga_invoice'] * RateCity::increment($shipment->package_weight, $rate->weight_inc);
                             } else {
                                 $price = ($rate->price - $rate->price * ($customer_rate['discount'] / 100)) * RateCity::increment($shipment->package_weight, $rate->weight_inc);
                             }
                             $price_vendor = ($rate->price - $rate->price * ($customer_rate['vendor_discount'] / 100)) * RateCity::increment($shipment->package_weight, $rate->weight_inc);
                         } else {
                             $area = Area::getZoneID($shipment->receiver_postal);
                             if (!$area) {
                                 $price = 0;
                                 $price_vendor = 0;
                                 $valid_area = false;
                             } else {
                                 $price = RateDomestic::getRatePrice($shipment->service_id, 1, $area['district_id'], $area['zone_id'], $shipment->package_weight, $customer_rate['discount']);
                                 $price_vendor = RateDomestic::getRatePrice($shipment->service_id, 1, $area['district_id'], $area['zone_id'], $shipment->package_weight, $customer_rate['vendor_discount']);
                             }
                         }
                         break;
                     case 'Domestic':
                         $area = Area::getZoneID($shipment->receiver_postal);
                         if (!$area) {
                             $price = 0;
                             $price_vendor = 0;
                             $valid_area = false;
                         } else {
                             $price = RateDomestic::getRatePrice($shipment->service_id, 1, $area['district_id'], $area['zone_id'], $shipment->package_weight, $customer_rate['discount']);
                             $price_vendor = RateDomestic::getRatePrice($shipment->service_id, 1, $area['district_id'], $area['zone_id'], $shipment->package_weight, $customer_rate['vendor_discount']);
                         }
                         break;
                     case 'International':
                         $zone = FALSE;
                         if ($shipment->service_code == 'IEX') {
                             $country = $shipment->receiver_country;
                         } else {
                             if ($shipment->service_code == 'IMX') {
                                 $country = $shipment->shipper_country;
                             }
                         }
                         $zone = ZoneInternational::getZoneCountryData($country);
                         if (!!$zone) {
                             $price = RateInternational::getRatePrice($shipment->service_id, $shipment->package_weight, $shipment->type, $zone, $customer_rate['discount']);
                             $price_vendor = RateInternational::getRatePrice($shipment->service_id, $shipment->package_weight, $shipment->type, $zone, $customer_rate['vendor_discount']);
                         } else {
                             $price = 0;
                             $price_vendor = 0;
                             $valid_area = false;
                         }
                         break;
                     case '':
                         continue;
                 }
                 $shipment->shipping_charges = $price;
                 $shipment->vendor_charge = $price_vendor;
                 $shipment->awb = '90' . rand(10000000, 99999999);
                 while (!$shipment->validate(array('awb'))) {
                     $shipment->awb = '90' . rand(10000000, 99999999);
                 }
                 if ($shipment->save()) {
                     $additional_costs = ShipmentAdditionalCharge::initSurcharges($shipment);
                     $shipment->charges = $shipment->shipping_charges + $additional_costs;
                     $shipment->save();
                     array_push($success, $counter);
                 } else {
                     CVarDumper::dump($shipment->attributes, 10, true);
                     CVarDumper::dump($shipment->getErrors(), 10, true);
                     array_push($failed, array('counter' => $counter, 'message' => $shipment->getErrors()));
                 }
             } else {
                 array_push($failed, array('counter' => $counter, 'message' => array('this service is not available')));
             }
         } else {
             array_push($failed, array('counter' => $counter, 'message' => array('wrong delimiter format')));
         }
     }
     return array('success' => $success, 'failed' => $failed);
 }
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Customer'])) {
         $model->attributes = $_POST['Customer'];
         $model->save();
         $this->redirect("#info");
         //				$this->redirect(array('view','id'=>$model->bilkey));
     }
     if (isset($_GET['Shipment'])) {
         $shipment_model->attributes = $_GET['Shipment'];
     }
     $service_details = Customer::model()->getCustomerServiceDetails($id);
     $shipment_details = Customer::model()->getShipmentsByCustomerBilkey($id);
     $customer = Customer::model()->findByPk($id);
     $commande = Commande::model()->findAllByAttributes(array('bilkey' => $id));
     $shipment_model = new Shipment('search');
     $shipment_model->unsetAttributes();
     // clear any default values
     $shipment_model->bilkey = $id;
     // DEBUGGING
     //		print "New total: " + $total_balance . '<br />';
     //		print "Old total: " + $customer->bilbalance;
     //		die;
     // TODO: We really should link the billing activity with the comkey...
     if (isset($_POST['Shipment'])) {
         // Check if it's an update
         if (isset($_POST['update'])) {
             $shipment = Shipment::model()->findByPk($_POST['update']);
             $shipment->attributes = $_POST['Shipment'];
             // We have to cast these manually.  For some reason this fails on the production server...
             $shipment->shipdebit = floatval($shipment->shipdebit);
             $shipment->shipcredit = floatval($shipment->shipcredit);
             // If the user leaves these fields blank, let's assume
             //  they meant to input a 0.
             if (empty($shipment->shipdebit) || $shipment->shipdebit == null) {
                 $shipment->shipdebit = 0;
             }
             if (empty($shipment->shipcredit) || $shipment->shipcredit == null) {
                 $shipment->shipcredit = 0;
             }
             // TODO: We should prolly check this
             $shipment->save();
         } else {
             $shipment = new Shipment();
             $shipment->attributes = $_POST['Shipment'];
             // We have to cast these manually.  For some reason this fails on the production server...
             $shipment->shipdebit = floatval($shipment->shipdebit);
             $shipment->shipcredit = floatval($shipment->shipcredit);
             // If the user leaves these fields blank, let's assume
             //  they meant to input a 0.
             if (empty($shipment->shipdebit) || $shipment->shipdebit == null) {
                 $shipment->shipdebit = 0;
             }
             if (empty($shipment->shipcredit) || $shipment->shipcredit == null) {
                 $shipment->shipcredit = 0;
             }
             if ($shipment->validate()) {
                 $shipment->comkey = $commande[0]->comkey;
                 $shipment->bilkey = $customer->bilkey;
                 $shipment->save();
             }
         }
         //            $this->redirect("customer/update/id/" + $customer->bilkey);
         $this->redirect("#billing");
     }
     $conn = Yii::app()->db;
     //        $total_balance = 0;
     // Update individual account balances
     foreach ($commande as $c) {
         $command = $conn->createCommand("SELECT SUM(shipcredit) - SUM(shipdebit) as balance FROM shipment WHERE comkey='" . $c->comkey . "'  GROUP BY comkey");
         $results = $command->queryRow();
         $balance = $results['balance'];
         //            $total_balance += $balance;
         $c->dest_bilbalance = $balance;
         $c->save();
     }
     // Fix for Support Request #430
     $command = $conn->createCommand("SELECT SUM(shipcredit) - SUM(shipdebit) as balance FROM shipment WHERE bilkey='" . $customer->bilkey . "'");
     $results = $command->queryRow();
     $total_balance = $results['balance'];
     // Update overall account balance
     $customer->bilbalance = $total_balance;
     $customer->save();
     $this->render('//shared/user-info', array('admin' => 1, 'commande' => $commande, 'customer' => $customer, 'customer_model' => $customer, 'service_details' => $service_details, 'shipment_details' => $shipment_details, 'shipment_model' => $shipment_model));
 }
 /**
  * Set shipment status to completed
  * 
  * @param Shipment $shipment
  * @param string $recepient_name
  */
 private function setJneStatusOrder(Shipment $shipment, $status, $recepient_name = '')
 {
     $event = new ShipmentEvent();
     $shipment->setScenario('event');
     $event->created = time();
     $event->event_time = $event->created;
     $event->shipment_id = $shipment->id;
     $event->user_id = User::USER_SYSTEM;
     switch (strtoupper($status)) {
         case 'DELIVERED':
             $event->status = ShipmentStatus::POD;
             $shipment->shipping_status = ShipmentStatus::POD;
             $shipment->event_time = $event->event_time;
             $shipment->recipient_name = $recepient_name;
             break;
         case 'MANIFESTED':
             $event->status = ShipmentStatus::MDE;
             $shipment->shipping_status = ShipmentStatus::MDE;
             $shipment->event_time = $event->event_time;
             break;
         case 'RECEIVED ON DESTINATION':
             $event->status = ShipmentStatus::ARR;
             $shipment->shipping_status = ShipmentStatus::ARR;
             $shipment->event_time = $event->event_time;
             break;
         case 'ON PROCESS':
             $event->status = ShipmentStatus::OTW;
             $shipment->shipping_status = ShipmentStatus::OTW;
             $shipment->event_time = $event->event_time;
             break;
     }
     try {
         $trans = Yii::app()->db->beginTransaction();
         if ($event->save()) {
             if ($shipment->save()) {
                 $trans->commit();
                 $this->printf('Shipment set to %s', $status);
                 return true;
             } else {
                 print_r($shipment->getErrors());
                 throw new CException();
             }
         } else {
             print_r($event->getErrors());
             throw new CException();
         }
     } catch (CException $e) {
         $trans->rollback();
         throw $e;
     }
 }