public function add($autodate = true, $null_values = false) { if (!parent::add($autodate)) { return false; } $order = new Order((int) $this->id_order); // Update id_order_state attribute in Order $order->current_state = $this->id_order_state; $order->update(); // start of implementation of the module code - taxamo $operation = null; $list_orderstateoperation = Taxamoeuvat::getListValues(); foreach ($list_orderstateoperation as $orderstateoperation) { if ($orderstateoperation['id_order_state'] == $order->current_state) { $operation = $orderstateoperation['operation']; } } if (!is_null($operation)) { if ($operation == 1 || $operation == 2) { $last_id_order_transaction = Taxamoeuvat::getLastIdByOrder($order->id); if (is_null($last_id_order_transaction)) { $res_process_store_transaction = Tools::taxamoStoreTransaction($order->id_currency, $order->id_address_invoice, $order->id_customer, $order->getCartProducts()); if (is_null($res_process_store_transaction['key_transaction'])) { $res_process_store_transaction['comment'] .= '* Transaccion NO Adicionada'; } else { $res_process_store_transaction['comment'] .= '* Transaccion ADICIONADA'; } Taxamoeuvat::addTransaction($order->id, $order->current_state, $res_process_store_transaction['key_transaction'], $res_process_store_transaction['comment']); } else { $reg_taxamo_transaction = null; $reg_taxamo_transaction = Taxamoeuvat::idExistsTransaction((int) $last_id_order_transaction); $res_process_store_transaction['key_transaction'] = $reg_taxamo_transaction[0]['key_transaction']; $res_process_store_transaction['comment'] = ''; } if ($operation == 2) { if (is_null($res_process_store_transaction['key_transaction'])) { $res_process_store_transaction['comment'] .= '* Transaccion NO Confirmada'; } else { $res_process_confirm_transaction = Tools::taxamoConfirmTransaction($res_process_store_transaction['key_transaction']); if (!is_null($res_process_confirm_transaction['status']) && $res_process_confirm_transaction['status'] == 'C') { $res_process_store_transaction['comment'] .= '* Transaccion CONFIRMADA'; } else { if (!empty($res_process_confirm_transaction['error'])) { $res_process_store_transaction['comment'] .= $res_process_confirm_transaction['error']; $res_process_store_transaction['comment'] .= '* Transaccion NO Confirmada'; } } } Taxamoeuvat::addTransaction($order->id, $order->current_state, $res_process_store_transaction['key_transaction'], $res_process_store_transaction['comment']); } } } // end of code implementation module - taxamo Hook::exec('actionOrderHistoryAddAfter', array('order_history' => $this), null, false, true, false, $order->id_shop); return true; }
/** * @param ShopgateOrder $order * * @return array * @throws PrestaShopException * @throws ShopgateLibraryException */ public function addOrder(ShopgateOrder $order) { /** * check exits shopgate order */ if (ShopgateOrderPrestashop::loadByOrderNumber($order->getOrderNumber())->status == 1) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DUPLICATE_ORDER, sprintf('external_order_id: %s', $order->getOrderNumber()), true); } /** @var CarrierCore $sgCarrier */ $sgCarrier = new Carrier(Configuration::get('SG_CARRIER_ID')); if (version_compare(_PS_VERSION_, '1.5.0', '<') && empty($sgCarrier->name)) { $sgCarrier->name = 'shopgate_tmp_carrier'; } if ($order->getShippingType() != ShopgateShipping::DEFAULT_PLUGIN_API_KEY) { if ($order->getShippingInfos()->getAmount() > 0) { if (version_compare(_PS_VERSION_, '1.5.0', '<')) { ShopgateModObjectModel::updateShippingPrice(pSQL($order->getShippingInfos()->getAmount())); } else { $data = array('price' => pSQL($order->getShippingInfos()->getAmount())); $where = 'a.id_carrier = ' . (int) Configuration::get('SG_CARRIER_ID'); ObjectModel::updateMultishopTable('Delivery', $data, $where); } $sgCarrier->is_free = 0; } else { $sgCarrier->is_free = 1; } } $sgCarrier->update(); $customerModel = new ShopgateItemsCustomerImportJson($this->getPlugin()); $paymentModel = new ShopgatePayment($this->getModule()); $shippingModel = new ShopgateShipping($this->getModule()); /** * read / check customer */ if (!($customerId = Customer::customerExists($order->getMail(), true, false))) { /** * prepare customer */ $shopgateCustomerItem = new ShopgateCustomer(); $shopgateCustomerItem->setLastName($order->getInvoiceAddress()->getLastName()); $shopgateCustomerItem->setFirstName($order->getInvoiceAddress()->getFirstName()); $shopgateCustomerItem->setGender($order->getInvoiceAddress()->getGender()); $shopgateCustomerItem->setBirthday($order->getInvoiceAddress()->getBirthday()); $shopgateCustomerItem->setNewsletterSubscription(Configuration::get('SG_SUBSCRIBE_NEWSLETTER') ? true : false); $customerId = $customerModel->registerCustomer($order->getMail(), md5(_COOKIE_KEY_ . time()), $shopgateCustomerItem); } /** @var CustomerCore $customer */ $customer = new Customer($customerId); /** * prepare cart */ if (!$order->getDeliveryAddress()->getPhone()) { $order->getDeliveryAddress()->setPhone($order->getPhone()); } if (!$order->getInvoiceAddress()->getPhone()) { $order->getInvoiceAddress()->setPhone($order->getPhone()); } $this->getCart()->id_address_delivery = $customerModel->createAddress($order->getDeliveryAddress(), $customer); $this->getCart()->id_address_invoice = $customerModel->createAddress($order->getInvoiceAddress(), $customer); $this->getCart()->id_customer = $customerId; // id_guest is a connection to a ps_guest entry which includes screen width etc. // is_guest field only exists in Prestashop 1.4.1.0 and higher if (version_compare(_PS_VERSION_, '1.4.1.0', '>=')) { $this->getCart()->id_guest = $customer->is_guest; } $this->getCart()->secure_key = $customer->secure_key; $this->getCart()->id_carrier = $shippingModel->getCarrierIdByApiOrder($order); $shopgateCustomFieldsHelper = new ShopgateCustomFieldsHelper(); $shopgateCustomFieldsHelper->saveCustomFields($this->getCart(), $order->getCustomFields()); $this->getCart()->add(); /** * add cart items */ $canCreateOrder = true; $errorMessages = array(); foreach ($order->getItems() as $item) { list($productId, $attributeId) = ShopgateHelper::getProductIdentifiers($item); if ($productId == 0) { continue; } $updateCart = $this->getCart()->updateQty($item->getQuantity(), $productId, $attributeId, false, 'up', $this->getCart()->id_address_delivery); if ($updateCart !== true) { $canCreateOrder = false; $errorMessages[] = array('product_id' => $productId, 'attribute_id' => $attributeId, 'quantity' => $item->getQuantity(), 'result' => $updateCart, 'reason' => $updateCart == -1 ? 'minimum quantity not reached' : ''); } } /** * coupons */ foreach ($order->getExternalCoupons() as $coupon) { /** @var CartRuleCore $cartRule */ $cartRule = new CartRule(CartRule::getIdByCode($coupon->getCode())); if (Validate::isLoadedObject($cartRule)) { $this->getCart()->addCartRule($cartRule->id); $this->getCart()->save(); } } if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) { /** * this field is not available in version 1.4.x.x * set delivery option */ $delivery_option = array($this->getCart()->id_address_delivery => $shippingModel->getCarrierIdByApiOrder($order) . ','); $this->getCart()->setDeliveryOption($delivery_option); } /** * store shopgate order */ $shopgateOrderItem = new ShopgateOrderPrestashop(); $shopgateOrderItem->fillFromOrder($this->getCart(), $order, $this->getPlugin()->getShopgateConfig()->getShopNumber()); if (version_compare(_PS_VERSION_, '1.6.0.0', '<')) { $shopgateOrderItem->add(); } /** * create order */ if ($canCreateOrder) { /** * get first item from order stats */ $this->getCart()->save(); $idOrderState = reset($paymentModel->getOrderStateId($order)); $validateOder = $this->getModule()->validateOrder($this->getCart()->id, $idOrderState, $this->getCart()->getOrderTotal(true, defined('Cart::BOTH') ? Cart::BOTH : 3), $paymentModel->getPaymentTitleByKey($order->getPaymentMethod()), null, array(), null, false, $this->getCart()->secure_key); if (version_compare(_PS_VERSION_, '1.5.0.0', '<') && (int) $this->getModule()->currentOrder > 0 && $order->getShippingType() != ShopgateShipping::DEFAULT_PLUGIN_API_KEY && $order->getShippingInfos()->getAmount() > 0) { ShopgateLogger::log('PS < 1.5.0.0: update shipping and payment cost', ShopgateLogger::LOGTYPE_DEBUG); // in versions below 1.5.0.0 the shipping and payment costs must be updated after the order was imported /** @var OrderCore $updateShopgateOrder */ $updateShopgateOrder = new Order($this->getModule()->currentOrder); $updateShopgateOrder->total_shipping = $order->getAmountShipping() + $order->getAmountShopPayment(); $updateShopgateOrder->total_paid += $order->getAmountShipping() + $order->getAmountShopPayment(); $updateShopgateOrder->total_paid_real += $order->getAmountShipping() + $order->getAmountShopPayment(); $updateShopgateOrder->update(); } /** * update shopgate order */ if ($validateOder) { $shopgateOrderItem->id_order = $this->getModule()->currentOrder; $shopgateOrderItem->status = 1; $shopgateOrderItem->save(); return array('external_order_id' => $shopgateOrderItem->id_order, 'external_order_number' => $shopgateOrderItem->id_order); } } $shopgateOrderItem->delete(); throw new ShopgateLibraryException(ShopgateLibraryException::UNKNOWN_ERROR_CODE, 'Unable to create order:' . print_r($errorMessages, true), true); }
public function addOrder(ShopgateOrder $order) { $this->log("PS start add_order", ShopgateLogger::LOGTYPE_DEBUG); $shopgateOrder = PSShopgateOrder::instanceByOrderNumber($order->getOrderNumber()); if ($shopgateOrder->id) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DUPLICATE_ORDER, 'external_order_id: ' . $shopgateOrder->id_order, true); } $comments = array(); // generate products array $products = $this->insertOrderItems($order); //Get or create customer $id_customer = Customer::customerExists($order->getMail(), true, false); $customer = new Customer($id_customer ? $id_customer : (int) $order->getExternalCustomerId()); if (!$customer->id) { $customer = $this->createCustomer($customer, $order); } // prepare addresses: company has to be shorten. add mobile phone / telephone $this->prepareAddresses($order); //Get invoice and delivery addresses $invoiceAddress = $this->getPSAddress($customer, $order->getInvoiceAddress()); $deliveryAddress = $order->getInvoiceAddress() == $order->getDeliveryAddress() ? $invoiceAddress : $this->getPSAddress($customer, $order->getDeliveryAddress()); //Creating currency $this->log("PS setting currency", ShopgateLogger::LOGTYPE_DEBUG); $id_currency = $order->getCurrency() ? Currency::getIdByIsoCode($order->getCurrency()) : $this->id_currency; $currency = new Currency($id_currency ? $id_currency : $this->id_currency); //Creating new cart $this->log("PS set cart variables", ShopgateLogger::LOGTYPE_DEBUG); $cart = new Cart(); $cart->id_lang = $this->id_lang; $cart->id_currency = $currency->id; $cart->id_address_delivery = $deliveryAddress->id; $cart->id_address_invoice = $invoiceAddress->id; $cart->id_customer = $customer->id; if (version_compare(_PS_VERSION_, '1.4.1.0', '>=')) { // id_guest is a connection to a ps_guest entry which includes screen width etc. // is_guest field only exists in Prestashop 1.4.1.0 and higher $cart->id_guest = $customer->is_guest; } $cart->recyclable = 0; $cart->gift = 0; $cart->id_carrier = (int) Configuration::get('SHOPGATE_CARRIER_ID'); $cart->secure_key = $customer->secure_key; $this->log("PS try to create cart", ShopgateLogger::LOGTYPE_DEBUG); if (!$cart->add()) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create cart', true); } //Adding items to cart $this->log("PS adding items to cart", ShopgateLogger::LOGTYPE_DEBUG); foreach ($products as $p) { $this->log("PS cart updateQty product id: " . $p['id_product'], ShopgateLogger::LOGTYPE_DEBUG); $this->log("PS cart updateQty product quantity: " . $p['quantity'], ShopgateLogger::LOGTYPE_DEBUG); $this->log("PS cart updateQty product quantity_difference: " . $p['quantity_difference'], ShopgateLogger::LOGTYPE_DEBUG); $this->log("PS cart updateQty product id_product_attribute: " . $p['id_product_attribute'], ShopgateLogger::LOGTYPE_DEBUG); $this->log("PS cart updateQty product delivery address: " . $deliveryAddress->id, ShopgateLogger::LOGTYPE_DEBUG); //TODO deal with customizations $id_customization = false; if ($p['quantity'] - $p['quantity_difference'] > 0) { // only if the result of $p['quantity'] - $p['quantity_difference'] is higher then 0 $cart->updateQty($p['quantity'] - $p['quantity_difference'], $p['id_product'], $p['id_product_attribute'], $id_customization, 'up', $deliveryAddress->id); } if ($p['quantity_difference'] > 0) { $this->log("PS try to add cart message ", ShopgateLogger::LOGTYPE_DEBUG); $message = new Message(); $message->id_cart = $cart->id; $message->private = 1; $message->message = 'Warning, wanted quantity for product "' . $p['name'] . '" was ' . $p['quantity'] . ' unit(s), however, the amount in stock is ' . $p['quantity_in_stock'] . ' unit(s). Only ' . $p['quantity_in_stock'] . ' unit(s) were added to the order'; $message->save(); } } $id_order_state = 0; $shopgate = new Shopgate(); $payment_name = $shopgate->getTranslation('Mobile Payment'); $this->log("PS map payment method", ShopgateLogger::LOGTYPE_DEBUG); if (!$order->getIsShippingBlocked()) { $id_order_state = $this->getOrderStateId('PS_OS_PREPARATION'); switch ($order->getPaymentMethod()) { case 'SHOPGATE': $payment_name = $shopgate->getTranslation('Shopgate'); break; case 'PREPAY': $payment_name = $shopgate->getTranslation('Bankwire'); $id_order_state = $this->getOrderStateId('PS_OS_BANKWIRE'); break; case 'COD': $payment_name = $shopgate->getTranslation('Cash on Delivery'); break; case 'PAYPAL': $payment_name = $shopgate->getTranslation('PayPal'); break; default: break; } } else { $id_order_state = $this->getOrderStateId('PS_OS_SHOPGATE'); switch ($order->getPaymentMethod()) { case 'SHOPGATE': $payment_name = $shopgate->getTranslation('Shopgate'); break; case 'PREPAY': $payment_name = $shopgate->getTranslation('Bankwire'); break; case 'COD': $payment_name = $shopgate->getTranslation('Cash on Delivery'); break; case 'PAYPAL': $id_order_state = $this->getOrderStateId('PS_OS_PAYPAL'); $payment_name = $shopgate->getTranslation('PayPal'); break; default: $id_order_state = $this->getOrderStateId('PS_OS_SHOPGATE'); break; } } $shippingCosts = $order->getAmountShipping() + $order->getAmountShopPayment(); //Creates shopgate order record and save shipping cost for future use $this->log("PS set PSShopgateOrder object variables", ShopgateLogger::LOGTYPE_DEBUG); $shopgateOrder = new PSShopgateOrder(); $shopgateOrder->order_number = $order->getOrderNumber(); $shopgateOrder->shipping_cost = $shippingCosts; $shopgateOrder->shipping_service = Configuration::get('SHOPGATE_SHIPPING_SERVICE'); $shopgateOrder->id_cart = $cart->id; $shopgateOrder->shop_number = $this->config->getShopNumber(); $shopgateOrder->comments = $this->jsonEncode($comments); if (version_compare(_PS_VERSION_, '1.4.0.2', '<')) { $this->log("PS lower 1.4.0.2: ", ShopgateLogger::LOGTYPE_DEBUG); // Fix: sets in database ps_delivery all zones of passed shippingCosts $this->setShippingCosts(0); } $this->log("PS try creating PSShopgateOrder object", ShopgateLogger::LOGTYPE_DEBUG); if (!$shopgateOrder->add()) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create shopgate order', true); } //PS 1.5 compatibility if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) { $this->log("PS 1.5.x.x: set cart context", ShopgateLogger::LOGTYPE_DEBUG); $this->context = Context::getContext(); $this->context->cart = $cart; $this->log("PS 1.5.x.x: \$cart->setDeliveryOption(array(\$cart->id_address_delivery => \$cart->id_carrier.','))\n\n==============", ShopgateLogger::LOGTYPE_DEBUG); $cart->setDeliveryOption(array($cart->id_address_delivery => $cart->id_carrier . ',')); $this->log("PS 1.5.x.x: \$cart->update()", ShopgateLogger::LOGTYPE_DEBUG); $cart->update(); $cart->id_carrier = (int) Configuration::get('SHOPGATE_CARRIER_ID'); } $amountPaid = $order->getAmountComplete(); if (version_compare(_PS_VERSION_, '1.4.0.2', '<')) { // substract the shipping costs. $amountPaid -= $shippingCosts; } $this->log("\$shopgate->validateOrder(\$cart->id, \$id_order_state, \$amountPaid, \$payment_name, NULL, array(), NULL, false, \$cart->secure_key", ShopgateLogger::LOGTYPE_DEBUG); $this->log("\$cart->id = " . var_export($cart->id, true) . "\n\$id_order_state = " . var_export($id_order_state, true) . "\n\$amountPaid = " . var_export($amountPaid, true) . "\n\$payment_name = " . var_export($payment_name, true) . "\n\$cart->secure_key" . var_export($cart->secure_key, true) . "\n==============", ShopgateLogger::LOGTYPE_DEBUG); try { $shopgate->validateOrder($cart->id, $id_order_state, $amountPaid, $payment_name, NULL, array(), NULL, false, $cart->secure_key); } catch (Swift_Message_MimeException $ex) { $this->log("\$shopgate->validateOrder(\$cart->id, \$id_order_state, \$amountPaid, \$payment_name, NULL, array(), NULL, false, \$cart->secure_key) FAILED with Swift_Message_MimeException", ShopgateLogger::LOGTYPE_ERROR); // catch Exception if there is a problem with sending mails } if (version_compare(_PS_VERSION_, '1.4.0.2', '<') && (int) $shopgate->currentOrder > 0) { $this->log("PS < 1.4.0.2: update shipping and payment cost", ShopgateLogger::LOGTYPE_DEBUG); // in versions below 1.4.0.2 the shipping and payment costs must be updated after the order $updateShopgateOrder = new Order($shopgate->currentOrder); $updateShopgateOrder->total_paid = $order->getAmountComplete(); $updateShopgateOrder->total_paid_real = $order->getAmountComplete(); $updateShopgateOrder->total_products_wt = $order->getAmountItems(); $updateShopgateOrder->total_shipping = $order->getAmountShipping() + $order->getAmountShopPayment(); $updateShopgateOrder->update(); } if ((int) $shopgate->currentOrder > 0) { $this->log("\$shopgateOrder->update()", ShopgateLogger::LOGTYPE_DEBUG); $shopgateOrder->id_order = $shopgate->currentOrder; $shopgateOrder->update(); return array('external_order_id' => $shopgate->currentOrder, 'external_order_number' => $shopgate->currentOrder); } else { $this->log("\$shopgateOrder->delete()", ShopgateLogger::LOGTYPE_DEBUG); $shopgateOrder->delete(); throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create order', true); } }
public function add($autodate = true, $null_values = false) { if (!parent::add($autodate)) { return false; } $order = new Order((int) $this->id_order); // Update id_order_state attribute in Order $order->current_state = $this->id_order_state; $order->update(); Hook::exec('actionOrderHistoryAddAfter', array('order_history' => $this), null, false, true, false, $order->id_shop); return true; }
private function _updateTable($params, $expeditionNum, $ticketURL, $trackingURL, $id_mr_selected) { Db::getInstance()->execute(' UPDATE `' . _DB_PREFIX_ . 'mr_selected` SET `MR_poids` = \'' . pSQL($params['Poids']) . '\', `exp_number` = \'' . pSQL($expeditionNum) . '\', `url_etiquette` = \'' . pSQL($ticketURL) . '\', `url_suivi` = \'' . pSQL($trackingURL) . '\' WHERE id_mr_selected = ' . (int) $id_mr_selected); // NDossier contains the id_order $order = new Order($params['NDossier']); // Update the database for order and orderHistory $order->shipping_number = $expeditionNum; $order->update(); $templateVars = array('{followup}' => $trackingURL); $orderState = Configuration::get('PS_OS_SHIPPING') ? Configuration::get('PS_OS_SHIPPING') : _PS_OS_SHIPPING_; $history = new OrderHistory(); $history->id_order = (int) $params['NDossier']; $history->changeIdOrderState($orderState, (int) $params['NDossier']); $history->id_employee = (int) Context::getContext()->employee->id; $history->addWithemail(true, $templateVars); unset($order); unset($history); }
private function _updateTable($params, $expeditionNum, $ticketURL, $trackingURL, $id_mr_selected) { $sql = ' UPDATE `' . _DB_PREFIX_ . 'mr_selected` SET `MR_poids` = \'' . pSQL($params['Poids']) . '\', `MR_insurance` = \'' . pSQL($params['Assurance']) . '\', `exp_number` = \'' . pSQL($expeditionNum) . '\', `url_etiquette` = \'' . pSQL($ticketURL) . '\', `url_suivi` = \'' . pSQL($trackingURL) . '\' WHERE id_mr_selected = ' . (int) $id_mr_selected; Db::getInstance()->execute($sql); // NDossier contains the id_order $order = new Order($params['NDossier']); // Update the database for order and orderHistory $order->shipping_number = $expeditionNum; $order->update(); if (version_compare(_PS_VERSION_, '1.5', '>=')) { //Retrieve Order Carrier $sql = 'SELECT `id_order_carrier` FROM `' . _DB_PREFIX_ . 'order_carrier` WHERE `id_order` = ' . (int) $order->id; $id_order_carrier = Db::getInstance()->getValue($sql); if ($id_order_carrier) { $order_carrier = new OrderCarrier((int) $id_order_carrier); if (Validate::isLoadedObject($order_carrier)) { $order_carrier->tracking_number = pSQL($expeditionNum); $order_carrier->update(); } } } $templateVars = array('{followup}' => $trackingURL); $orderState = Configuration::get('PS_OS_SHIPPING') ? Configuration::get('PS_OS_SHIPPING') : _PS_OS_SHIPPING_; $history = new OrderHistory(); $history->id_order = (int) $params['NDossier']; if (version_compare(_PS_VERSION_, '1.5.2', '>=')) { $history->changeIdOrderState((int) $orderState, $order); } else { $history->changeIdOrderState((int) $orderState, (int) $params['NDossier']); } $history->id_employee = isset(Context::getContext()->employee->id) ? (int) Context::getContext()->employee->id : ''; $history->addWithemail(true, $templateVars); unset($order); unset($order_carrier); unset($history); }
<?php if (isset($_GET['id'])) { $id = (int) $_GET['id']; $obj = new Order($id); } if (Tools::isSubmit('orderStatusUpdate')) { $obj->id_order_status = (int) Tools::getRequest('id_order_status'); if (strlen(trim(Tools::getRequest('track_number'))) > 0) { $obj->track_number = Tools::getRequest('track_number'); Alert::send($obj->id_user, "Your order:#" . sprintf("%09d", intval($obj->id)) . " has been shipped."); } $obj->update(); $obj->order_status = new OrderStatus((int) $obj->id_order_status); } $breadcrumb = new UIAdminBreadcrumb(); $breadcrumb->home(); $breadcrumb->add(array('title' => '定单 #' . sprintf("%09d", $id), 'active' => true)); $bread = $breadcrumb->draw(); $btn_group = array(array('type' => 'button', 'title' => '提交到定单系统', 'id' => 'send-to-order-system', 'class' => 'btn-success', 'icon' => 'wrench'), array('type' => 'a', 'title' => '预览', 'href' => 'index.php?rule=order_view&id=' . $obj->id, 'class' => 'btn-warning', 'icon' => 'eye-open'), array('type' => 'a', 'title' => '返回', 'href' => 'index.php?rule=order', 'class' => 'btn-primary', 'icon' => 'level-up')); echo UIViewBlock::area(array('bread' => $bread, 'btn_groups' => $btn_group), 'breadcrumb'); ?> <div class="order_base_info"> <div style="width: 49%; float:left;"> <fieldset class="small"> <legend><img src="<?php echo $_tmconfig['ico_dir']; ?> tab-customers.gif">用户</legend> <span style="font-weight: bold; font-size: 14px;"><a href="index.php?rule=user_edit&id=<?php
/** * Update order history status with kwixo status given * * @param int $id_order * @param int $psosstatus */ public function updateOrderHistory($id_order, $psosstatus) { $order = new Order((int) $id_order); $orderHistory = new OrderHistory(); $orderHistory->id_order = $id_order; $orderHistory->id_order_state = $psosstatus; $orderHistory->save(); $orderHistory->changeIdOrderState($psosstatus, $id_order); $orderHistory->save(); $order->current_state = $psosstatus; $order->update(); }
/** * @global object $cookie Employee cookie necessary to keep trace of his/her actions */ public function postProcess() { global $currentIndex, $cookie; /* Update shipping number */ if (Tools::isSubmit('submitShippingNumber') and $id_order = intval(Tools::getValue('id_order')) and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { if (!$order->hasBeenShipped()) { die(Tools::displayError('The shipping number can only be set once the order has been shipped!')); } $_GET['view' . $this->table] = true; if (!($shipping_number = pSQL(Tools::getValue('shipping_number')))) { $this->_errors[] = Tools::displayError('Invalid new order status!'); } else { global $_LANGMAIL; $order->shipping_number = $shipping_number; $order->update(); $customer = new Customer(intval($order->id_customer)); $carrier = new Carrier(intval($order->id_carrier)); if (!Validate::isLoadedObject($customer) or !Validate::isLoadedObject($carrier)) { die(Tools::displayError()); } $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => intval($order->id)); $subject = 'Package in transit'; Mail::Send(intval($order->id_lang), 'in_transit', (is_array($_LANGMAIL) and key_exists($subject, $_LANGMAIL)) ? $_LANGMAIL[$subject] : $subject, $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } } elseif (Tools::isSubmit('submitState') and $id_order = intval(Tools::getValue('id_order')) and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { $_GET['view' . $this->table] = true; if (!($newOrderStatusId = intval(Tools::getValue('id_order_state')))) { $this->_errors[] = Tools::displayError('Invalid new order status!'); } else { $history = new OrderHistory(); $history->id_order = $id_order; $history->changeIdOrderState(intval($newOrderStatusId), intval($id_order)); $history->id_employee = intval($cookie->id_employee); $carrier = new Carrier(intval($order->id_carrier), intval($order->id_lang)); $templateVars = array('{followup}' => ($history->id_order_state == _PS_OS_SHIPPING_ and $order->shipping_number) ? str_replace('@', $order->shipping_number, $carrier->url) : ''); if ($history->addWithemail(true, $templateVars)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder' . '&token=' . $this->token); } $this->_errors[] = Tools::displayError('an error occurred while changing status or was unable to send e-mail to the customer'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } } elseif (isset($_POST['submitMessage'])) { $_GET['view' . $this->table] = true; if ($this->tabAccess['edit'] === '1') { if (!($id_order = intval(Tools::getValue('id_order'))) or !($id_customer = intval(Tools::getValue('id_customer')))) { $this->_errors[] = Tools::displayError('an error occurred before sending message'); } elseif (!Tools::getValue('message')) { $this->_errors[] = Tools::displayError('message cannot be blank'); } else { /* Get message rules and and check fields validity */ $rules = call_user_func(array('Message', 'getValidationRules'), 'Message'); foreach ($rules['required'] as $field) { if (($value = Tools::getValue($field)) == false and (string) $value != '0') { if (!Tools::getValue('id_' . $this->table) or $field != 'passwd') { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is required'); } } } foreach ($rules['size'] as $field => $maxLength) { if (Tools::getValue($field) and Tools::strlen(Tools::getValue($field)) > $maxLength) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is too long') . ' (' . $maxLength . ' ' . Tools::displayError('chars max') . ')'; } } foreach ($rules['validate'] as $field => $function) { if (Tools::getValue($field)) { if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is invalid'); } } } if (!sizeof($this->_errors)) { $message = new Message(); $message->id_employee = intval($cookie->id_employee); $message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8'); $message->id_order = $id_order; $message->private = Tools::getValue('visibility'); if (!$message->add()) { $this->_errors[] = Tools::displayError('an error occurred while sending message'); } elseif ($message->private) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } elseif (Validate::isLoadedObject($customer = new Customer($id_customer))) { $order = new Order(intval($message->id_order)); if (Validate::isLoadedObject($order)) { $title = html_entity_decode($this->l('New message regarding your order') . ' ' . $message->id_order, ENT_NOQUOTES, 'UTF-8'); $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : nl2br2($message->message)); if (Mail::Send(intval($order->id_lang), 'order_merchant_comment', $title, $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } } } $this->_errors[] = Tools::displayError('an error occurred while sending e-mail to the customer'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('cancelProduct') and Validate::isLoadedObject($order = new Order(intval(Tools::getValue('id_order'))))) { if ($this->tabAccess['delete'] === '1') { $productList = Tools::getValue('id_order_detail'); $customizationList = Tools::getValue('id_customization'); $qtyList = Tools::getValue('cancelQuantity'); $customizationQtyList = Tools::getValue('cancelCustomizationQuantity'); if ($productList or $customizationList) { if ($productList) { foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } } } if ($customizationList) { foreach ($customizationList as $id_customization => $id_order_detail) { $qtyCancelProduct = abs($customizationQtyList[$id_customization]); if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } } } if (!sizeof($this->_errors) and $productList) { foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); $orderDetail = new OrderDetail(intval($id_order_detail)); // Reinject product if (isset($_POST['reinjectQuantities']) or !$order->hasBeenDelivered() and !$order->hasBeenPaid()) { $reinjectableQuantity = intval($orderDetail->product_quantity_in_stock) - intval($orderDetail->product_quantity_reinjected); $quantityToReinject = $qtyCancelProduct > $reinjectableQuantity ? $reinjectableQuantity : $qtyCancelProduct; if (!Product::reinjectQuantities($orderDetail, $quantityToReinject)) { $this->_errors[] = Tools::displayError('Cannot re-stock product') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } } // Delete product if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct)) { $this->_errors[] = Tools::displayError('an error occurred during deletion for the product') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } Module::hookExec('cancelProduct', array('order' => $order, 'id_order_detail' => $id_order_detail)); } } if (!sizeof($this->_errors) and $customizationList) { foreach ($customizationList as $id_customization => $id_order_detail) { $orderDetail = new OrderDetail(intval($id_order_detail)); $qtyCancelProduct = abs($customizationQtyList[$id_customization]); if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail)) { $this->_errors[] = Tools::displayError('an error occurred during deletion for the product customization') . ' ' . $id_customization; } } } // E-mail params if ((isset($_POST['generateCreditSlip']) or isset($_POST['generateDiscount'])) and !sizeof($this->_errors)) { $customer = new Customer(intval($order->id_customer)); $params['{lastname}'] = $customer->lastname; $params['{firstname}'] = $customer->firstname; $params['{id_order}'] = $order->id; } // Generate credit slip if (isset($_POST['generateCreditSlip']) and !sizeof($this->_errors)) { if (!OrderSlip::createOrderSlip($order, $productList, $qtyList, isset($_POST['shippingBack']))) { $this->_errors[] = Tools::displayError('Cannot generate credit slip'); } else { Module::hookExec('orderSlip', array('order' => $order, 'productList' => $productList, 'qtyList' => $qtyList)); @Mail::Send(intval($order->id_lang), 'credit_slip', html_entity_decode($this->l('New credit slip regarding your order #') . $order->id, ENT_NOQUOTES, 'UTF-8'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } // Generate voucher if (isset($_POST['generateDiscount']) and !sizeof($this->_errors)) { if (!($voucher = Discount::createOrderDiscount($order, $productList, $qtyList, $this->l('Credit Slip concerning the order #'), isset($_POST['shippingBack'])))) { $this->_errors[] = Tools::displayError('Cannot generate voucher'); } else { $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false, false); $params['{voucher_num}'] = $voucher->name; @Mail::Send(intval($order->id_lang), 'voucher', html_entity_decode($this->l('New voucher regarding your order #') . $order->id, ENT_NOQUOTES, 'UTF-8'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } } else { $this->_errors[] = Tools::displayError('No product or quantity selected.'); } // Redirect if no errors if (!sizeof($this->_errors)) { Tools::redirectLink($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=1&token=' . $this->token); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (isset($_GET['messageReaded'])) { Message::markAsReaded(intval($_GET['messageReaded']), intval($cookie->id_employee)); } parent::postProcess(); }
</div> </fieldset> <fieldset class="buttons"> <button type="reset">reset</button> <button type="submit">submit</button> </fieldset> </form> </div>'; } break; case "edit": break; case "view": if (isset($_REQUEST["target"])) { $order = new Order($_REQUEST["target"]); $pageBody .= '<pre>' . $order->save(RETURN_QUERY) . $order->update(RETURN_QUERY) . '</pre>'; } else { $pageBody .= Dialog(DIALOG_ERROR, 'no target specified'); } break; case "delete": break; } break; case "agents": $pageBody = '<h1>agents</h1>'; $action = "list"; if (isset($_REQUEST["action"])) { $action = $_REQUEST["action"]; } switch ($action) {
<?php require_once $_SERVER['DOCUMENT_ROOT'] . "/model/order.php"; require_once $_SERVER['DOCUMENT_ROOT'] . "/model/session.php"; $id = $_POST['id']; $orders = new Order(); $session = new Session(); $order = $orders->find('id', $id); if ($order['user_id'] == $session->get_session_data('id')) { $data = ['address_id' => $_POST['address_id'], 'card_id' => $_POST['card_id'], 'status' => 2]; if ($orders->update('id', $id, $data)) { header('Location: /confirmation.php'); } else { print_r("Something went wrong"); } } else { print_r("Something serious went wrong"); }
<?php include_once "../connection/db.php"; $json = file_get_contents('php://input'); $requests = json_decode($json, true); $action = $requests['action']; $email = $requests['email']; $respose = array(); $respose["success"] = 0; if ($action == "create") { $order = new Order(); $order->create($email, $status); } elseif ($action == "index") { $orders = Order . fetch(); echo json_encode($orders); } elseif ($action == "delete") { $success = Order . deletee($id); $respose["success"] = $success; echo json_encode($respose); } else { $order = new Order(); $success = $order->update($status, $id); $respose["success"] = $success; echo json_encode($respose); } // return response echo json_encode($response);
<?php require_once 'model/session.php'; require_once 'model/order.php'; require_once 'model/restaurant.php'; $session = new Session(); $order = new Order(); $restaurant = new Restaurant(); if (isset($_GET['order-id'])) { $getOrder = $order->find('id', $_GET['order-id']); $getRestaurant = $restaurant->find('id', $getOrder['restaurant_id']); if ($getRestaurant['owner_id'] == $session->get_session_data('id') && $session->get_session_data('user_type') == "restaurant_owner") { $status = intval($getOrder['status']) + 1; $order->update('id', $_GET['order-id'], ['status' => $status]); header('Location: owner-track-order.php'); } else { print_r("Something went wrong"); } } else { print_r("Something went wrong"); }
<?php $paymentObj = new Icepay_PaymentObject(); $paymentObj->setAmount(400)->setCountry("NL")->setLanguage("NL")->setIssuer('ACCEPTGIRO')->setPaymentMethod('AFTERPAY')->setReference("My Sample Website")->setDescription("My Sample Payment")->setCurrency("EUR")->setOrderID('test01'); try { $webservice = Icepay_Api_Webservice::getInstance()->paymentService(); $webservice->setMerchantID(MERCHANTID)->setSecretCode(SECRETCODE); $transactionObj = $webservice->extendedCheckout($paymentObj); $orderID = $transactionObj->getOrderID(); $order = new Order(); // We update the user order so we know he was redirect to icepay $order->update($orderID, array('status' => 'USER_REDIRECTED')); printf('<a href="%s">%s</a>', $transactionObj->getPaymentScreenURL(), 'Pay via icepay'); } catch (Exception $e) { var_dump($e); } /** * Example Order Class */ class Order { public function update($id, $attributes = array()) { // Store this data somewhere } }
/** * Action that gets called before we interface with our payment * method. * * This action is responsible for setting up an order and * saving it into the database (as well as a session) and also then * generating an order summary before the user performs any final * actions needed. * * This action is then mapped directly to the index action of the * Handler for the payment method that was selected by the user * in the "Postage and Payment" form. * */ public function index() { $cart = ShoppingCart::get(); // If shopping cart doesn't exist, redirect to base if (!$cart->getItems()->exists() || $this->getPaymentHandler() === null) { return $this->redirect(Director::BaseURL()); } // Get billing and delivery details and merge into an array $billing_data = Session::get("Commerce.BillingDetailsForm.data"); $delivery_data = Session::get("Commerce.DeliveryDetailsForm.data"); $postage = PostageArea::get()->byID(Session::get('Commerce.PostageID')); if (!$postage || !$billing_data || !$delivery_data) { return $this->redirect(Checkout_Controller::create()->Link()); } // Work out if an order prefix string has been set in siteconfig $config = SiteConfig::current_site_config(); $order_prefix = $config->OrderPrefix ? $config->OrderPrefix . '-' : ''; // Merge billand and delivery data into an array $data = array_merge((array) $billing_data, (array) $delivery_data); // Set discount info $data['DiscountAmount'] = $cart->DiscountAmount(); // Get postage data $data['PostageType'] = $postage->Title; $data['PostageCost'] = $postage->Cost; $data['PostageTax'] = $config->TaxRate > 0 && $postage->Cost > 0 ? (double) $postage->Cost / 100 * $config->TaxRate : 0; // Set status $data['Status'] = 'incomplete'; // Setup an order based on the data from the shopping cart and load data $order = new Order(); $order->update($data); // If user logged in, track it against an order if (Member::currentUserID()) { $order->CustomerID = Member::currentUserID(); } // Write so we can setup our foreign keys $order->write(); // Loop through each session cart item and add that item to the order foreach ($cart->getItems() as $cart_item) { $order_item = new OrderItem(); $order_item->Title = $cart_item->Title; $order_item->SKU = $cart_item->SKU; $order_item->Price = $cart_item->Price; $order_item->Tax = $cart_item->Tax; $order_item->Customisation = serialize($cart_item->Customised); $order_item->Quantity = $cart_item->Quantity; $order_item->write(); $order->Items()->add($order_item); } $order->write(); // Add order to session so our payment handler can process it Session::set("Commerce.Order", $order); $this->payment_handler->setOrder($order); // Get gateway data $return = $this->payment_handler->index(); return $this->customise($return)->renderWith(array("Payment", "Commerce", "Page")); }
public function saveOrder() { $inputShipFrom = Input::get('shipFrom'); $inputShipFrom = $this->jsonToInputArray($inputShipFrom); $inputshipTo = Input::get('shipTo'); $inputshipTo = $this->jsonToInputArray($inputshipTo); $inputItem = Input::get('itemDetail'); $inputItem = $this->jsonToInputArray($inputItem); $inputCompany = Input::get('companyInfo'); $inputCompany = $this->jsonToInputArray($inputCompany); $result = array('errors' => '', 'result' => ''); $foundErrors = false; //validate ship from info. $shipFrom = new ShipFrom(); if ($shipFrom->validate($inputShipFrom) === false) { $foundErrors = true; $messages = $shipFrom->messages(); if (count($messages)) { foreach ($messages as $message) { $result['errors'] .= "<li>{$message}</li>"; } } } //validate ship to information $shipTo = new ShipTo(); if ($shipTo->validate($inputshipTo) === false) { $foundErrors = true; $messages = $shipTo->messages(); if (count($messages)) { foreach ($messages as $message) { $result['errors'] .= "<li>{$message}</li>"; } } } //validate item information $item = new Item(); if ($item->validate($inputItem) === false) { $foundErrors = true; $messages = $item->messages(); if (count($messages)) { foreach ($messages as $message) { $result['errors'] .= "<li>{$message}</li>"; } } } //validate company information $company = new Company(); if ($company->validate($inputCompany) === false) { $foundErrors = true; $messages = $company->messages(); if (count($messages)) { foreach ($messages as $message) { $result['errors'] .= "<li>{$message}</li>"; } } } if ($foundErrors == true) { echo json_encode($result); return; } $data = array('shipFrom' => $inputShipFrom, 'shipTo' => $inputshipTo, 'item' => $inputItem, 'company' => $inputCompany); $action = Input::get('action'); if ($action == 'update') { $orderId = Input::get('order_id'); if (Order::update($orderId, $data) == true) { $result['result'] = 'success'; } else { $result['errors'] = "<li>There was a problem with record update.Please try later.</li>"; } } else { //create new order $newOrderId = Order::insert($data); if (is_numeric($newOrderId) && $newOrderId > 0) { $result['result'] = 'success'; } } echo json_encode($result); }
public function processChangeCarrier() { $id_order = (int) Tools::getValue('id_o'); $id_new_carrier = (int) Tools::getValue('new_carrier'); $price_incl = (double) Tools::getValue('pr_incl'); $price_excl = (double) Tools::getValue('pr_excl'); $order = new Order($id_order); $result = array(); $result['error'] = ''; if ($id_new_carrier == 0) { $result['error'] = $this->l('Error: cannot select carrier'); } else { if ($order->id < 1) { $result['error'] = $this->l('Error: cannot find order'); } else { $total_carrierwt = (double) $order->total_products_wt + (double) $price_incl; $total_carrier = (double) $order->total_products + (double) $price_excl; $order->total_paid = (double) $total_carrierwt; $order->total_paid_tax_incl = (double) $total_carrierwt; $order->total_paid_tax_excl = (double) $total_carrier; $order->total_paid_real = (double) $total_carrierwt; $order->total_shipping = (double) $price_incl; $order->total_shipping_tax_excl = (double) $price_excl; $order->total_shipping_tax_incl = (double) $price_incl; $order->carrier_tax_rate = (double) $order->carrier_tax_rate; $order->id_carrier = (int) $id_new_carrier; if (!$order->update()) { $result['error'] = $this->l('Error: cannot update order'); $result['status'] = false; } else { if ($order->invoice_number > 0) { $order_invoice = new OrderInvoice($order->invoice_number); $order_invoice->total_paid_tax_incl = (double) $total_carrierwt; $order_invoice->total_paid_tax_excl = (double) $total_carrier; $order_invoice->total_shipping_tax_excl = (double) $price_excl; $order_invoice->total_shipping_tax_incl = (double) $price_incl; if (!$order_invoice->update()) { $result['error'] = $this->l('Error: cannot update order invoice'); $result['status'] = false; } } $id_order_carrier = Db::getInstance()->getValue(' SELECT `id_order_carrier` FROM `' . _DB_PREFIX_ . 'order_carrier` WHERE `id_order` = ' . (int) $order->id); if ($id_order_carrier) { $order_carrier = new OrderCarrier($id_order_carrier); $order_carrier->id_carrier = $order->id_carrier; $order_carrier->shipping_cost_tax_excl = (double) $price_excl; $order_carrier->shipping_cost_tax_incl = (double) $price_incl; if (!$order_carrier->update()) { $result['error'] = $this->l('Error: cannot update order carrier'); $result['status'] = false; } } $result['status'] = true; } } } if ($result['status']) { $this->sendCarrierToYandex($order); } return $result; }
public function ajaxProcessEditProductOnOrder() { $res = true; $order = new Order((int) Tools::getValue('id_order')); $order_detail = new OrderDetail((int) Tools::getValue('product_id_order_detail')); if (Tools::isSubmit('product_invoice')) { $order_invoice = new OrderInvoice((int) Tools::getValue('product_invoice')); } $this->doEditProductValidation($order_detail, $order, isset($order_invoice) ? $order_invoice : null); $qty_behavior = PP::qtyBehavior($order_detail, $order_detail->product_quantity) && !is_array(Tools::getValue('product_quantity')); $product_quantity = 0; if (is_array(Tools::getValue('product_quantity'))) { foreach (Tools::getValue('product_quantity') as $id_customization => $qty) { Db::getInstance()->update('customization', array('quantity' => (int) $qty), 'id_customization = ' . (int) $id_customization); $product_quantity += $qty; } } else { $product_quantity = str_replace(',', '.', Tools::getValue('product_quantity')); } $product_price_tax_incl = Tools::ps_round(Tools::getValue('product_price_tax_incl'), 2); $product_price_tax_excl = Tools::ps_round(Tools::getValue('product_price_tax_excl'), 2); $total_products_tax_incl = PP::calcPrice($product_price_tax_incl, $qty_behavior ? $order_detail->product_quantity : $product_quantity, $qty_behavior ? $product_quantity : $order_detail->product_quantity_fractional, $order_detail->product_id); $total_products_tax_excl = PP::calcPrice($product_price_tax_excl, $qty_behavior ? $order_detail->product_quantity : $product_quantity, $qty_behavior ? $product_quantity : $order_detail->product_quantity_fractional, $order_detail->product_id); $diff_price_tax_incl = $total_products_tax_incl - $order_detail->total_price_tax_incl; $diff_price_tax_excl = $total_products_tax_excl - $order_detail->total_price_tax_excl; $ppropertiessmartprice_hook1 = null; if (isset($order_invoice)) { if ($order_detail->id_order_invoice != $order_invoice->id) { $old_order_invoice = new OrderInvoice($order_detail->id_order_invoice); $old_order_invoice->total_products -= $order_detail->total_price_tax_excl; $old_order_invoice->total_products_wt -= $order_detail->total_price_tax_incl; $old_order_invoice->total_paid_tax_excl -= $order_detail->total_price_tax_excl; $old_order_invoice->total_paid_tax_incl -= $order_detail->total_price_tax_incl; $res &= $old_order_invoice->update(); $order_invoice->total_products += $order_detail->total_price_tax_excl; $order_invoice->total_products_wt += $order_detail->total_price_tax_incl; $order_invoice->total_paid_tax_excl += $order_detail->total_price_tax_excl; $order_invoice->total_paid_tax_incl += $order_detail->total_price_tax_incl; $order_detail->id_order_invoice = $order_invoice->id; } } if ($diff_price_tax_incl != 0 && $diff_price_tax_excl != 0) { $order_detail->unit_price_tax_excl = $product_price_tax_excl; $order_detail->unit_price_tax_incl = $product_price_tax_incl; $order_detail->total_price_tax_incl += $diff_price_tax_incl; $order_detail->total_price_tax_excl += $diff_price_tax_excl; if (isset($order_invoice)) { $order_invoice->total_products += $diff_price_tax_excl; $order_invoice->total_products_wt += $diff_price_tax_incl; $order_invoice->total_paid_tax_excl += $diff_price_tax_excl; $order_invoice->total_paid_tax_incl += $diff_price_tax_incl; } $order = new Order($order_detail->id_order); $order->total_products += $diff_price_tax_excl; $order->total_products_wt += $diff_price_tax_incl; $order->total_paid += $diff_price_tax_incl; $order->total_paid_tax_excl += $diff_price_tax_excl; $order->total_paid_tax_incl += $diff_price_tax_incl; $res &= $order->update(); } $old_quantity = PP::resolveQty($order_detail->product_quantity, $order_detail->product_quantity_fractional); if ($qty_behavior) { $order_detail->product_quantity_fractional = $product_quantity; } else { $order_detail->product_quantity = $product_quantity; } $res &= $order_detail->updateTaxAmount($order); $res &= $order_detail->update(); $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier()); if (Validate::isLoadedObject($order_carrier)) { $order_carrier->weight = (double) $order->getTotalWeight(); $res &= $order_carrier->update(); if ($res) { $order->weight = sprintf('%.3f ' . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight); } } if (isset($order_invoice)) { $res &= $order_invoice->update(); } StockAvailable::updateQuantity($order_detail->product_id, $order_detail->product_attribute_id, $old_quantity - PP::resolveQty($order_detail->product_quantity, $order_detail->product_quantity_fractional), $order->id_shop); $products = $this->getProducts($order); $product = $products[$order_detail->id]; $resume = OrderSlip::getProductSlipResume($order_detail->id); $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity']; $product['amount_refundable'] = $product['total_price_tax_excl'] - $resume['amount_tax_excl']; $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']); $product['refund_history'] = OrderSlip::getProductSlipDetail($order_detail->id); if ($product['id_warehouse'] != 0) { $warehouse = new Warehouse((int) $product['id_warehouse']); $product['warehouse_name'] = $warehouse->name; } else { $product['warehouse_name'] = '--'; } $invoice_collection = $order->getInvoicesCollection(); $invoice_array = array(); foreach ($invoice_collection as $invoice) { $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop); $invoice_array[] = $invoice; } $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))); if (!$res) { die(Tools::jsonEncode(array('result' => $res, 'error' => Tools::displayError('An error occurred while editing the product line.')))); } if (is_array(Tools::getValue('product_quantity'))) { $view = $this->createTemplate('_customized_data.tpl')->fetch(); } else { $view = $this->createTemplate('_product_line.tpl')->fetch(); } $this->sendChangedNotification($order); die(Tools::jsonEncode(array('result' => $res, 'view' => $view, 'can_edit' => $this->tabAccess['add'], 'invoices_collection' => $invoice_collection, 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'customized_product' => is_array(Tools::getValue('product_quantity'))))); }
private function addShippingNumber($id_order, $shipping_number) { $order = new Order((int) $id_order); $order->shipping_number = $shipping_number; $order->update(); if ($shipping_number) { $customer = new Customer((int) $order->id_customer); $carrier = new Carrier((int) $order->id_carrier); if (!Validate::isLoadedObject($customer) || !Validate::isLoadedObject($carrier)) { self::$errors[] = $this->l('Customer / Carrier not found'); return false; } $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{order_name}' => sprintf('#%06d', (int) $order->id), '{id_order}' => (int) $order->id); @Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_); } return true; }
$page->startBody(); $update = null; $control = new Controls(Controls::Insert); //Chưa chọn loại sản phẩm; $Order = new Order(); $maxTotal = Order::getValueMaxColName('Total'); $maxTotal = empty($maxTotal) ? 0 : ceil($maxTotal / 1000000); // /1 triệu đồng if (isset($_POST["btnSave"])) { if (isset($_POST["txtOrderID"])) { $Order->setOrderID($_POST["txtOrderID"]); } if (isset($_POST["cboStatus"])) { $Order->setStatus(new Status($_POST["cboStatus"])); } $Order->update(); $update = true; } else { if (isset($_GET["OrderID"]) && isset($_GET["control"])) { $Order = Order::getOrder($_GET["OrderID"]); if ($Order != null) { echo "<script> \$(function () { \$(window).load(function(){ \$('#modalOrder').modal( { backdrop: 'static', keyboard: false }, 'show');}); });</script>"; } else { require_once '../helper/Utils.php'; $url = "orders.php"; Utils::Redirect($url); } } } ?> <div class="page-header">
<?php require '../includes/functions.php'; require 'templates/header.php'; if (isset($_GET['logout']) && $_GET['logout'] == "true") { $session->logout(); } if (isset($_POST['submit'])) { foreach ($_POST['orders'] as $order) { $orderObj = new Order(); $orderObj->id = $order; $orderObj->served = 1; $orderObj->date = ''; $orderObj->update(); } } require 'templates/navbar.php'; ?> <div class="row" style="margin-right: 0"> <div class="col-md-8 col-md-offset-2 page-wrapper"> <h2>Orders To Be Served Today<a id="hideButton" class="btn btn-info pull-right" data-toggle="collapse" data-target="#orderTable">Hide</a></h2> <hr> <?php $sql = "SELECT menu_item.name, SUM(orders.quantity) AS quantity from orders " . "INNER JOIN menu_item " . "ON menu_item.id = orders.menu_item_id " . "WHERE orders.date = '" . today() . "' AND orders.served = '0'" . "GROUP BY menu_item.name"; $name_link = "name-asc"; $quantity_link = "quantity-asc"; if (isset($_GET['by'])) { switch ($_GET['by']) { case 'name-asc': $name_link = 'name-desc'; $sql .= ' ORDER BY menu_item.name ASC';
/** * @global object $cookie Employee cookie necessary to keep trace of his/her actions */ public function postProcess() { global $currentIndex, $cookie; /* Update shipping number */ if (Tools::isSubmit('submitShippingNumber') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { if (!$order->hasBeenShipped()) { die(Tools::displayError('The shipping number can only be set once the order has been shipped.')); } $_GET['view' . $this->table] = true; $shipping_number = pSQL(Tools::getValue('shipping_number')); $order->shipping_number = $shipping_number; $order->update(); if ($shipping_number) { global $_LANGMAIL; $customer = new Customer((int) $order->id_customer); $carrier = new Carrier((int) $order->id_carrier); if (!Validate::isLoadedObject($customer) or !Validate::isLoadedObject($carrier)) { die(Tools::displayError()); } $templateVars = array('{order_amount}' => Tools::displayPrice($order->total_paid, $currency, false), '{carrier_name}' => $carrier->name, '{tracking_number}' => $order->shipping_number, '{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => (int) $order->id); if (strpos($order->payment, 'COD') === false) { @Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Your order #' . $order->id . ' with IndusDiva.com has been shipped'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname); } else { @Mail::Send((int) $order->id_lang, 'in_transit_cod', Mail::l('Your order #' . $order->id . ' with IndusDiva.com has been shipped'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname); } //Send SMS $delivery = new Address((int) $order->id_address_delivery); if (strpos($order->payment, 'COD') === false) { $smsText = 'Dear customer, your order #' . $order->id . ' at IndusDiva.com has been shipped via ' . $carrier->name . '. The airway bill no is ' . $order->shipping_number . '. www.indusdiva.com'; } else { $smsText = 'Dear customer, your order #' . $order->id . ' at IndusDiva.com has been shipped. Carrier: ' . $carrier->name . ', AWB No. : ' . $order->shipping_number . ', Amount payable:' . Tools::displayPrice($order->total_paid, $currency, false) . '. www.indusdiva.com'; } Tools::sendSMS($delivery->phone_mobile, $smsText); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitExpectedShippingDate') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { $dateshipping = new DateTime(Tools::getValue('expected_shipping_date')); $order->expected_shipping_date = pSQL($dateshipping->format('Y-m-d H:i:s')); $order->update(); $order = new Order($id_order); } elseif (Tools::isSubmit('submitCarrier') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { $order->shipping_number = ''; $order->id_carrier = (int) Tools::getValue('id_carrier'); $order->update(); $order = new Order($id_order); } elseif (Tools::isSubmit('submitState') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { $_GET['view' . $this->table] = true; if (!($newOrderStatusId = (int) Tools::getValue('id_order_state'))) { $this->_errors[] = Tools::displayError('Invalid new order status'); } else { if ($newOrderStatusId == _PS_OS_DELIVERED_ && strpos($order->payment, 'COD')) { $paymentHistory = new OrderPaymentHistory(); $paymentHistory->id_order = (int) $id_order; $paymentHistory->id_employee = (int) $cookie->id_employee; $paymentHistory->changeIdOrderPaymentState(_PS_PS_PAYMENT_WITH_CARRIER_, (int) $id_order); $paymentHistory->addState(); } $history = new OrderHistory(); $history->id_order = (int) $id_order; $history->id_employee = (int) $cookie->id_employee; $history->changeIdOrderState((int) $newOrderStatusId, (int) $id_order); $order = new Order((int) $order->id); $carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang); $templateVars = array(); if ($history->id_order_state == _PS_OS_SHIPPING_ and $order->shipping_number) { $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url)); } elseif ($history->id_order_state == _PS_OS_CHEQUE_) { $templateVars = array('{cheque_name}' => Configuration::get('CHEQUE_NAME') ? Configuration::get('CHEQUE_NAME') : '', '{cheque_address_html}' => Configuration::get('CHEQUE_ADDRESS') ? nl2br(Configuration::get('CHEQUE_ADDRESS')) : ''); } elseif ($history->id_order_state == _PS_OS_BANKWIRE_) { $templateVars = array('{bankwire_owner}' => Configuration::get('BANK_WIRE_OWNER') ? Configuration::get('BANK_WIRE_OWNER') : '', '{bankwire_details}' => Configuration::get('BANK_WIRE_DETAILS') ? nl2br(Configuration::get('BANK_WIRE_DETAILS')) : '', '{bankwire_address}' => Configuration::get('BANK_WIRE_ADDRESS') ? nl2br(Configuration::get('BANK_WIRE_ADDRESS')) : ''); } if ($history->id_order_state == _PS_OS_CANCELED_) { $this->cancelOrder($id_order); } if ($history->addWithemail(true, $templateVars)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder' . '&token=' . $this->token); } $this->_errors[] = Tools::displayError('An error occurred while changing the status or was unable to send e-mail to the customer.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_POST['submitMessage'])) { $_GET['view' . $this->table] = true; if ($this->tabAccess['edit'] === '1') { if (!($id_order = (int) Tools::getValue('id_order')) or !($id_customer = (int) Tools::getValue('id_customer'))) { $this->_errors[] = Tools::displayError('An error occurred before sending message'); } elseif (!Tools::getValue('message')) { $this->_errors[] = Tools::displayError('Message cannot be blank'); } else { /* Get message rules and and check fields validity */ $rules = call_user_func(array('Message', 'getValidationRules'), 'Message'); foreach ($rules['required'] as $field) { if (($value = Tools::getValue($field)) == false and (string) $value != '0') { if (!Tools::getValue('id_' . $this->table) or $field != 'passwd') { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is required.'); } } } foreach ($rules['size'] as $field => $maxLength) { if (Tools::getValue($field) and Tools::strlen(Tools::getValue($field)) > $maxLength) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is too long.') . ' (' . $maxLength . ' ' . Tools::displayError('chars max') . ')'; } } foreach ($rules['validate'] as $field => $function) { if (Tools::getValue($field)) { if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is invalid.'); } } } if (!sizeof($this->_errors)) { $message = new Message(); $message->id_employee = (int) $cookie->id_employee; $message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8'); $message->id_order = $id_order; $message->private = Tools::getValue('visibility'); if (!$message->add()) { $this->_errors[] = Tools::displayError('An error occurred while sending message.'); } elseif ($message->private) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } elseif (Validate::isLoadedObject($customer = new Customer($id_customer))) { $order = new Order((int) $message->id_order); if (Validate::isLoadedObject($order)) { $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : nl2br2($message->message)); if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order'), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } } } $this->_errors[] = Tools::displayError('An error occurred while sending e-mail to customer.'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('cancelProduct') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) { if ($this->tabAccess['delete'] === '1') { $productList = Tools::getValue('id_order_detail'); $customizationList = Tools::getValue('id_customization'); $qtyList = Tools::getValue('cancelQuantity'); $customizationQtyList = Tools::getValue('cancelCustomizationQuantity'); $full_product_list = $productList; $full_quantity_list = $qtyList; if ($customizationList) { foreach ($customizationList as $key => $id_order_detail) { $full_product_list[$id_order_detail] = $id_order_detail; $full_quantity_list[$id_order_detail] = $customizationQtyList[$key]; } } if ($productList or $customizationList) { if ($productList) { $id_cart = Cart::getCartIdByOrderId($order->id); $customization_quantities = Customization::countQuantityByCart($id_cart); foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } // check actionable quantity $order_detail = new OrderDetail($id_order_detail); $customization_quantity = 0; if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) { $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id]; } if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) { $this->_errors[] = Tools::displayError('Invalid quantity selected for product.'); } } } if ($customizationList) { $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList)); foreach ($customizationList as $id_customization => $id_order_detail) { $qtyCancelProduct = abs($customizationQtyList[$id_customization]); $customization_quantity = $customization_quantities[$id_customization]; if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) { $this->_errors[] = Tools::displayError('Invalid quantity selected for product.'); } } } if (!sizeof($this->_errors) and $productList) { foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); $orderDetail = new OrderDetail((int) $id_order_detail); // Reinject product if (!$order->hasBeenDelivered() or $order->hasBeenDelivered() and Tools::isSubmit('reinjectQuantities')) { $reinjectableQuantity = (int) $orderDetail->product_quantity - (int) $orderDetail->product_quantity_reinjected; $quantityToReinject = $qtyCancelProduct > $reinjectableQuantity ? $reinjectableQuantity : $qtyCancelProduct; if (!Product::reinjectQuantities($orderDetail, $quantityToReinject)) { $this->_errors[] = Tools::displayError('Cannot re-stock product') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } else { $updProductAttributeID = !empty($orderDetail->product_attribute_id) ? (int) $orderDetail->product_attribute_id : NULL; $newProductQty = Product::getQuantity((int) $orderDetail->product_id, $updProductAttributeID); $product = get_object_vars(new Product((int) $orderDetail->product_id, false, (int) $cookie->id_lang)); if (!empty($orderDetail->product_attribute_id)) { $updProduct['quantity_attribute'] = (int) $newProductQty; $product['quantity_attribute'] = $updProduct['quantity_attribute']; } else { $updProduct['stock_quantity'] = (int) $newProductQty; $product['stock_quantity'] = $updProduct['stock_quantity']; } Hook::updateQuantity($product, $order); } } // Delete product if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct)) { $this->_errors[] = Tools::displayError('An error occurred during deletion of the product.') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } Module::hookExec('cancelProduct', array('order' => $order, 'id_order_detail' => $id_order_detail)); } } if (!sizeof($this->_errors) and $customizationList) { foreach ($customizationList as $id_customization => $id_order_detail) { $orderDetail = new OrderDetail((int) $id_order_detail); $qtyCancelProduct = abs($customizationQtyList[$id_customization]); if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail)) { $this->_errors[] = Tools::displayError('An error occurred during deletion of product customization.') . ' ' . $id_customization; } } } // E-mail params if ((isset($_POST['generateCreditSlip']) or isset($_POST['generateDiscount'])) and !sizeof($this->_errors)) { $customer = new Customer((int) $order->id_customer); $params['{lastname}'] = $customer->lastname; $params['{firstname}'] = $customer->firstname; $params['{id_order}'] = $order->id; } // Generate credit slip if (isset($_POST['generateCreditSlip']) and !sizeof($this->_errors)) { if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, isset($_POST['shippingBack']))) { $this->_errors[] = Tools::displayError('Cannot generate credit slip'); } else { Module::hookExec('orderSlip', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list)); @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } // Generate voucher if (isset($_POST['generateDiscount']) and !sizeof($this->_errors)) { if (!($voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Credit Slip concerning the order #'), isset($_POST['shippingBack'])))) { $this->_errors[] = Tools::displayError('Cannot generate voucher'); } else { $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); $params['{voucher_num}'] = $voucher->name; @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } } else { $this->_errors[] = Tools::displayError('No product or quantity selected.'); } // Redirect if no errors if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('updateOrder') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) { $cart = Cart::getCartByOrderId($order->id); $update = false; if ($discountValue = Tools::getValue('addDiscount')) { $discountVoucher = new Discount(); $discountVoucher->name = 'ADMIND-' . $order->id . date('mdHis'); $discountVoucher->id_discount_type = 2; $discountVoucher->id_customer = $order->id_customer; $discountVoucher->cumulable = 1; $discountVoucher->cumulable_reduction = 1; $discountVoucher->date_from = $order->date_add; $discountVoucher->date_to = date('Y-m-d', time() + 86400); $discountVoucher->quantity = 1; $discountVoucher->quantity_per_user = 1; $discountVoucher->value = (double) $discountValue; $discountVoucher->minimal = 0; $discountVoucher->id_currency = 4; $discountVoucher->behavior_not_exhausted = 1; $discountVoucher->add(true); $cart->addDiscount($discountVoucher->id); $order->addDiscount($discountVoucher->id, $discountVoucher->name, $discountVoucher->value); $cart->update(); $update = true; } //waive shipping, create a free shipping voucher, apply, reload the order object if (Tools::getValue('waiveShipping')) { $freeShipVoucher = new Discount(); $freeShipVoucher->name = 'ADMINFS-' . $order->id . date('mdHis'); $freeShipVoucher->id_discount_type = 3; $freeShipVoucher->id_customer = $order->id_customer; $freeShipVoucher->cumulable = 1; $freeShipVoucher->cumulable_reduction = 1; $freeShipVoucher->date_from = $order->date_add; $freeShipVoucher->date_to = date('Y-m-d', time() + 86400); $freeShipVoucher->quantity = 0; $freeShipVoucher->quantity_per_user = 1; $freeShipVoucher->value = 0; $freeShipVoucher->add(true); $cart->addDiscount($freeShipVoucher->id); $order->addDiscount($freeShipVoucher->id, $freeShipVoucher->name, $freeShipVoucher->value); $cart->update(); $update = true; } $id_product = false; if ($id_product = Tools::getValue('addProductID')) { $product = new Product((int) $id_product, true, (int) $cookie->id_lang); if ($product->quantity > 0 && $product->available_for_order) { $cart->updateQty(1, $id_product); } $orderDetail = null; $db = Db::getInstance(); $res = $db->getRow('select id_order_detail from ps_order_detail where id_order = ' . $order->id . ' and product_id = ' . $id_product); $vat_address = new Address((int) $order->id_address_delivery); $customer = new Customer((int) $order->id_customer); $unitPrice = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); if ($res) { $orderDetail = new OrderDetail($res['id_order_detail']); $orderDetail->product_quantity = $orderDetail->product_quantity + 1; } else { $productName = $product->name; $orderDetail = new OrderDetail(); $orderDetail->product_quantity = 1; $orderDetail->id_order = $order->id; $orderDetail->product_id = $id_product; $orderDetail->product_name = $productName; $orderDetail->product_ean13 = $product->ean13; $price = Product::getPriceStatic($id_product, false, NULL, 6, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $tax_rate = Tax::getProductTaxRate((int) $id_product, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $specificPrice = 0; $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $id_product, Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, $orderDetail->product_quantity); $orderDetail->product_price = (double) Product::getPriceStatic((int) $id_product, false, NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE); $orderDetail->product_quantity_discount = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0; $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0); $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0); $orderDetail->tax_rate = $tax_rate; $orderDetail->tax_name = 'default_tax'; $orderDetail->group_reduction = 0; $orderDetail->product_quantity_in_stock = (int) Product::getQuantity((int) $id_product, NULL); $orderDetail->product_quantity_refunded = 0; $orderDetail->product_quantity_reinjected = 0; $orderDetail->ecotax = 0; $orderDetail->ecotax_tax_rate = 0; $orderDetail->discount_quantity_applied = 0; $orderDetail->add(true, true); } $price = Product::getPriceStatic($id_product, false, NULL, 6, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $tax_rate = Tax::getProductTaxRate((int) $id_product, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $id_product, Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, $orderDetail->product_quantity); $orderDetail->product_price = (double) Product::getPriceStatic((int) $id_product, false, NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE); $orderDetail->product_quantity_discount = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0; $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0); $orderDetail->reduction_amount = (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0); $orderDetail->update(); $product->addStockMvt(-1, _STOCK_MOVEMENT_ORDER_REASON_, NULL, $order->id, (int) $cookie->id_employee); $update = true; } if ($update) { //Recalculate product prices with and without tax from order detail $detailIds = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' SELECT id_order_detail FROM `' . _DB_PREFIX_ . 'order_detail` od WHERE od.`id_order` = ' . (int) $order->id); $totalProducts = 0.0; $totalProductsWT = 0.0; foreach ($detailIds as $id) { $reduction_amount = 0.0; $orderDetail = new OrderDetail($id['id_order_detail']); $price = $orderDetail->product_price * (1 + $orderDetail->tax_rate * 0.01); if ($orderDetail->reduction_percent != 0.0) { $reduction_amount = $price * $orderDetail->reduction_percent / 100; } elseif ($orderDetail->reduction_amount != 0.0) { $reduction_amount = Tools::ps_round($orderDetail->reduction_amount, 2); } if (isset($reduction_amount) and $reduction_amount) { $price = Tools::ps_round($price - $reduction_amount, 2); } $productPriceWithoutTax = $price / (1 + $orderDetail->tax_rate * 0.01); //Update order $totalProducts += $orderDetail->product_quantity * $productPriceWithoutTax; $totalProductsWT += $orderDetail->product_quantity * $price; } $order->total_products = Tools::ps_round($totalProducts, 2); $order->total_products_wt = Tools::ps_round($totalProductsWT, 2); $order->total_shipping = $cart->getOrderShippingCost(); //$order->total_products = $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order->total_discounts = abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $order->total_paid = $order->total_products_wt + $order->total_shipping - $order->total_discounts + $order->total_cod; $order->total_paid_real = $order->total_products_wt + $order->total_shipping - $order->total_discounts + $order->total_cod; //$order->total_products_wt = (float)($cart->getOrderTotal(true, Cart::ONLY_PRODUCTS)); $order->update(); } // Redirect if no errors if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token); } } elseif (isset($_GET['messageReaded'])) { Message::markAsReaded((int) $_GET['messageReaded'], (int) $cookie->id_employee); } parent::postProcess(); }
// $ret['msg'] = '40002:'.$texts['email_repeat_error_1']; // die(json_encode($ret)); // } // } // $check_ret = Attendee::check_email_exists($activity_id, $attendee_data['email']); // if ($check_ret['r'] == 'error') { // $ret['r'] = 'error'; // $ret['msg'] = '40002:'.$attendee_data['email'].' '.$texts['email_repeat_error_2']; // die(json_encode($ret)); // } ##禁止修改email // if (isset($attendees_data[$key]['email'])) { // unset($attendees_data[$key]['email']); // } $attendees_data[$key]['company'] = $order_data['company_name']; } //更新订单 $update_ret = $order->update($write_order); if ($update_ret['r'] == 'error') { die(json_encode($update_ret)); } //更新参会者 for ($i = 0; $i < count($attendees_data); $i++) { $update_ret = $attendees[$i]->update($attendees_data[$i]); if ($update_ret['r'] == 'error') { die(json_encode($update_ret)); } } $ret['r'] = 'ok'; die(json_encode($ret)); }
/** * @global object $cookie Employee cookie necessary to keep trace of his/her actions */ public function postProcess() { global $currentIndex, $cookie; /* Update shipping number */ if (Tools::isSubmit('submitShippingNumber') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { if (!$order->hasBeenShipped()) { die(Tools::displayError('The shipping number can only be set once the order has been shipped.')); } $_GET['view' . $this->table] = true; $shipping_number = pSQL(Tools::getValue('shipping_number')); $order->shipping_number = $shipping_number; $order->update(); if ($shipping_number) { global $_LANGMAIL; $customer = new Customer((int) $order->id_customer); $carrier = new Carrier((int) $order->id_carrier); if (!Validate::isLoadedObject($customer) or !Validate::isLoadedObject($carrier)) { die(Tools::displayError()); } $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => (int) $order->id); @Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitState') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { $_GET['view' . $this->table] = true; if (!($newOrderStatusId = (int) Tools::getValue('id_order_state'))) { $this->_errors[] = Tools::displayError('Invalid new order status'); } else { $history = new OrderHistory(); $history->id_order = (int) $id_order; $history->id_employee = (int) $cookie->id_employee; $history->changeIdOrderState((int) $newOrderStatusId, (int) $id_order); $order = new Order((int) $order->id); $carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang); $templateVars = array(); if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') and $order->shipping_number) { $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url)); } elseif ($history->id_order_state == Configuration::get('PS_OS_CHEQUE')) { $templateVars = array('{cheque_name}' => Configuration::get('CHEQUE_NAME') ? Configuration::get('CHEQUE_NAME') : '', '{cheque_address_html}' => Configuration::get('CHEQUE_ADDRESS') ? nl2br(Configuration::get('CHEQUE_ADDRESS')) : ''); } elseif ($history->id_order_state == Configuration::get('PS_OS_BANKWIRE')) { $templateVars = array('{bankwire_owner}' => Configuration::get('BANK_WIRE_OWNER') ? Configuration::get('BANK_WIRE_OWNER') : '', '{bankwire_details}' => Configuration::get('BANK_WIRE_DETAILS') ? nl2br(Configuration::get('BANK_WIRE_DETAILS')) : '', '{bankwire_address}' => Configuration::get('BANK_WIRE_ADDRESS') ? nl2br(Configuration::get('BANK_WIRE_ADDRESS')) : ''); } if ($history->addWithemail(true, $templateVars)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder' . '&token=' . $this->token); } $this->_errors[] = Tools::displayError('An error occurred while changing the status or was unable to send e-mail to the customer.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_POST['submitMessage'])) { $_GET['view' . $this->table] = true; if ($this->tabAccess['edit'] === '1') { if (!($id_order = (int) Tools::getValue('id_order')) or !($id_customer = (int) Tools::getValue('id_customer'))) { $this->_errors[] = Tools::displayError('An error occurred before sending message'); } elseif (!Tools::getValue('message')) { $this->_errors[] = Tools::displayError('Message cannot be blank'); } else { /* Get message rules and and check fields validity */ $rules = call_user_func(array('Message', 'getValidationRules'), 'Message'); foreach ($rules['required'] as $field) { if (($value = Tools::getValue($field)) == false and (string) $value != '0') { if (!Tools::getValue('id_' . $this->table) or $field != 'passwd') { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is required.'); } } } foreach ($rules['size'] as $field => $maxLength) { if (Tools::getValue($field) and Tools::strlen(Tools::getValue($field)) > $maxLength) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is too long.') . ' (' . $maxLength . ' ' . Tools::displayError('chars max') . ')'; } } foreach ($rules['validate'] as $field => $function) { if (Tools::getValue($field)) { if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is invalid.'); } } } if (!sizeof($this->_errors)) { $message = new Message(); $message->id_employee = (int) $cookie->id_employee; $message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8'); $message->id_order = $id_order; $message->private = Tools::getValue('visibility'); if (!$message->add()) { $this->_errors[] = Tools::displayError('An error occurred while sending message.'); } elseif ($message->private) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } elseif (Validate::isLoadedObject($customer = new Customer($id_customer))) { $order = new Order((int) $message->id_order); if (Validate::isLoadedObject($order)) { $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : nl2br2($message->message)); if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order'), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } } } $this->_errors[] = Tools::displayError('An error occurred while sending e-mail to customer.'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('cancelProduct') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) { if ($this->tabAccess['delete'] === '1') { $productList = Tools::getValue('id_order_detail'); $customizationList = Tools::getValue('id_customization'); $qtyList = Tools::getValue('cancelQuantity'); $customizationQtyList = Tools::getValue('cancelCustomizationQuantity'); $full_product_list = $productList; $full_quantity_list = $qtyList; if ($customizationList) { foreach ($customizationList as $key => $id_order_detail) { $full_product_list[$id_order_detail] = $id_order_detail; $full_quantity_list[$id_order_detail] = $customizationQtyList[$key]; } } if ($productList or $customizationList) { if ($productList) { $id_cart = Cart::getCartIdByOrderId($order->id); $customization_quantities = Customization::countQuantityByCart($id_cart); foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } // check actionable quantity $order_detail = new OrderDetail($id_order_detail); $customization_quantity = 0; if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) { $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id]; } if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) { $this->_errors[] = Tools::displayError('Invalid quantity selected for product.'); } } } if ($customizationList) { $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList)); foreach ($customizationList as $id_customization => $id_order_detail) { $qtyCancelProduct = abs($customizationQtyList[$id_customization]); $customization_quantity = $customization_quantities[$id_customization]; if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) { $this->_errors[] = Tools::displayError('Invalid quantity selected for product.'); } } } if (!sizeof($this->_errors) and $productList) { foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); $orderDetail = new OrderDetail((int) $id_order_detail); // Reinject product if (!$order->hasBeenDelivered() or $order->hasBeenDelivered() and Tools::isSubmit('reinjectQuantities')) { $reinjectableQuantity = (int) $orderDetail->product_quantity - (int) $orderDetail->product_quantity_reinjected; $quantityToReinject = $qtyCancelProduct > $reinjectableQuantity ? $reinjectableQuantity : $qtyCancelProduct; if (!Product::reinjectQuantities($orderDetail, $quantityToReinject)) { $this->_errors[] = Tools::displayError('Cannot re-stock product') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } else { $updProductAttributeID = !empty($orderDetail->product_attribute_id) ? (int) $orderDetail->product_attribute_id : NULL; $newProductQty = Product::getQuantity((int) $orderDetail->product_id, $updProductAttributeID); $product = get_object_vars(new Product((int) $orderDetail->product_id, false, (int) $cookie->id_lang)); if (!empty($orderDetail->product_attribute_id)) { $updProduct['quantity_attribute'] = (int) $newProductQty; $product['quantity_attribute'] = $updProduct['quantity_attribute']; } else { $updProduct['stock_quantity'] = (int) $newProductQty; $product['stock_quantity'] = $updProduct['stock_quantity']; } Hook::updateQuantity($product, $order); } } // Delete product if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct)) { $this->_errors[] = Tools::displayError('An error occurred during deletion of the product.') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } Module::hookExec('cancelProduct', array('order' => $order, 'id_order_detail' => $id_order_detail)); } } if (!sizeof($this->_errors) and $customizationList) { foreach ($customizationList as $id_customization => $id_order_detail) { $orderDetail = new OrderDetail((int) $id_order_detail); $qtyCancelProduct = abs($customizationQtyList[$id_customization]); if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail)) { $this->_errors[] = Tools::displayError('An error occurred during deletion of product customization.') . ' ' . $id_customization; } } } // E-mail params if ((isset($_POST['generateCreditSlip']) or isset($_POST['generateDiscount'])) and !sizeof($this->_errors)) { $customer = new Customer((int) $order->id_customer); $params['{lastname}'] = $customer->lastname; $params['{firstname}'] = $customer->firstname; $params['{id_order}'] = $order->id; } // Generate credit slip if (isset($_POST['generateCreditSlip']) and !sizeof($this->_errors)) { if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, isset($_POST['shippingBack']))) { $this->_errors[] = Tools::displayError('Cannot generate credit slip'); } else { Module::hookExec('orderSlip', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list)); @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order', $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true); } } // Generate voucher if (isset($_POST['generateDiscount']) and !sizeof($this->_errors)) { if (!($voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Credit Slip concerning the order #'), isset($_POST['shippingBack'])))) { $this->_errors[] = Tools::displayError('Cannot generate voucher'); } else { $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); $params['{voucher_num}'] = $voucher->name; @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true); } } } else { $this->_errors[] = Tools::displayError('No product or quantity selected.'); } // Redirect if no errors if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (isset($_GET['messageReaded'])) { Message::markAsReaded((int) $_GET['messageReaded'], (int) $cookie->id_employee); } parent::postProcess(); }
<?php $status = Utils::getUrlParam('status'); $cmd = Utils::getUrlParam('cmd'); $order = Utils::getUserByGetId(); $order->setStatus($cmd); $dao = new Order(); $dao->update($order); $msg = ''; if ($cmd === Order::VOIDED) { $smg = 'Flight booking deleted successfully.'; } else { $smg = 'order changed successfully.'; } Flash::addFlash($smg); Utils::redirect('dashboard', array('status' => $status));
public function getShippingLabel($id_order) { if (is_array($this->_response['errors']) && !count($this->_response['errors'])) { $this->_request = $this->buildLabelRequest(); $error_code = null; do { $this->_post_response = $this->curl_post($this->_dhl_post_url, $this->_request); $this->_xml = @simplexml_load_string($this->_post_response); if ($this->_xml === false) { $this->_xml = @simplexml_load_string(utf8_encode($this->_post_response)); } $error_code = @$this->_xml->GetCapabilityResponse->Note->Condition->ConditionCode; $date = date('Y-m-d', strtotime('+1 day', strtotime(date('Y-m-d')))); } while ($error_code == '1003'); //do while error will be non "Pick-up service is not provided on this day." /** IF TIME OUT ERROR */ if ($this->_post_response == 28) { $this->_error = $this->l('[Error #28] Time out error. The request took more than the time limit of execution'); $this->_error = array(0, $this->_error); } elseif ($this->_xml->Response->Status->Condition) { $this->_error = strlen($this->_xml->Response->Status->Condition->ConditionData) ? $this->_xml->Response->Status->Condition->ConditionData : $this->_xml->Response->Status->Condition->ConditionCode; $this->_error = array(0, $this->_error); } else { $this->_response[] = $this->_xml; $this->_trackingIdType = $this->_dhl_label_infos['ShippingType']; //the same for all packages, shipping method $this->_tracking_numbers[] = (string) $this->_xml->Pieces->Piece->LicensePlate; } } else { $this->_response[0] = 0; return $this->_response; } //if some request failed but before it were successful requests, we need to cancel all successful requests if ($this->_error) { return $this->_error; } //if success if ((int) $this->_dhl_label_order_status > 0) { $history = new OrderHistory(); $history->id_order = (int) $id_order; $history->changeIdOrderState($this->_dhl_label_order_status, $id_order); $history->addWithemail(); } //saving tracking number $order = new Order($id_order); $order->shipping_number = implode(', ', $this->_tracking_numbers); $order->update(); $id_order_carrier = Db::getInstance()->getValue(' SELECT `id_order_carrier` FROM `' . _DB_PREFIX_ . 'order_carrier` WHERE `id_order` = ' . (int) $order->id); if ($id_order_carrier) { $order_carrier = new OrderCarrier($id_order_carrier); $order_carrier->tracking_number = implode(', ', $this->_tracking_numbers); $order_carrier->update(); } //sending email to customer if ($order->shipping_number) { global $_LANGMAIL; $customer = new Customer((int) $order->id_customer); $carrier = new Carrier((int) $order->id_carrier); if (!Validate::isLoadedObject($customer) or !Validate::isLoadedObject($carrier)) { die(Tools::displayError()); } $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => (int) $order->id); if ($this->getPSV() == 1.6) { $templateVars['{order_name}'] = $order->getUniqReference(); } @Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true); } $this->_tracking_numbers = serialize($this->_tracking_numbers); Db::getInstance()->execute(' UPDATE `' . _DB_PREFIX_ . 'fe_dhl_labels_info` SET `tracking_id_type` = \'' . pSQL($this->_trackingIdType) . '\', `tracking_numbers` = \'' . $this->_tracking_numbers . '\' WHERE `id_order` = ' . (int) $id_order . ' '); return array(1, $this->_response); }
$ogone->validate((int) $_GET['orderID'], _PS_OS_ERROR_, 0, $ogone->l('Error (auth. refused)') . '<br />' . $_GET['NCERROR'] . $params, $_GET['secure_key']); break; case 5: case 9: /* Payment OK */ $ogone->validate((int) $_GET['orderID'], _PS_OS_PAYMENT_, (double) $_GET['amount'], $ogone->l('Payment authorized / OK') . $params, $_GET['secure_key']); break; case 6: case 7: case 8: // Payment canceled later if ($id_order = (int) Order::getOrderByCartId((int) $_GET['orderID'])) { // Update the amount really paid $order = new Order($id_order); $order->total_paid_real = 0; $order->update(); // Send a new message and change the state $history = new OrderHistory(); $history->id_order = $id_order; $history->changeIdOrderState(_PS_OS_ERROR_, $id_order); $history->addWithemail(true, array()); } break; default: $ogone->validate((int) $_GET['orderID'], _PS_OS_ERROR_, (double) $_GET['amount'], $ogone->l('Unknown status:') . ' ' . $_GET['STATUS'] . $params, $_GET['secure_key']); } exit; } else { $message = $ogone->l('Invalid SHA-1 signature') . '<br />' . $ogone->l('SHA-1 given:') . ' ' . $_GET['SHASIGN'] . '<br />' . $ogone->l('SHA-1 calculated:') . ' ' . $sha1 . '<br />' . $ogone->l('Plain key:') . ' ' . $shasign; $ogone->validate((int) $_GET['orderID'], _PS_OS_ERROR_, 0, $message . '<br />' . $params, $_GET['secure_key']); }
public function setData(Order $order, array $data) { $order->update($data); $order->write(); }
public function ajaxProcessEditProductOnOrder() { // Return value $res = true; $order = new Order((int) Tools::getValue('id_order')); $order_detail = new OrderDetail((int) Tools::getValue('product_id_order_detail')); if (Tools::isSubmit('product_invoice')) { $order_invoice = new OrderInvoice((int) Tools::getValue('product_invoice')); } // Check fields validity $this->doEditProductValidation($order_detail, $order, isset($order_invoice) ? $order_invoice : null); // If multiple product_quantity, the order details concern a product customized $product_quantity = 0; if (is_array(Tools::getValue('product_quantity'))) { foreach (Tools::getValue('product_quantity') as $id_customization => $qty) { // Update quantity of each customization Db::getInstance()->update('customization', array('quantity' => $qty), 'id_customization = ' . (int) $id_customization); // Calculate the real quantity of the product $product_quantity += $qty; } } else { $product_quantity = Tools::getValue('product_quantity'); } $product_price_tax_incl = Tools::ps_round(Tools::getValue('product_price_tax_incl'), 2); $product_price_tax_excl = Tools::ps_round(Tools::getValue('product_price_tax_excl'), 2); $total_products_tax_incl = $product_price_tax_incl * $product_quantity; $total_products_tax_excl = $product_price_tax_excl * $product_quantity; // Calculate differences of price (Before / After) $diff_price_tax_incl = $total_products_tax_incl - $order_detail->total_price_tax_incl; $diff_price_tax_excl = $total_products_tax_excl - $order_detail->total_price_tax_excl; // Apply change on OrderInvoice if (isset($order_invoice)) { // If OrderInvoice to use is different, we update the old invoice and new invoice if ($order_detail->id_order_invoice != $order_invoice->id) { $old_order_invoice = new OrderInvoice($order_detail->id_order_invoice); // We remove cost of products $old_order_invoice->total_products -= $order_detail->total_price_tax_excl; $old_order_invoice->total_products_wt -= $order_detail->total_price_tax_incl; $old_order_invoice->total_paid_tax_excl -= $order_detail->total_price_tax_excl; $old_order_invoice->total_paid_tax_incl -= $order_detail->total_price_tax_incl; $res &= $old_order_invoice->update(); $order_invoice->total_products += $order_detail->total_price_tax_excl; $order_invoice->total_products_wt += $order_detail->total_price_tax_incl; $order_invoice->total_paid_tax_excl += $order_detail->total_price_tax_excl; $order_invoice->total_paid_tax_incl += $order_detail->total_price_tax_incl; $order_detail->id_order_invoice = $order_invoice->id; } } if ($diff_price_tax_incl != 0 && $diff_price_tax_excl != 0) { $order_detail->unit_price_tax_excl = $product_price_tax_excl; $order_detail->unit_price_tax_incl = $product_price_tax_incl; $order_detail->total_price_tax_incl += $diff_price_tax_incl; $order_detail->total_price_tax_excl += $diff_price_tax_excl; if (isset($order_invoice)) { // Apply changes on OrderInvoice $order_invoice->total_products += $diff_price_tax_excl; $order_invoice->total_products_wt += $diff_price_tax_incl; $order_invoice->total_paid_tax_excl += $diff_price_tax_excl; $order_invoice->total_paid_tax_incl += $diff_price_tax_incl; } // Apply changes on Order $order = new Order($order_detail->id_order); $order->total_products += $diff_price_tax_excl; $order->total_products_wt += $diff_price_tax_incl; $order->total_paid += $diff_price_tax_incl; $order->total_paid_tax_excl += $diff_price_tax_excl; $order->total_paid_tax_incl += $diff_price_tax_incl; $res &= $order->update(); } $old_quantity = $order_detail->product_quantity; $order_detail->product_quantity = $product_quantity; // update taxes $res &= $order_detail->updateTaxAmount($order); // Save order detail $res &= $order_detail->update(); // Update weight SUM $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier()); if (Validate::isLoadedObject($order_carrier)) { $order_carrier->weight = (double) $order->getTotalWeight(); $res &= $order_carrier->update(); if ($res) { $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight); } } // Save order invoice if (isset($order_invoice)) { $res &= $order_invoice->update(); } // Update product available quantity StockAvailable::updateQuantity($order_detail->product_id, $order_detail->product_attribute_id, $old_quantity - $order_detail->product_quantity, $order->id_shop); $products = $this->getProducts($order); // Get the last product $product = $products[$order_detail->id]; $resume = OrderSlip::getProductSlipResume($order_detail->id); $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity']; $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl']; $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']); $product['refund_history'] = OrderSlip::getProductSlipDetail($order_detail->id); if ($product['id_warehouse'] != 0) { $warehouse = new Warehouse((int) $product['id_warehouse']); $product['warehouse_name'] = $warehouse->name; } else { $product['warehouse_name'] = '--'; } // Get invoices collection $invoice_collection = $order->getInvoicesCollection(); $invoice_array = array(); foreach ($invoice_collection as $invoice) { $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop); $invoice_array[] = $invoice; } // Assign to smarty informations in order to show the new product line $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))); if (!$res) { die(Tools::jsonEncode(array('result' => $res, 'error' => Tools::displayError('An error occurred while editing the product line.')))); } if (is_array(Tools::getValue('product_quantity'))) { $view = $this->createTemplate('_customized_data.tpl')->fetch(); } else { $view = $this->createTemplate('_product_line.tpl')->fetch(); } $this->sendChangedNotification($order); die(Tools::jsonEncode(array('result' => $res, 'view' => $view, 'can_edit' => $this->tabAccess['add'], 'invoices_collection' => $invoice_collection, 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'customized_product' => is_array(Tools::getValue('product_quantity'))))); }
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart Value * @param integer $id_order_state Value * @param float $amountPaid Amount really paid by customer (in the default currency) * @param string $paymentMethod Payment method (eg. 'Credit card') * @param string $message Message to attach to order */ public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false) { global $cart, $link, $cookie; $id_payment_state = _PS_PS_NOT_PAID_; $cart = new Cart((int) $id_cart); // Does order already exists ? if (Validate::isLoadedObject($cart) and $cart->OrderExists() == false) { if ($secure_key !== false and $secure_key != $cart->secure_key) { die(Tools::displayError()); } // Copying data from cart $order = new Order(); $order->id_carrier = (int) $cart->id_carrier; $order->id_customer = (int) $cart->id_customer; $order->id_address_invoice = (int) $cart->id_address_invoice; $order->id_address_delivery = (int) $cart->id_address_delivery; $vat_address = new Address((int) $order->id_address_delivery); $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency; $order->id_lang = (int) $cart->id_lang; $order->id_cart = (int) $cart->id; $customer = new Customer((int) $order->id_customer); $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key); $order->payment = $paymentMethod; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $cart->recyclable; $order->gift = (int) $cart->gift; $order->gift_message = $cart->gift_message; $currency = new Currency($order->id_currency); $order->conversion_rate = $currency->conversion_rate; $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid; $order->total_paid_real = $amountPaid; $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS); $order->total_customization = $cart->getCartCustomizationCost(); $order->total_donation = round($cookie->donation_amount); unset($cookie->donation_amount); if (strpos($order->payment, 'COD') === false) { $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, true)); $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, true)); } else { $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, false)); $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, false)); $order->total_cod = COD_CHARGE; } $order->total_shipping = (double) $cart->getOrderShippingCost(); $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING)); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; $shippingdate = $cart->getExpectedShippingDate(); $order->expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s')); $order->actual_expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s')); // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if (number_format(round($order->total_paid)) != number_format(round($order->total_paid_real))) { $id_order_state = _PS_OS_ERROR_; $id_payment_state = _PS_PS_NOT_PAID_; } else { if (strpos($order->payment, 'COD') === false) { $id_payment_state = _PS_PS_PAID_; } } //update payment status // Creating order if ($cart->OrderExists() == false) { $cart_value = $cart->getOrderTotal(); if ($cart_value >= 1000) { //if(!$cart->containsProduct(FREE_GIFT_ID, NULL, NULL)) //$cart->updateQty(1, FREE_GIFT_ID, NULL, false, 'up', TRUE); } $result = $order->add(); } else { $errorMessage = Tools::displayError('An order has already been placed using this cart.'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart)); die($errorMessage); } // Next ! if ($result and isset($order->id)) { if (!$secure_key) { $message .= $this->l('Warning : the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) and !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } } // Insert products from cart into order_detail table $products = $cart->getProducts(); $productsList = ''; $db = Db::getInstance(); $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail` (`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`, `customization`) VALUES '; $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart); Product::addCustomizationPrice($products, $customizedDatas); $outOfStock = false; foreach ($products as $key => $product) { $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL); $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity']; if ($id_order_state != _PS_OS_CANCELED_ and $id_order_state != _PS_OS_ERROR_) { if (Product::updateQuantity($product, (int) $order->id)) { $product['stock_quantity'] -= $product['cart_quantity']; } if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) { $outOfStock = true; } if ($product['stock_quantity'] < 1) { SolrSearch::updateProduct((int) $product['id_product']); } Product::updateDefaultAttribute($product['id_product']); } $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 2, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); // Add some informations for virtual products $deadline = '0000-00-00 00:00:00'; $download_hash = NULL; if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) { $productDownload = new ProductDownload((int) $id_product_download); $deadline = $productDownload->getDeadLine(); $download_hash = $productDownload->getHash(); } // Exclude VAT if (Tax::excludeTaxeOption()) { $product['tax'] = 0; $product['rate'] = 0; $tax_rate = 0; } else { $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $ecotaxTaxRate = 0; if (!empty($product['ecotax'])) { $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']); $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0; $specificPrice = 0; $query .= '(' . (int) $order->id . ', ' . (int) $product['id_product'] . ', ' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ', \'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\', ' . (int) $product['cart_quantity'] . ', ' . $quantityInStock . ', ' . (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE) . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ', ' . (double) Group::getReduction((int) $order->id_customer) . ', ' . $quantityDiscountValue . ', ' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ', ' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ', ' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ', ' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ', ' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ', \'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\', ' . (double) $tax_rate . ', ' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ', ' . (double) $ecotaxTaxRate . ', ' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ', \'' . pSQL($deadline) . '\', \'' . pSQL($download_hash) . '\', ' . $cart->getProductCustomizationCost($product['id_product']) . '),'; $customizationQuantity = 0; if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) { $customizationText = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { if ($text['index'] == 8) { $customizationText .= 'Saree with unstitched blouse and fall/pico work.' . '<br />'; } else { if ($text['index'] == 1) { $customizationText .= 'Pre-stitched saree with unstitched blouse and fall/pico work.' . '<br />'; } else { if ($text['index'] == 2) { $customizationText .= 'Stitched to measure blouse.' . '<br />'; } else { if ($text['index'] == 3) { $customizationText .= 'Stitched to measure in-skirt.' . '<br />'; } else { if ($text['index'] == 4) { $customizationText .= 'Stitched to measure kurta.' . '<br />'; } else { if ($text['index'] == 5) { $customizationText .= 'Stitched to measure salwar.' . '<br />'; } } } } } } } } if (isset($customization['datas'][_CUSTOMIZE_FILE_])) { $customizationText .= sizeof($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />'; } $customizationText .= '---<br />'; } $customizationText = rtrim($customizationText, '---<br />'); $customizationQuantity = (int) $product['customizationQuantityTotal']; $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td> </tr>'; } if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) { $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td> </tr>'; } //if giftcard, create voucher and send the mails now. $categories = Product::getProductCategories($product['id_product']); if (in_array(CAT_GIFTCARD, $categories)) { $friendsName = ''; $friendsEmail = ''; $giftMessage = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { if ($text['index'] == 21) { $friendsName = $text['value']; } else { if ($text['index'] == 22) { $friendsEmail = $text['value']; } else { if ($text['index'] == 23) { $giftMessage = $text['value']; } else { if ($text['index'] == 25) { $couponCode = $text['value']; } } } } } } } //$couponCode = "GC" . Tools::rand_string(8); // create discount $languages = Language::getLanguages($order); $voucher = new Discount(); $voucher->id_discount_type = 2; foreach ($languages as $language) { $voucher->description[$language['id_lang']] = $product['name']; } $voucher->value = (double) $unitPrice; $voucher->name = $couponCode; $voucher->id_currency = 2; //USD $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = 1; $voucher->cumulable_reduction = 1; $voucher->minimal = 0; $voucher->active = 1; $voucher->cart_display = 0; $now = time(); $voucher->date_from = date('Y-m-d H:i:s', $now); $voucher->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365); /* 365 days */ $voucher->add(); $productObj = new Product($product['id_product'], true, 1); $idImage = $productObj->getCoverWs(); if ($idImage) { $idImage = $productObj->id . '-' . $idImage; } else { $idImage = Language::getIsoById(1) . '-default'; } $params = array(); $params['{voucher_code}'] = $voucher->name; $params['{freinds_name}'] = $friendsName; $params['{gift_message}'] = $giftMessage; $params['{product_name}'] = $product['name']; $params['{voucher_value}'] = $voucher->value; $params['{image_url}'] = _PS_BASE_URL_ . _PS_IMG_ . 'banners/' . $productObj->location; $params['{sender_name}'] = $customer->firstname . ' ' . $customer->lastname; $subject = $friendsName . ', You Have Received A $' . $voucher->value . ' IndusDiva Gift Card'; @Mail::Send(1, 'gift_card', $subject, $params, $friendsEmail, $friendsName, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true); @Mail::Send(1, 'gift_card', $subject, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true); } } // end foreach ($products) $query = rtrim($query, ','); $result = $db->Execute($query); // Insert discounts from cart into order_discount table $discounts = $cart->getDiscounts(); $discountsList = ''; $total_discount_value = 0; $shrunk = false; foreach ($discounts as $discount) { $objDiscount = new Discount((int) $discount['id_discount'], $order->id_lang); $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id); if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) { $shrunk = true; } if ($shrunk and $total_discount_value + $value > $order->total_products + $order->total_shipping + $order->total_wrapping) { $amount_to_add = $order->total_products + $order->total_shipping + $order->total_wrapping - $total_discount_value; if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and $objDiscount->behavior_not_exhausted == 2) { $voucher = new Discount(); foreach ($objDiscount as $key => $discountValue) { $voucher->{$key} = $discountValue; } $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id; $voucher->value = (double) $value - $amount_to_add; $voucher->add(); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); $params['{voucher_num}'] = $voucher->name; @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #') . $order->id, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } else { $amount_to_add = $value; } $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add); $total_discount_value += $amount_to_add; if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_) { $objDiscount->quantity = $objDiscount->quantity - 1; } $objDiscount->update(); $discountsList .= '<tr style="background-color:#EBECEE;"> <td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td> </tr>'; } // Specify order id for message $oldMessage = Message::getMessageByCartId((int) $cart->id); if ($oldMessage) { $message = new Message((int) $oldMessage['id_message']); $message->id_order = (int) $order->id; $message->update(); } // Hook new order $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang); if (Validate::isLoadedObject($orderStatus)) { Hook::newOrder($cart, $order, $customer, $currency, $orderStatus); foreach ($cart->getProducts() as $product) { if ($orderStatus->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } } if (isset($outOfStock) and $outOfStock) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, (int) $order->id); $history->addWithemail(); } // Set order state in order history ONLY even if the "out of stock" status has not been yet reached // So you migth have two order states $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id); $new_history->addWithemail(true, $extraVars); //Payment status $paymentHistory = new OrderPaymentHistory(); $paymentHistory->id_order = (int) $order->id; $paymentHistory->changeIdOrderPaymentState($id_payment_state, (int) $order->id); $paymentHistory->addState(); // Order is reloaded because the status just changed $order = new Order($order->id); //Update tracking code for quantium if ($order->id_carrier == QUANTIUM) { if (strpos($order->payment, 'COD') === false) { $order->shipping_number = 'VBN' . $order->id; } else { $order->shipping_number = 'VBC' . $order->id; } $order->update(); } else { if ($order->id_carrier == SABEXPRESS) { $db = Db::getInstance(); $db->Execute('LOCK TABLES vb_awb_pool WRITE'); $res = $db->getRow("select min(id) as 'id', awb from vb_awb_pool where id_carrier = " . SABEXPRESS . " and assigned = 0"); $awb = $res['awb']; $id = $res['id']; $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id); $db->Execute('UNLOCK TABLES'); $order->shipping_number = $awb; $order->update(); } else { if ($order->id_carrier == AFL) { $db = Db::getInstance(); $db->Execute('LOCK TABLES vb_awb_pool WRITE'); $res = $db->getRow("select min(id) as 'id' , awb from vb_awb_pool where id_carrier = " . AFL . " and assigned = 0"); $awb = $res['awb']; $id = $res['id']; $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id); $db->Execute('UNLOCK TABLES'); $order->shipping_number = $awb; $order->update(); } } } // Send an e-mail to customer if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id and $id_order_state != _PS_OS_OP_PAYEMENT_FAILED) { //deduct reward points $points_redeemed = $cart->getPoints(); if ($points_redeemed) { VBRewards::removeRewardPoints($order->id_customer, EVENT_POINTS_REDEEMED, 0, $cart->getPoints(), 'Coins redeemed - Order no ' . $order->id, $order->id, $order->date_add); } /* if(strpos($order->payment, 'COD') === false && $order->total_paid_real > 0) { VBRewards::addRewardPoints($order->id_customer, ONLINE_ORDER, 0, 100, 'Online payment bonus - Order no ' . $order->id, $order->id, $order->date_add); } */ $invoice = new Address((int) $order->id_address_invoice); $delivery = new Address((int) $order->id_address_delivery); $carrier = new Carrier((int) $order->id_carrier, $order->id_lang); $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false; $shippingdate = new DateTime($order->expected_shipping_date); $data = array('{firstname}' => $customer->firstname, '{shipping_date}' => $shippingdate->format("F j, Y"), '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", (int) $order->id), '{date}' => date("F j, Y, g:i a"), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_cod - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_cod}' => Tools::displayPrice($order->total_cod, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false)); if (is_array($extraVars)) { $data = array_merge($data, $extraVars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) { $fileAttachment['content'] = PDF::invoice($order, 'S'); $fileAttachment['name'] = $fileAttachment['name'] = 'IndusDiva Order #' . sprintf('%06d', (int) $order->id) . '.pdf'; $fileAttachment['mime'] = 'application/pdf'; } else { $fileAttachment = NULL; } if (Validate::isEmail($customer->email)) { if ($id_order_state == _PS_OS_BANKWIRE_) { Mail::Send((int) $order->id_lang, 'order_conf_bankwire', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } else { $data['payment'] = 'Online Payment'; Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } } //Send SMS //$smsText = 'Dear customer, your order #'.$order->id.' at IndusDiva.com is confirmed and will be delivered to you within 3-5 business days. www.indusdiva.com'; //Tools::sendSMS($delivery->phone_mobile, $smsText); } $this->currentOrder = (int) $order->id; return true; } else { $errorMessage = Tools::displayError('Order creation failed'); Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart)); die($errorMessage); } } else { $errorMessage = Tools::displayError('Cart can\'t be loaded or an order has already been placed using this cart'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id)); die($errorMessage); } }