/** * Get lat lon by address * @author Oleg D. */ function getLatLon($address, $updateAddress = 0) { $addressString = $city = $state = $country = ''; if (!empty($address['address'])) { $addressString = $address['address'] . ' ' . $address['address2'] . ' ' . $address['address3']; if (!empty($address['city'])) { $city = $address['city']; } if (!empty($address['Country']['name'])) { $country = $address['Country']['name']; } elseif (!empty($address['country_name'])) { $country = $address['country_name']; } if (!empty($address['Provincestate']['name'])) { $state = $address['Provincestate']['name']; } elseif (!empty($address['state_name'])) { $state = $address['state_name']; } App::import('Vendor', 'GoogleMapAPI', array('file' => 'class.GoogleMapAPI.php')); $map = new GoogleMapAPI(); $map->setAPIKey(GOOGLE_MAP_KEY); $latLon = $map->getCoordsByAddress(trim($addressString), $city, $state, $country); if ($updateAddress && !empty($address['id']) && !empty($latLon['lat']) && !empty($latLon['lon'])) { $Address = new Address(); $Address->save(array('id' => $address['id'], 'latitude' => $latLon['lat'], 'longitude' => $latLon['lon'])); } return $latLon; } else { return false; } }
function save($id = FALSE) { if ($_POST) { $about = new Address($id); // if($_FILES['image']['name']) // { // if($about->id){ // $about->delete_file($about->id,'uploads/about_us/','image'); // } // $_POST['image'] = $about->upload($_FILES['image'],'uploads/about_us/',260,195); // } // if($_FILES['imagemap']['name']) // { // if($about->id){ // $about->delete_file($about->id,'uploads/about_us/','imagemap'); // } // $_POST['imagemap'] = $about->upload($_FILES['imagemap'],'uploads/about_us/'); // } $_POST['name'] = lang_encode($_POST['name']); $_POST['address'] = lang_encode($_POST['address']); $_POST['tel'] = lang_encode($_POST['tel']); $_POST['facebook'] = lang_encode($_POST['facebook']); $_POST['twitter'] = lang_encode($_POST['twitter']); $_POST['googleplus'] = lang_encode($_POST['googleplus']); $_POST['open'] = lang_encode($_POST['open']); $_POST['open2'] = lang_encode($_POST['open2']); //$_POST['service_time'] = lang_encode($_POST['service_time']); $_POST['detail'] = lang_encode($_POST['detail']); // $_POST['user_id'] = $this->session->userdata('id'); $about->from_array($_POST); $about->save(); set_notify('success', lang('save_data_complete')); } redirect('addresses/admin/addresses'); }
public function actionCreate() { if ($model = Shop::getCustomer()) { $address = $model->address; } else { $model = new Customer(); } if (isset($_POST['Customer'])) { $model->attributes = $_POST['Customer']; if (isset($_POST['Address'])) { $address = new Address(); $address->attributes = $_POST['Address']; if ($address->save()) { $model->address_id = $address->id; } } if (!Yii::app()->user->isGuest) { $model->user_id = Yii::app()->user->id; } if ($model->save()) { Yii::app()->user->setState('customer_id', $model->customer_id); $this->redirect(array('//shop/order/create', 'customer' => $model->customer_id)); } } $this->render('create', array('customer' => $model, 'address' => isset($address) ? $address : new Address())); }
public function up() { $this->addColumn($this->tableName, $this->columnName, 'int'); /** @var $data Office[] */ $data = Office::model()->findAll(); $migratedAddresses = []; foreach ($data as $office) { $fullAddress = implode(' ', [$office->address1, $office->address2, $office->address3, $office->address4]); if (isset($migratedAddresses[$fullAddress])) { $office->addressId = $migratedAddresses[$fullAddress]->id; $office->save(false); continue; } $parts = explode(' ', $office->address1); $buildingNumber = array_shift($parts); $line2 = implode(' ', $parts); $address = new Address(); $address->line1 = $buildingNumber; $address->line2 = $line2; $address->line5 = $office->address3; $address->postcode = $office->postcode; $address->save(); $migratedAddresses[$fullAddress] = $address; $office->addressId = $migratedAddresses[$fullAddress]->id; $office->save(false); continue; } }
public function actionCreate() { // if some data has been entered before or the user is already logged in, // take the already existing data and prefill the input form if ($model = Shop::getCustomer()) { $address = $model->address; } else { $model = new Customer(); } if (isset($_POST['Customer'])) { $model->attributes = $_POST['Customer']; if (isset($_POST['Address'])) { $address = new Address(); $address->attributes = $_POST['Address']; if ($address->save()) { $model->address_id = $address->id; } } if (!Yii::app()->user->isGuest) { $model->user_id = Yii::app()->user->id; } $model->validate(); if (Shop::module()->useWithYum && isset($_POST['register']) && ($_POST['register'] = true)) { if (isset($_POST['Customer']['password']) && isset($_POST['Customer']['passwordRepeat'])) { if ($_POST['Customer']['password'] != $_POST['Customer']['passwordRepeat']) { $model->addError('password', Shop::t('Passwords do not match')); } else { if ($_POST['Customer']['password'] == '') { $model->addError('password', Shop::t('Password is empty')); } else { $user = new YumUser(); $profile = new YumProfile(); $profile->attributes = $_POST['Customer']; $profile->attributes = $_POST['Address']; if ($user->register(strtr($model->email, array('@' => '_', '.' => '_')), $_POST['Customer']['password'], $profile)) { $user->status = YumUser::STATUS_ACTIVE; $user->save(false, array('status')); $model->user_id = $user->id; Shop::setFlash(Shop::t('Successfully registered user')); } else { $model->addErrors($user->getErrors()); $model->addErrors($profile->getErrors()); Shop::setFlash(Shop::t('Error while registering user')); } } } } } if (!$model->hasErrors()) { if ($model->save()) { Yii::app()->user->setState('customer_id', $model->customer_id); $this->redirect(array('//shop/order/create', 'customer' => $model->customer_id)); } } } $this->render('create', array('customer' => $model, 'address' => isset($address) ? $address : new Address())); }
public function actionAdd($id = 0) { if (!empty($id)) { $Insurance = Insurance::model()->findByPk($id); if (!Yii::app()->user->checkAccess('admin') && ((Yii::app()->getUser()->getProfile()->modules->head != UserModules::DIRECTOR_COMPANY || Yii::app()->user->getProfile()->company_id != $Insurance->user->company_id) && (Yii::app()->getUser()->getProfile()->modules->insurance != '1' || $Insurance->user_id != Yii::app()->user->id) || Yii::app()->getUser()->getProfile()->company->active == '0')) { throw new CHttpException(403); } $Address = $Insurance->address; $ContentManager = null; } else { if (Yii::app()->user->getProfile()->content_manager == '0') { if (!Yii::app()->user->checkAccess('admin') && (Yii::app()->getUser()->getProfile()->modules->head != UserModules::DIRECTOR_COMPANY && Yii::app()->getUser()->getProfile()->modules->insurance != '1' || Yii::app()->getUser()->getProfile()->company->active == '0')) { throw new CHttpException(403); } elseif (!Yii::app()->getUser()->getProfile()->company->validate) { $this->redirect('/complete'); } $ContentManager = null; } else { $ContentManager = new ContentManager(); } $Insurance = new Insurance(); $Address = new Address(); $Address->setscenario('insurance'); } //if(isset($_POST['save'])) { if (!empty($_POST)) { if (!empty($Insurance->address)) { Address::model()->deleteByPk($Insurance->address->address_id); } if (Yii::app()->user->getProfile()->content_manager == '1' && $id == 0) { $ContentManager->setAttributes($_POST['ContentManager'], false); $contentValid = $ContentManager->validate(); } else { $contentValid = true; } $Insurance->setAttributes($_POST['Insurance'], false); $Address->setAttributes($_POST['Address'], false); $valid = $Address->validate(); $valid = $Insurance->validate() && $valid && $contentValid; if ($valid) { if (Yii::app()->user->getProfile()->content_manager == '1' && $id == 0) { $Insurance->user_id = User::createFakeUser($ContentManager); $Insurance->contact_id = $Insurance->user_id; } $Address->save(); $Insurance->address_id = $Address->address_id; $Insurance->save(); $Insurance->autosearch(); // $this->redirect('/insurance'); $this->render('insuranceaddsuccess', ['Insurance' => $Insurance, 'contacts' => User::getContact()]); exit; } } $this->render('add', ['Insurance' => $Insurance, 'Address' => $Address, 'contacts' => User::getContact(), 'ContentManager' => $ContentManager]); }
public function postCreateAddress() { $address = new Address(); $address->user_id = Auth::user()->id; $address->line_1 = Input::get('line1'); $address->line_2 = Input::get('line2'); $address->city = Input::get('city'); $address->postcode = Input::get('postcode'); $address->country = Input::get('country'); $address->save(); Session::flash('alert', 'Your address has been created.'); return Redirect::to(route('my.addresses')); }
public function run() { DB::statement("TRUNCATE TABLE addresses"); $cityId = City::select('id')->where('city', 'Da Nang')->first()->id; $address = array('306 - đường 2/9, Hai Chau', '225 Nguyễn Chí Thanh, Hai Chau', '123 Nguyen Van Linh, Hai Chau', '328 Hoang Dieu, Hai Chau', '423 Nguyen Huu Tho, Hai Chau'); foreach ($address as $add) { $address = new Address(); $address->city_id = $cityId; $address->address = $add; $address->created_at = new DateTime(); $address->updated_at = new DateTime(); $address->save(); } }
/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $user = Auth::user(); $address = new Address(); $address->user_id = $user->id; $address->name = $request->name; $address->street = $request->street; $address->city = $request->city; $address->state = $request->state; $address->zip = $request->zip; $address->save(); $request->session()->flash('status', 'Address information was successfully saved.'); return Redirect::action('AddressController@index'); }
public function actionCreate() { $model = new Address(); if (isset($_POST['Address'])) { $model->setAttributes($_POST['Address']); if ($model->save()) { if (Yii::app()->getRequest()->getIsAjaxRequest()) { Yii::app()->end(); } else { $this->redirect(array('view', 'id' => $model->address_id)); } } } $this->render('create', array('model' => $model)); }
/** * @param ShopgateCart $cart * @return array */ public function checkCart(ShopgateCart $cart) { $this->_createCustomer($cart); if ($cart->getDeliveryAddress()) { if (!$cart->getDeliveryAddress()->getPhone()) { $cart->getDeliveryAddress()->setPhone($cart->getPhone()); } $this->_deliveryAddress = $this->_createAddress($cart->getDeliveryAddress()); $this->_deliveryAddress->id_customer = $this->getPlugin()->getContext()->customer->id; $this->_deliveryAddress->save(); $this->getPlugin()->getContext()->cart->id_address_delivery = $this->_deliveryAddress->id; $this->getPlugin()->getContext()->cart->save(); } if ($cart->getInvoiceAddress()) { if (!$cart->getInvoiceAddress()->getPhone()) { $cart->getInvoiceAddress()->setPhone($cart->getPhone()); } $this->_invoiceAddress = $this->_createAddress($cart->getInvoiceAddress()); $this->_deliveryAddress->id_customer = $this->getPlugin()->getContext()->customer->id; $this->_invoiceAddress->save(); $this->getPlugin()->getContext()->cart->id_address_invoice = $this->_invoiceAddress->id; $this->getPlugin()->getContext()->cart->save(); } /** * add selected carrier is given */ if ($cart->getShippingType() == ShopgateShipping::DEFAULT_PLUGIN_API_KEY) { if (is_array(unserialize($cart->getShippingInfos()->getInternalShippingInfo()))) { $carrierInfo = unserialize($cart->getShippingInfos()->getInternalShippingInfo()); $carrierId = isset($carrierInfo['carrierId']) ? $carrierInfo['carrierId'] : false; if ($carrierId) { $this->getPlugin()->getContext()->cart->id_carrier = (int) $carrierId; } } } /** * don't change the direction */ $result = array('items' => $this->_addItems($cart), 'external_coupons' => $this->_addCoupons($cart), 'currency' => $this->_getCurrency(), 'customer' => $this->_getCustomerGroups($cart), 'shipping_methods' => $this->_getCarriers(), 'payment_methods' => array()); return $result; }
/** * Adds new Address Record to database * * @return Redirect successfully redirects to home page */ public function doCreate() { if (Auth::check()) { $address = Input::get('address'); $address = Str::slug($address, '+'); //Sends address through Google Maps Geocoding API, which converts it to Lat and Lng Values $response = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&key=AIzaSyBoaSu9IZTRrCkY1tTnMibgHg-uwB8aduk'); $response = json_decode($response, true); $results = $response['results']; $address = new Address(); $address->address = $results[0]['formatted_address']; $address->lng = $results[0]['geometry']['location']['lng']; $address->lat = $results[0]['geometry']['location']['lat']; $address->depth = Input::get('depth'); $address->flow_rate = Input::get('flow_rate'); $address->year_dug = Input::get('year_dug'); $address->user_id = Auth::user()->id; $address->save(); return Redirect::action('HomeController@index'); } }
public function register() { if ($this->validate()) { $address = new Address(); $lines = explode("\n", $this->address); $postcode = ''; if (count($lines) > 1) { $postcode = array_pop($lines); } for ($i = 0; $i < count($lines) && $i < 5; $i++) { $t = 'line' . ($i + 1); $address->{$t} = $lines[$i]; } $address->postcode = strtoupper($postcode); $address->save(); $client = new Client(); $client->cli_fname = $this->name; $client->cli_sname = $this->surname; $client->cli_email = $this->email; $client->cli_branch = $this->branch; $client->cli_neg = 0; $client->cli_status = 'Active'; $client->cli_salemin = $this->minPrice; $client->cli_salemax = $this->maxPrice; $client->cli_salebed = $this->bedrooms; $client->cli_sales = 'Yes'; $client->cli_saleemail = 'Yes'; $client->cli_salestatus = $this->currentPosition; $client->addressID = $address->id; if ($client->save(false)) { $telephone = new Telephone(); $telephone->tel_type = 'Other'; $telephone->tel_number = $this->telephone; $telephone->tel_cli = $client->cli_id; $telephone->tel_ord = 1; $telephone->save(); } return true; } }
/** * process a search on postcode table store it to address entity * at the end return it for the api call * * @param $address_object * * @return string * @throws PrestaShopException */ public function extractPostCodeForShippingRequest(Address $address_object) { $id_state = $address_object->id_state; $country_name = pSQL($address_object->country); $region_name = State::getNameById($id_state); $address = array('country' => $country_name, 'region' => $region_name, 'city' => $address_object->city, 'address' => $address_object->address1 . ($address_object->address2 ? ' ' . $address_object->address2 : ''), 'postcode' => $address_object->postcode); if ($this->isEnabledAutocompleteForPostcode($country_name)) { $dpd_postcode_address = new DpdGroupDpdPostcodeAddress(); $dpd_postcode_address->loadDpdAddressByAddressId($address_object->id); $current_hash = $this->generateAddressHash($address); if ($dpd_postcode_address->id_address && $current_hash == $dpd_postcode_address->hash) { return $dpd_postcode_address->auto_postcode; } if (!$dpd_postcode_address->id_address || $current_hash != $dpd_postcode_address->hash) { $postcode_relevance = new stdClass(); $post_code = $this->search($address, $postcode_relevance); $dpd_postcode_address->auto_postcode = $post_code; $dpd_postcode_address->id_address = $address_object->id; $dpd_postcode_address->hash = $current_hash; if ($this->isValid($post_code, $postcode_relevance)) { $dpd_postcode_address->relevance = 1; $address_object->postcode = $post_code; $address_object->save(); } else { $dpd_postcode_address->relevance = 0; } if (!empty($dpd_postcode_address->dpd_postcode_id)) { $dpd_postcode_address->id = $dpd_postcode_address->dpd_postcode_id; } $dpd_postcode_address->save(); } else { return $dpd_postcode_address->auto_postcode; } } else { $post_code = $address_object->postcode; } return $post_code; }
public function actionCreate($id) { $model = new Address(); //$this->performAjaxValidation($model); $model->comp_id = $id; if (isset($_POST['Address'])) { $model->attributes = $_POST['Address']; if ($model->save()) { if (Yii::app()->request->isAjaxRequest) { echo CJSON::encode(array('status' => 1)); exit; } else { $this->redirect(array('/company/view', 'id' => $id)); } } } if (Yii::app()->request->isAjaxRequest) { Yii::app()->clientScript->scriptMap['jquery.js'] = false; Yii::app()->clientScript->scriptMap['jquery.min.js'] = false; echo CJSON::encode(array('status' => 0, 'div' => $this->renderPartial('/address/_form', array('model' => $model), true))); exit; } }
/** * Store a newly created resource in storage. * * @return Response */ public function store(Customer $customer) { $input = array_except(Input::all(), array('_token')); $input['customer_id'] = $customer->id; // Use postal code-to-locality lookup to find city/state to standardize... if (isset($input['postal_code'])) { $location_data = array(); try { $location_data = Utility::getLocalityFromPostalCode($input['postal_code']); } catch (\Exception $ex) { if ($ex->getCode() != 100) { // If we get an except OTHER THAN no data found, then pass it up. throw $ex; } } if ($location_data) { $input['postal_code'] = $location_data['post code']; $input['city'] = $location_data['places'][0]['place name']; $input['state'] = $location_data['places'][0]['state abbreviation']; } } $address = new Address($input); if ($address->save()) { //return Redirect::route('customers.show', $customer)->with('message', 'Customer created.'); //return Redirect::route('profile', array($customer->id))->with('message', 'Address created.'); if (Session::has('checkOutInProgress') && Session::get('checkOutInProgress') == TRUE) { return Redirect::route('checkout'); } elseif (Auth::check() && Auth::user()->admin_ind) { return Redirect::route('profile', array('id' => $customer->id)); } else { return Redirect::route('products')->with('message', 'Click on "Check Out" button when you are ready to pay.'); } } else { //return Redirect::route('customers.create')->withInput()->withErrors( $customer->errors() ); return Redirect::route('customers.addresses.create', $customer->id)->withInput()->withErrors($address->errors()); } }
/** * When the customer is back from PayPal after filling his/her credit card info or credentials, this function is preparing the order * PayPal is providing us with the customer info (E-mail address, billing address) and we are trying to find a matching customer in the Shop database. * If no customer is found, we create a new one and we simulate a logged customer session. * Eventually it will redirect the customer to the "Shipping" step/page of the order process */ private function _expressCheckout() { /* We need to double-check that the token provided by PayPal is the one expected */ $result = $this->paypal_usa->postToPayPal('GetExpressCheckoutDetails', '&TOKEN=' . urlencode(Tools::getValue('token'))); if ((strtoupper($result['ACK']) == 'SUCCESS' || strtoupper($result['ACK']) == 'SUCCESSWITHWARNING') && $result['TOKEN'] == Tools::getValue('token') && $result['PAYERID'] == Tools::getValue('PayerID')) { /* Checks if a customer already exists for this e-mail address */ if (Validate::isEmail($result['EMAIL'])) { $customer = new Customer(); $customer->getByEmail($result['EMAIL']); } /* If the customer does not exist yet, create a new one */ if (!Validate::isLoadedObject($customer)) { $customer = new Customer(); $customer->email = $result['EMAIL']; $customer->firstname = $result['FIRSTNAME']; $customer->lastname = $result['LASTNAME']; $customer->passwd = Tools::encrypt(Tools::passwdGen()); $customer->add(); } /* Look for an existing PayPal address for this customer */ $addresses = $customer->getAddresses((int) Configuration::get('PS_LANG_DEFAULT')); foreach ($addresses as $address) { if ($address['alias'] == 'PayPal') { $id_address = (int) $address['id_address']; break; } } /* Create or update a PayPal address for this customer */ $address = new Address(isset($id_address) ? (int) $id_address : 0); $address->id_customer = (int) $customer->id; $address->id_country = (int) Country::getByIso($result['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE']); $address->id_state = (int) State::getIdByIso($result['PAYMENTREQUEST_0_SHIPTOSTATE'], (int) $address->id_country); $address->alias = 'PayPal'; $address->lastname = substr($result['PAYMENTREQUEST_0_SHIPTONAME'], 0, strpos($result['PAYMENTREQUEST_0_SHIPTONAME'], ' ')); $address->firstname = substr($result['PAYMENTREQUEST_0_SHIPTONAME'], strpos($result['PAYMENTREQUEST_0_SHIPTONAME'], ' '), strlen($result['PAYMENTREQUEST_0_SHIPTONAME']) - strlen($address->lastname)); $address->address1 = $result['PAYMENTREQUEST_0_SHIPTOSTREET']; if ($result['PAYMENTREQUEST_0_SHIPTOSTREET2'] != '') { $address->address2 = $result['PAYMENTREQUEST_0_SHIPTOSTREET2']; } $address->city = $result['PAYMENTREQUEST_0_SHIPTOCITY']; $address->postcode = $result['PAYMENTREQUEST_0_SHIPTOZIP']; $address->save(); /* Update the cart billing and delivery addresses */ $this->context->cart->id_address_delivery = (int) $address->id; $this->context->cart->id_address_invoice = (int) $address->id; $this->context->cart->update(); /* Update the customer cookie to simulate a logged-in session */ $this->context->cookie->id_customer = (int) $customer->id; $this->context->cookie->customer_lastname = $customer->lastname; $this->context->cookie->customer_firstname = $customer->firstname; $this->context->cookie->passwd = $customer->passwd; $this->context->cookie->email = $customer->email; $this->context->cookie->is_guest = $customer->isGuest(); $this->context->cookie->logged = 1; /* Save the Payer ID and Checkout token for later use (during the payment step/page) */ $this->context->cookie->paypal_express_checkout_token = $result['TOKEN']; $this->context->cookie->paypal_express_checkout_payer_id = $result['PAYERID']; if (_PS_VERSION_ < '1.5') { Module::hookExec('authentication'); } else { Hook::exec('authentication'); } /* Redirect the use to the "Shipping" step/page of the order process */ Tools::redirectLink($this->context->link->getPageLink('order.php', false, null, array('step' => '3'))); exit; } else { foreach ($result as $key => $val) { $result[$key] = urldecode($val); } $this->context->smarty->assign('paypal_usa_errors', $result); $this->setTemplate('express-checkout-messages.tpl'); } }
protected function afterDelete($object, $old_id) { $customer = new Customer($old_id); $addresses = $customer->getAddresses($this->default_form_language); foreach ($addresses as $k => $v) { $address = new Address($v['id_address']); $address->id_customer = $object->id; $address->save(); } return true; }
/** * Each time a new order with Kiala delivery is passed, create the Kiala order in database * * @param array $params */ public function hookNewOrder($params) { // Get the kiala order created when the user selected a Kiala point $kiala_order = SmKialaOrder::getEmptyKialaOrder($params['cart']->id); if (!Validate::isLoadedObject($kiala_order) || !$kiala_order->point_short_id) { return; } // If the kiala carrier was selected at some point, but another carrier was the final choice, delete the uncomplete kiala order if ($params['cart']->id_carrier != Configuration::get('KIALASMALL_CARRIER_ID')) { $kiala_order->delete(); return; } $kiala_order->id_customer = $params['customer']->id; $kiala_order->id_cart = $params['cart']->id; $kiala_order->id_order = $params['order']->id; $kiala_country_pickup = SmKialaCountry::getPickupCountry(); $kiala_order->id_country_pickup = $kiala_country_pickup->id_country; // Get delivery country using the customer delivery address (not the kiala point address) $delivery_address = new Address($params['order']->id_address_delivery); $kiala_order->id_country_delivery = $delivery_address->id_country; // Create a new address with the Kiala point location $point_address = new Address(); $point_address->id_customer = $kiala_order->id_customer; $point_address->id_country = $kiala_order->id_country_delivery; // Set id_state in case the merchant added this field to the required fields list $point_address->id_state = 0; $point_address->lastname = $delivery_address->lastname; $point_address->firstname = $delivery_address->firstname; $point_address->address1 = substr($kiala_order->point_name . ' - ' . $kiala_order->point_street, 0, 128); $point_address->postcode = $kiala_order->point_zip; $point_address->city = $kiala_order->point_city; $point_address->address2 = $kiala_order->point_location_hint; $point_address->alias = 'Kiala point - ' . date('d-m-Y'); $point_address->deleted = true; $point_address->save(); // Assign the kiala point address as delivery address in order if ($point_address->id) { $order = $params['order']; $order->id_address_delivery = $point_address->id; $order->update(); } $kiala_order->save(); }
$customer->add(); } if (Configuration::get('QUI_CREATE_ADDRESS')) { $address = new Address(); if (Configuration::get('QUI_COUNTRY')) { $address->id_country = Country::getByIso(Configuration::get('QUI_COUNTRY')); } $address->firstname = Tools::getValue('firstname'); $address->lastname = ' '; $address->phone_mobile = Tools::getValue('phone'); $address->other = 'Эл.адрес:' . ' default@default.ru' . "\r\n" . 'Время: ' . Tools::getValue('time'); $address->address1 = ' '; $address->city = ' '; $address->alias = 'quickorder_' . substr(md5(time() . _COOKIE_KEY_), 0, 7); $address->id_customer = $customer->id; $address->save(); $cart->id_address_invoice = (int) $address->id; $cart->id_address_delivery = (int) $address->id; $id_address = (int) $address->id; $cart->update(); CartRule::autoRemoveFromCart($context); CartRule::autoAddToCart($context); if (!$context->cart->isMultiAddressDelivery()) { $context->cart->setNoMultishipping(); } } else { $message = new Message(); $message->id_cart = $cart->id; $message->message = 'Имя:' . ' ' . Tools::getValue('firstname') . "\r\n" . 'Эл.адрес:' . ' default@default.ru' . "\r\n" . 'Телефон:' . ' ' . Tools::getValue('phone') . "\r\n" . 'Время: ' . Tools::getValue('time'); $message->private = true; $message->add();
protected function runPage() { if (WebRequest::wasPosted()) { if (!WebRequest::postInt("calroom")) { $this->showCal(); return; } $startdate = new DateTime(WebRequest::post("qbCheckin")); $enddate = new DateTime(WebRequest::post("qbCheckout")); $room = Room::getById(WebRequest::postInt("calroom")); for ($date = $startdate; $date < $enddate; $date->modify("+1 day")) { if (!$room->isAvailable($date)) { $this->error("room-not-available"); $this->showCal(); return; } } // search for customer if (!($customer = Customer::getByEmail(WebRequest::post("qbEmail")))) { $customer = new Customer(); $suTitle = WebRequest::post("qbTitle"); $suFirstname = WebRequest::post("qbFirstname"); $suLastname = WebRequest::post("qbLastname"); $suAddress = WebRequest::post("qbAddress"); $suCity = WebRequest::post("qbCity"); $suPostcode = WebRequest::post("qbPostcode"); $suCountry = WebRequest::post("qbCountry"); $suEmail = WebRequest::post("qbEmail"); $customer->setPassword($suEmail); // set values $customer->setTitle($suTitle); $customer->setFirstname($suFirstname); $customer->setSurname($suLastname); $address = new Address(); $address->setLine1($suAddress); $address->setCity($suCity); $address->setPostCode($suPostcode); $address->setCountry($suCountry); $address->save(); $customer->setAddress($address); $customer->setEmail($suEmail); // save it $customer->save(); $customer->sendMailConfirm(); // save it again $customer->save(); } $booking = new Booking(); $booking->setStartDate(WebRequest::post("qbCheckin")); $booking->setEndDate(WebRequest::post("qbCheckout")); $booking->setAdults(WebRequest::post("qbAdults")); $booking->setChildren(WebRequest::post("qbChildren")); $booking->setPromocode(WebRequest::post("qbPromoCode")); $booking->setRoom($room->getId()); $booking->setCustomer($customer->getId()); $booking->save(); $msg = Message::getMessage("booking-confirmation"); $msg = str_replace("\$1", $booking->getStartDate(), $msg); $msg = str_replace("\$2", $booking->getEndDate(), $msg); $msg = str_replace("\$3", $booking->getAdults(), $msg); $msg = str_replace("\$4", $booking->getChildren(), $msg); $msg = str_replace("\$5", $booking->getRoom()->getName(), $msg); Mail::send($customer->getEmail(), Message::getMessage("booking-confimation-subject"), $msg); $this->mSmarty->assign("content", $msg); return; } throw new YouShouldntBeDoingThatException(); }
public function alertOrderStatus($data) { $order = $this->module->getOrderByYaId((int) $data->order->id); if ($order->id_cart > 0) { $status = $data->order->status; if ($status == 'CANCELLED') { $sub = $data->order->substatus; if (isset($sub) && $sub == 'RESERVATION_EXPIRED') { $order->setCurrentState((int) $this->module->status['RESERVATION_EXPIRED']); } else { $order->setCurrentState((int) $this->module->status['CANCELLED']); } } if ($status == 'PROCESSING') { $buyer = isset($data->order->buyer) ? $data->order->buyer : ''; if (isset($buyer) && !empty($buyer)) { $customer = new Customer(); $c = $customer->getByEmail($buyer->email); if (isset($c->id) && $c->id > 0) { $customer = new Customer($c->id); } else { $customer->firstname = $buyer->firstName; $customer->lastname = $buyer->lastName; $customer->email = $buyer->email; $customer->passwd = Tools::encrypt('OPC123456dmo'); $customer->newsletter = 1; $customer->optin = 1; $customer->active = 1; $customer->save(); } $address = new Address($order->id_address_delivery); $address->id_customer = $customer->id; $order->id_customer = $customer->id; $order->save(); $address->save(); } $order->setCurrentState((int) $this->module->status['PROCESSING']); } if ($status == 'UNPAID') { $order->setCurrentState($this->module->status['UNPAID']); } die(1); } }
protected function _addAddress($step) { $id_address = (int) Tools::getValue('id_address', 0); if ($id_address && !Tools::getValue('address_update', 0)) { $address = new Address((int) $id_address); if (Validate::isLoadedObject($address) and Customer::customerHasAddress((int) self::$cookie->id_customer, (int) $id_address)) { if (Tools::isSubmit('delete')) { if (self::$cart->id_address_invoice == $address->id) { unset(self::$cart->id_address_invoice); } if (self::$cart->id_address_delivery == $address->id) { unset(self::$cart->id_address_delivery); } if ($address->delete()) { Tools::redirect('order.php?step=1'); } $this->errors[] = Tools::displayError('This address cannot be deleted.'); } self::$smarty->assign(array('address' => $address, 'id_address' => (int) $id_address)); if (Tools::isSubmit('id_state') and Tools::getValue('id_state') != NULL and is_numeric(Tools::getValue('id_state'))) { $selected_state = Tools::getValue('id_state'); } elseif (isset($address) and isset($address->id_state) and !empty($address->id_state) and isset($address->id_state)) { $selected_state = $address->id_state; } else { $selected_state = false; } // default to karnataka. if (Tools::isSubmit('id_country') and Tools::getValue('id_country') != NULL and is_numeric(Tools::getValue('id_country'))) { $selected_country = Tools::getValue('id_country'); } elseif (isset($address) and isset($address->id_country) and !empty($address->id_country) and isset($address->id_state)) { $selected_country = $address->id_country; } else { $selected_country = false; } self::$smarty->assign('selected_country', $selected_country); self::$smarty->assign('selected_state', $selected_state); } } if (Tools::isSubmit('submitAddress')) { $address = new Address(); $this->errors = $address->validateControler(); $address->id_customer = (int) self::$cookie->id_customer; if (!Tools::getValue('phone') and !Tools::getValue('phone_mobile')) { $this->errors[] = Tools::displayError('Please add your mobile phone number.'); } if (!($country = new Country((int) $address->id_country)) or !Validate::isLoadedObject($country)) { die(Tools::displayError()); } //remove zipcode verification /* $zip_code_format = $country->zip_code_format; if ($country->need_zip_code) { if (($postcode = Tools::getValue('postcode')) AND $zip_code_format) { $zip_regexp = '/^'.$zip_code_format.'$/ui'; $zip_regexp = str_replace(' ', '( |)', $zip_regexp); $zip_regexp = str_replace('-', '(-|)', $zip_regexp); $zip_regexp = str_replace('N', '[0-9]', $zip_regexp); $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp); $zip_regexp = str_replace('C', $country->iso_code, $zip_regexp); if (!preg_match($zip_regexp, $postcode)) $this->errors[] = '<strong>'.Tools::displayError('Post/Zip Code mentioned is incorrect.').'</strong> '; } elseif ($zip_code_format) $this->errors[] = '<strong>'.Tools::displayError('Post/Zip Code mentioned is incorrect.').'</strong> '; elseif ($postcode AND !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode)) $this->errors[] = '<strong>'.Tools::displayError('Post/Zip Code mentioned is incorrect.').'</strong> '; } */ if (!Tools::isSubmit('order_add_address_billing')) { //validate pincode and assign possible payment options $op = 0; $op = Carrier::getPreferredCarriers($country->id); if ($op == 0) { $this->errors[] = 'We are sorry but we do not provide service to this region as of now. However, we keep adding new locations with time and would request you to check our website a few weeks later. We apologise for the inconvenience caused. '; } } if (!$country->isNeedDni()) { $address->dni = NULL; } if (Configuration::get('PS_TOKEN_ENABLE') == 1 and strcmp(Tools::getToken(false), Tools::getValue('token')) and self::$cookie->isLogged(true) === true) { $this->errors[] = Tools::displayError('Invalid token'); } if ((int) $country->contains_states and !(int) $address->id_state) { $this->errors[] = Tools::displayError('Please select a state.'); } if (!sizeof($this->errors)) { if (isset($id_address)) { $country = new Country((int) $address->id_country); if (Validate::isLoadedObject($country) and !$country->contains_states) { $address->id_state = 0; } $address_old = new Address((int) $id_address); if (Validate::isLoadedObject($address_old) and Customer::customerHasAddress((int) self::$cookie->id_customer, (int) $address_old->id)) { if ($address_old->isUsed()) { $address_old->delete(); if (!Tools::isSubmit('ajax')) { $to_update = false; if (self::$cart->id_address_invoice == $address_old->id) { $to_update = true; self::$cart->id_address_invoice = 0; } if (self::$cart->id_address_delivery == $address_old->id) { $to_update = true; self::$cart->id_address_delivery = 0; } if ($to_update) { self::$cart->update(); } } } else { $address->id = (int) $address_old->id; $address->date_add = $address_old->date_add; } } } if ($result = $address->save()) { if (Tools::isSubmit('order_add_address')) { self::$cart->id_address_delivery = (int) $address->id; self::$cart->update(); self::$smarty->assign(array('op' => $op)); } else { if (Tools::isSubmit('order_add_address_billing')) { self::$cart->id_address_invoice = (int) $address->id; self::$cart->update(); } } } else { $this->errors[] = Tools::displayError('An error occurred while updating your address.'); } } if (sizeof($this->errors)) { self::$smarty->assign('errors', $this->errors); $this->step = 1; } } }
/** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; // We call the save method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->aAddress !== null) { if ($this->aAddress->isModified() || $this->aAddress->isNew()) { $affectedRows += $this->aAddress->save($con); } $this->setAddress($this->aAddress); } if ($this->isNew() || $this->isModified()) { // persist changes if ($this->isNew()) { $this->doInsert($con); } else { $this->doUpdate($con); } $affectedRows += 1; $this->resetModified(); } if ($this->bookingTypesScheduledForDeletion !== null) { if (!$this->bookingTypesScheduledForDeletion->isEmpty()) { BookingTypeQuery::create()->filterByPrimaryKeys($this->bookingTypesScheduledForDeletion->getPrimaryKeys(false))->delete($con); $this->bookingTypesScheduledForDeletion = null; } } if ($this->collBookingTypes !== null) { foreach ($this->collBookingTypes as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } if ($this->clockingTypesScheduledForDeletion !== null) { if (!$this->clockingTypesScheduledForDeletion->isEmpty()) { ClockingTypeQuery::create()->filterByPrimaryKeys($this->clockingTypesScheduledForDeletion->getPrimaryKeys(false))->delete($con); $this->clockingTypesScheduledForDeletion = null; } } if ($this->collClockingTypes !== null) { foreach ($this->collClockingTypes as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } if ($this->domainsScheduledForDeletion !== null) { if (!$this->domainsScheduledForDeletion->isEmpty()) { DomainQuery::create()->filterByPrimaryKeys($this->domainsScheduledForDeletion->getPrimaryKeys(false))->delete($con); $this->domainsScheduledForDeletion = null; } } if ($this->collDomains !== null) { foreach ($this->collDomains as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } if ($this->holidaysScheduledForDeletion !== null) { if (!$this->holidaysScheduledForDeletion->isEmpty()) { HolidayQuery::create()->filterByPrimaryKeys($this->holidaysScheduledForDeletion->getPrimaryKeys(false))->delete($con); $this->holidaysScheduledForDeletion = null; } } if ($this->collHolidays !== null) { foreach ($this->collHolidays as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } if ($this->pluginsScheduledForDeletion !== null) { if (!$this->pluginsScheduledForDeletion->isEmpty()) { PluginQuery::create()->filterByPrimaryKeys($this->pluginsScheduledForDeletion->getPrimaryKeys(false))->delete($con); $this->pluginsScheduledForDeletion = null; } } if ($this->collPlugins !== null) { foreach ($this->collPlugins as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } if ($this->propertysScheduledForDeletion !== null) { if (!$this->propertysScheduledForDeletion->isEmpty()) { PropertyQuery::create()->filterByPrimaryKeys($this->propertysScheduledForDeletion->getPrimaryKeys(false))->delete($con); $this->propertysScheduledForDeletion = null; } } if ($this->collPropertys !== null) { foreach ($this->collPropertys as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } if ($this->usersScheduledForDeletion !== null) { if (!$this->usersScheduledForDeletion->isEmpty()) { UserQuery::create()->filterByPrimaryKeys($this->usersScheduledForDeletion->getPrimaryKeys(false))->delete($con); $this->usersScheduledForDeletion = null; } } if ($this->collUsers !== null) { foreach ($this->collUsers as $referrerFK) { if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { $affectedRows += $referrerFK->save($con); } } } $this->alreadyInSave = false; } return $affectedRows; }
/** * Process changes on an address */ protected function processSubmitAddress() { $address = new Address(); $this->errors = $address->validateController(); $address->id_customer = (int) $this->context->customer->id; // Check page token if ($this->context->customer->isLogged() && !$this->isTokenValid()) { $this->errors[] = Tools::displayError('Invalid token.'); } // Check phone if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile')) { $this->errors[] = Tools::displayError('You must register at least one phone number.'); } if ($address->id_country) { // Check country if (!($country = new Country($address->id_country)) || !Validate::isLoadedObject($country)) { throw new PrestaShopException('Country cannot be loaded with address->id_country'); } if ((int) $country->contains_states && !(int) $address->id_state) { $this->errors[] = Tools::displayError('This country requires you to chose a State.'); } // US customer: normalize the address if ($address->id_country == Country::getByIso('US') && Configuration::get('PS_TAASC')) { include_once _PS_TAASC_PATH_ . 'AddressStandardizationSolution.php'; $normalize = new AddressStandardizationSolution(); $address->address1 = $normalize->AddressLineStandardization($address->address1); $address->address2 = $normalize->AddressLineStandardization($address->address2); } $postcode = Tools::getValue('postcode'); /* Check zip code format */ if ($country->zip_code_format && !$country->checkZipCode($postcode)) { $this->errors[] = sprintf(Tools::displayError('The Zip/Postal code you\'ve entered is invalid. It must follow this format: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format)))); } elseif (empty($postcode) && $country->need_zip_code) { $this->errors[] = Tools::displayError('A Zip / Postal code is required.'); } elseif ($postcode && !Validate::isPostCode($postcode)) { $this->errors[] = Tools::displayError('The Zip / Postal code is invalid.'); } // Check country DNI nox fix /*if ($country->isNeedDni() && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni')))) $this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.'); else if (!$country->isNeedDni()) $address->dni = null;*/ if ($country->need_identification_number && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni')))) { $this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.'); } elseif (!$country->need_identification_number) { ${$addresses_type}->dni = null; } } // Check if the alias exists if (!$this->context->customer->is_guest && !empty($_POST['alias']) && (int) $this->context->customer->id > 0) { $id_address = Tools::getValue('id_address'); if (Configuration::get('PS_ORDER_PROCESS_TYPE') && (int) Tools::getValue('opc_id_address_' . Tools::getValue('type')) > 0) { $id_address = Tools::getValue('opc_id_address_' . Tools::getValue('type')); } if (Db::getInstance()->getValue(' SELECT count(*) FROM ' . _DB_PREFIX_ . 'address WHERE `alias` = \'' . pSql($_POST['alias']) . '\' AND id_address != ' . (int) $id_address . ' AND id_customer = ' . (int) $this->context->customer->id . ' AND deleted = 0') > 0) { $this->errors[] = sprintf(Tools::displayError('The alias "%s" has already been used. Please select another one.'), Tools::safeOutput($_POST['alias'])); } } // Check the requires fields which are settings in the BO $this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase()); // Don't continue this process if we have errors ! if ($this->errors && !$this->ajax) { return; } // If we edit this address, delete old address and create a new one if (Validate::isLoadedObject($this->_address)) { if (Validate::isLoadedObject($country) && !$country->contains_states) { $address->id_state = 0; } $address_old = $this->_address; if (Customer::customerHasAddress($this->context->customer->id, (int) $address_old->id)) { if ($address_old->isUsed()) { $address_old->delete(); } else { $address->id = (int) $address_old->id; $address->date_add = $address_old->date_add; } } } if ($this->ajax && Tools::getValue('type') == 'invoice' && Configuration::get('PS_ORDER_PROCESS_TYPE')) { $this->errors = array_unique(array_merge($this->errors, $address->validateController())); if (count($this->errors)) { $return = array('hasError' => (bool) $this->errors, 'errors' => $this->errors); die(Tools::jsonEncode($return)); } } // Save address if ($result = $address->save()) { // Update id address of the current cart if necessary if (isset($address_old) && $address_old->isUsed()) { $this->context->cart->updateAddressId($address_old->id, $address->id); } else { // Update cart address $this->context->cart->autosetProductAddress(); } if ((bool) Tools::getValue('select_address', false) == true or Tools::getValue('type') == 'invoice' && Configuration::get('PS_ORDER_PROCESS_TYPE')) { $this->context->cart->id_address_invoice = (int) $address->id; } elseif (Configuration::get('PS_ORDER_PROCESS_TYPE')) { $this->context->cart->id_address_invoice = (int) $this->context->cart->id_address_delivery; } $this->context->cart->update(); if ($this->ajax) { $return = array('hasError' => (bool) $this->errors, 'errors' => $this->errors, 'id_address_delivery' => (int) $this->context->cart->id_address_delivery, 'id_address_invoice' => (int) $this->context->cart->id_address_invoice); die(Tools::jsonEncode($return)); } // Redirect to old page or current page if ($back = Tools::getValue('back')) { if ($back == Tools::secureReferrer(Tools::getValue('back'))) { Tools::redirect(html_entity_decode($back)); } $mod = Tools::getValue('mod'); Tools::redirect('index.php?controller=' . $back . ($mod ? '&back=' . $mod : '')); } else { Tools::redirect('index.php?controller=addresses'); } } $this->errors[] = Tools::displayError('An error occurred while updating your address.'); }
/** * @see AdminController::processDelete(); */ public function processDelete() { if (Tools::isSubmit('delete' . $this->table)) { /** @var Warehouse $obj */ // check if the warehouse exists and can be deleted if (!($obj = $this->loadObject(true))) { return; } elseif ($obj->getQuantitiesOfProducts() > 0) { // not possible : products $this->errors[] = $this->l('It is not possible to delete a warehouse when there are products in it.'); } elseif (SupplyOrder::warehouseHasPendingOrders($obj->id)) { // not possible : supply orders $this->errors[] = $this->l('It is not possible to delete a Warehouse if it has pending supply orders.'); } else { // else, it can be deleted // sets the address of the warehouse as deleted $address = new Address($obj->id_address); $address->deleted = 1; $address->save(); // removes associations with carriers/shops/products location $obj->setCarriers(array()); $obj->resetProductsLocations(); return parent::processDelete(); } } }
private function updateOrderRedoute($neteven_order) { if ($id_order = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT `id_order` FROM `' . _DB_PREFIX_ . 'orders_gateway` WHERE `id_order_neteven` = ' . (int) $neteven_order->OrderID)) { $order = new Order((int) $id_order); $last_name = Toolbox::removeAccents($neteven_order->BillingAddress->LastName); $customer = new Customer((int) $order->id_customer); $customer->firstname = !empty($neteven_order->BillingAddress->FirstName) ? substr(Toolbox::stringFilter($neteven_order->BillingAddress->FirstName), 0, 32) : ' '; $customer->lastname = !empty($last_name) ? substr(Toolbox::stringFilter($last_name), 0, 32) : ' '; $customer->email = Validate::isEmail($neteven_order->BillingAddress->Email) && !empty($neteven_order->BillingAddress->Email) ? '_' . $neteven_order->BillingAddress->Email : '_client' . $neteven_order->OrderID . '@' . $neteven_order->MarketPlaceName . '.com'; $customer->save(); $date_now = date('Y-m-d H:i:s'); $shipping_address = $neteven_order->ShippingAddress; $id_country = $this->getValue('id_country_default'); $address = new Address((int) $order->id_address_delivery); $address->lastname = !empty($shipping_address->LastName) ? substr(Toolbox::stringFilter($shipping_address->LastName), 0, 32) : ' '; $address->firstname = !empty($shipping_address->FirstName) ? substr(Toolbox::stringFilter($shipping_address->FirstName), 0, 32) : ' '; $address->address1 = !empty($shipping_address->Address1) ? Toolbox::stringWithNumericFilter($shipping_address->Address1) : ' '; $address->address2 = Toolbox::stringWithNumericFilter($shipping_address->Address2); $address->postcode = Toolbox::numericFilter($shipping_address->PostalCode); $address->city = !empty($shipping_address->CityName) ? Toolbox::stringFilter($shipping_address->CityName) : ' '; $address->phone = substr(Toolbox::numericFilter($shipping_address->Phone), 0, 16); $address->phone_mobile = substr(Toolbox::numericFilter($shipping_address->Mobile), 0, 16); $address->id_country = $id_country; $address->date_upd = $date_now; if (!empty($shipping_address->Company)) { $address->company = $shipping_address->Company; } $address->save(); $billing_address = $neteven_order->BillingAddress; $address = new Address((int) $order->id_address_invoice); $address->lastname = !empty($billing_address->LastName) ? substr(Toolbox::stringFilter($billing_address->LastName), 0, 32) : ' '; $address->firstname = !empty($billing_address->FirstName) ? substr(Toolbox::stringFilter($billing_address->FirstName), 0, 32) : ' '; $address->address1 = !empty($billing_address->Address1) ? Toolbox::stringWithNumericFilter($billing_address->Address1) : ' '; $address->address2 = Toolbox::stringWithNumericFilter($billing_address->Address2); $address->postcode = Toolbox::numericFilter($billing_address->PostalCode); $address->city = !empty($billing_address->CityName) ? Toolbox::stringFilter($billing_address->CityName) : ' '; $address->phone = substr(Toolbox::numericFilter($billing_address->Phone), 0, 16); $address->phone_mobile = substr(Toolbox::numericFilter($billing_address->Mobile), 0, 16); $address->id_country = $id_country; $address->date_upd = $date_now; if (!empty($billing_address->Company)) { $address->company = $billing_address->Company; } $address->save(); } }
public function actionEditCommissioningBody() { if (isset($_GET['commissioning_body_id'])) { if (!($cb = CommissioningBody::model()->findByPk(@$_GET['commissioning_body_id']))) { throw new Exception("CommissioningBody not found: " . @$_GET['commissioning_body_id']); } if (!($address = $cb->contact->address)) { $address = new Address(); $address->country_id = 1; } } else { $cb = new CommissioningBody(); $address = new Address(); $address->country_id = 1; } $errors = array(); if (!empty($_POST)) { $cb->attributes = $_POST['CommissioningBody']; if (!$cb->validate()) { $errors = $cb->getErrors(); } $address->attributes = $_POST['Address']; if (!$address->validate()) { $errors = array_merge($errors, $address->getErrors()); } if (empty($errors)) { if (!($contact = $cb->contact)) { $contact = new Contact(); if (!$contact->save()) { throw new Exception("Unable to save contact for commissioning body: " . print_r($contact->getErrors(), true)); } } $cb->contact_id = $contact->id; $method = $cb->id ? 'edit' : 'add'; $audit = $_POST; if ($method == 'edit') { $audit['id'] = $cb->id; } if (!$cb->save()) { throw new Exception("Unable to save CommissioningBody : " . print_r($cb->getErrors(), true)); } $address->contact_id = $contact->id; if (!$address->save()) { throw new Exception("Unable to save CommissioningBody address: " . print_r($address->getErrors(), true)); } Audit::add('admin-CommissioningBody', $method, $cb->id); $this->redirect('/admin/commissioning_bodies'); } } else { Audit::add('admin-CommissioningBody', 'view', @$_GET['commissioning_body_id']); } $this->render('/admin/editCommissioningBody', array('cb' => $cb, 'address' => $address, 'errors' => $errors)); }
public function actionOrder() { $firstname = Yii::app()->request->getPost("firstname", null); $lastname = Yii::app()->request->getPost("lastname", null); $phone = Yii::app()->request->getPost("phone", null); $billing_addr1 = Yii::app()->request->getPost("billing_addr1", null); $billing_addr2 = Yii::app()->request->getPost('billing_addr2', null); $billing_city = Yii::app()->request->getPost('billing_city', null); $billing_region = Yii::app()->request->getPost('billing_region', null); $billing_postcode = Yii::app()->request->getPost('billing_postcode', null); $billing_country = Yii::app()->request->getPost('billing_country', null); $ship_to_billing = Yii::app()->request->getPost('ship_to_billing', null); if ($ship_to_billing === "true") { $shipping_addr1 = $billing_addr1; $shipping_addr2 = $billing_addr2; $shipping_city = $billing_city; $shipping_region = $billing_region; $shipping_postcode = $billing_postcode; $shipping_country = $billing_country; } else { $shipping_addr1 = Yii::app()->request->getPost("shipping_addr1", null); $shipping_addr2 = Yii::app()->request->getPost('shipping_addr2', null); $shipping_city = Yii::app()->request->getPost('shipping_city', null); $shipping_region = Yii::app()->request->getPost('shipping_region', null); $shipping_postcode = Yii::app()->request->getPost('shipping_postcode', null); $shipping_country = Yii::app()->request->getPost('shipping_country', null); } if (!$billing_addr1 || !$billing_city || !$billing_region || !$billing_postcode || !$billing_country || !$shipping_addr1 || !$shipping_city || !$shipping_region || !$shipping_postcode || !$shipping_country) { throw new CHttpException(400, 'Invalid request; missing parameters.'); } if (!Yii::app()->user->user->firstname && !$firstname || !Yii::app()->user->user->lastname && !$lastname) { throw new CHttpException(400, 'Invalid request; missing parameters for basic user info.'); } if ($firstname) { Yii::app()->user->user->firstname = $firstname; Yii::app()->user->user->save(); } if ($lastname) { Yii::app()->user->user->lastname = $lastname; Yii::app()->user->user->save(); } $cart = $this->getCart(); $order_details = $cart->orderDetails; if ($order_details === null) { $order_details = new OrderDetails(); $order_details->order_id = $cart->id; } // Save phone number Yii::app()->user->user->addUserPhone($phone); # TODO Replace systematic new addresses by saved addresses $billing_address = new Address(); $billing_address->user_id = Yii::app()->user->user->id; $billing_address->street1 = $billing_addr1; $billing_address->street2 = $billing_addr2; $billing_address->city = $billing_city; $billing_address->postcode = $billing_postcode; $billing_address->region = $billing_region; $billing_address->country = $billing_country; $billing_address->save(); if (!Yii::app()->user->user->prefered_billing_address_id) { Yii::app()->user->user->prefered_billing_address_id = $billing_address->id; Yii::app()->user->user->save(); } $order_details->billing_address_id = $billing_address->id; if ($ship_to_billing === "true") { $shipping_address = $billing_address; $order_details->shipping_address_id = $billing_address->id; } else { $shipping_address = new Address(); $shipping_address->user_id = Yii::app()->user->user->id; $shipping_address->street1 = $shipping_addr1; $shipping_address->street2 = $shipping_addr2; $shipping_address->city = $shipping_city; $shipping_address->postcode = $shipping_postcode; $shipping_address->region = $shipping_region; $shipping_address->country = $shipping_country; $shipping_address->save(); $order_details->shipping_address_id = $shipping_address->id; } if (!Yii::app()->user->user->prefered_shipping_address_id) { Yii::app()->user->user->prefered_shipping_address_id = $shipping_address->id; Yii::app()->user->user->save(); } // Save every detail for the order total price and taxes based on the provided shipping address $itemsInCart = new CActiveDataProvider('OrderHasProduct', array('criteria' => array('condition' => 'order_id=' . $cart->id, 'with' => array('product')), 'pagination' => false)); $total_weight = 0.0; $total_value = 0.0; $total_item_qty = 0; foreach ($itemsInCart->getData() as $relationship) { $total_weight += $relationship->quantity * $relationship->product->weight; $total_value += $relationship->quantity * $relationship->price_paid; $total_item_qty += $relationship->quantity; } // Build the json request data we'll send to our server $weight = $total_weight; $handling = 0; $postal_code = $shipping_address->postcode; $country_code = $shipping_address->country; $value = $total_value; $qty = $total_item_qty; $orderData = array("weight" => $weight, "handling" => $handling, "postal_code" => $postal_code, "country_code" => $country_code, "value" => $value, "qty" => $qty); $jsonpayload = json_encode($orderData); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://kle-en-main.com/CloudServices/index.php/BoukemAPI/canadaPostEstimate/listServices?storeid=" . Yii::app()->params['outbound_api_user'] . "&storekey=" . Yii::app()->params['outbound_api_secret']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpayload); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); $result = curl_exec($ch); curl_close($ch); $arr = json_decode($result); if (!isset($arr->services)) { throw new CHttpException(400, Yii::t("app", "Postes Canada ne peut fournir d'estimé en ce moment.")); } $rates = $arr->services; if ($rates === null) { throw new CHttpException(400, Yii::t("app", 'Une erreur est survenue.')); } $preferred_method = Yii::app()->session['shipment_method']; $shiprate = null; foreach ($rates as $rate) { if ($rate->service_code === $preferred_method) { $shiprate = $rate->price_due; break; } } if ($shiprate === null) { throw new CHttpException(400, 'The delivery method specified in the cart is not available.'); } // TAXES $order_details->shipping = $shiprate; $order_details->shipping_type = $preferred_method; $order_details->taxes = $this->taxesForProvinceCountryValue($shipping_address->region, $shipping_address->country, $total_value); $order_details->subtotal = $total_value; $order_details->total = floatval($order_details->subtotal) + floatval($order_details->taxes) + floatval($order_details->shipping); $order_details->balance = $order_details->total; $order_details->save(); // Transform the cart in order to avoid deleting it. $cart->status = "pending"; $cart->save(); $order = $cart; $order->orderDetails = $order_details; // We need to manually set the association to avoid having a null returned //$outputArray = array("id"=>$order->id, , 'sid'=>Yii::app()->params['outbound_api_user']); $link = $order->getPaypalPaymentLink(); $this->jsonout(array("payment_link" => $link)); }
/** * AdminController::postProcess() override * @see AdminController::postProcess() */ public function postProcess() { // checks access if (Tools::isSubmit('submitAdd' . $this->table) && !($this->tabAccess['add'] === '1')) { $this->errors[] = Tools::displayError('You do not have permission to add suppliers.'); return parent::postProcess(); } if (Tools::isSubmit('submitAdd' . $this->table)) { if (Tools::isSubmit('id_supplier') && !($obj = $this->loadObject(true))) { return; } // updates/creates address if it does not exist if (Tools::isSubmit('id_address') && (int) Tools::getValue('id_address') > 0) { $address = new Address((int) Tools::getValue('id_address')); } else { $address = new Address(); } // creates address $address->alias = Tools::getValue('name', null); $address->lastname = 'supplier'; // skip problem with numeric characters in supplier name $address->firstname = 'supplier'; // skip problem with numeric characters in supplier name $address->address1 = Tools::getValue('address', null); $address->address2 = Tools::getValue('address2', null); $address->postcode = Tools::getValue('postcode', null); $address->phone = Tools::getValue('phone', null); $address->phone_mobile = Tools::getValue('phone_mobile', null); $address->id_country = Tools::getValue('id_country', null); $address->id_state = Tools::getValue('id_state', null); $address->city = Tools::getValue('city', null); $validation = $address->validateController(); // checks address validity if (count($validation) > 0) { foreach ($validation as $item) { $this->errors[] = $item; } $this->errors[] = Tools::displayError('The address is not correct. Please make sure all of the required fields are completed.'); } else { if (Tools::isSubmit('id_address') && Tools::getValue('id_address') > 0) { $address->update(); } else { $address->save(); $_POST['id_address'] = $address->id; } } return parent::postProcess(); } elseif (Tools::isSubmit('delete' . $this->table)) { if (!($obj = $this->loadObject(true))) { return; } elseif (SupplyOrder::supplierHasPendingOrders($obj->id)) { $this->errors[] = $this->l('It is not possible to delete a supplier if there are pending supplier orders.'); } else { //delete all product_supplier linked to this supplier Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'product_supplier` WHERE `id_supplier`=' . (int) $obj->id); $id_address = Address::getAddressIdBySupplierId($obj->id); $address = new Address($id_address); if (Validate::isLoadedObject($address)) { $address->deleted = 1; $address->save(); } return parent::postProcess(); } } else { return parent::postProcess(); } }