public function registerDiscount($id_customer, $register = false) { $configurations = Configuration::getMultiple(array('REFERRAL_DISCOUNT_TYPE', 'REFERRAL_DISCOUNT_VALUE')); $discount = new Discount(); $discount->id_discount_type = intval($configurations['REFERRAL_DISCOUNT_TYPE']); $discount->value = floatval($configurations['REFERRAL_DISCOUNT_VALUE']); $discount->quantity = 1; $discount->quantity_per_user = 1; $discount->date_from = date('Y-m-d H:i:s', time()); $discount->date_to = date('Y-m-d H:i:s', time() + 31536000); // + 1 year $discount->name = $this->getDiscountPrefix() . Tools::passwdGen(6); $discount->description = Configuration::getInt('REFERRAL_DISCOUNT_DESCRIPTION'); $discount->id_customer = intval($id_customer); if ($discount->add()) { if ($register != false) { if ($register == 'sponsor') { $this->id_discount_sponsor = $discount->id; } elseif ($register == 'sponsored') { $this->id_discount = $discount->id; } return $this->save(); } return true; } return false; }
public function createDefaultBcashDiscounts() { foreach ($this->names as $name) { $coupon = new Discount(); $coupon->name = $this->getLangsForName($name); $coupon->quantity = self::billion; $coupon->quantity_per_user = self::billion; $coupon->date_from = date('Y-m-d H:i:s'); $coupon->date_to = date('Y-m-d', strtotime('+30 year')); $coupon->partial_use = 0; $coupon->code = 'gerenciado_pelo_modulo_' . Tools::passwdGen(8); $coupon->active = 0; //Invisivel $coupon->highlight = 0; //Envio excluido $coupon->minimum_amount_shipping = 0; //Acoes $coupon->free_shipping = 0; $coupon->reduction_percent = 0; if ($coupon->add()) { Configuration::updateValue(self::prefix . self::bcash . $name, (int) $coupon->id); } } return true; }
public function createTodaysVouchers() { $users = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' SELECT DISTINCT c.id_customer, firstname, lastname, email FROM ' . _DB_PREFIX_ . 'customer c LEFT JOIN ' . _DB_PREFIX_ . 'orders o ON (c.id_customer = o.id_customer) WHERE o.valid = 1 AND c.birthday LIKE \'%' . date('-m-d') . '\''); foreach ($users as $user) { $voucher = new Discount(); $voucher->id_customer = (int) $user['id_customer']; $voucher->id_discount_type = (int) Configuration::get('BIRTHDAY_DISCOUNT_TYPE'); $voucher->name = 'BIRTHDAY-' . (int) $voucher->id_customer . '-' . date('Y'); $voucher->description[(int) Configuration::get('PS_LANG_DEFAULT')] = $this->l('Your birthday present !'); $voucher->value = Configuration::get('BIRTHDAY_DISCOUNT_VALUE'); $voucher->id_currency = Configuration::get('PS_CURRENCY_DEFAULT'); $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = 1; $voucher->cumulable_reduction = 1; $voucher->date_from = date('Y-m-d'); $voucher->date_to = strftime('%Y-%m-%d', strtotime('+1 month')); $voucher->minimal = Configuration::get('BIRTHDAY_MINIMAL_ORDER'); $voucher->active = true; if ($voucher->add()) { Mail::Send((int) Configuration::get('PS_LANG_DEFAULT'), 'birthday', Mail::l('Happy birthday!', (int) Configuration::get('PS_LANG_DEFAULT')), array('{firstname}' => $user['firstname'], '{lastname}' => $user['lastname']), $user['email'], NULL, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/mails/'); } else { echo Db::getInstance()->getMsgError(); } } }
$voucher->minimal = (double) Configuration::get('PS_LOYALTY_MINIMAL'); $voucher->active = 1; $categories = Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY'); if ($categories != '' and $categories != 0) { $categories = explode(',', Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY')); } else { die(Tools::displayError()); } $languages = Language::getLanguages(true); $default_text = Configuration::get('PS_LOYALTY_VOUCHER_DETAILS', (int) Configuration::get('PS_LANG_DEFAULT')); foreach ($languages as $language) { $text = Configuration::get('PS_LOYALTY_VOUCHER_DETAILS', (int) $language['id_lang']); $voucher->description[(int) $language['id_lang']] = $text ? strval($text) : strval($default_text); } if (is_array($categories) and sizeof($categories)) { $voucher->add(true, false, $categories); } else { $voucher->add(); } /* Register order(s) which contributed to create this voucher */ LoyaltyModule::registerDiscount($voucher); Tools::redirect('modules/loyalty/loyalty-program.php'); } include dirname(__FILE__) . '/../../header.php'; $orders = LoyaltyModule::getAllByIdCustomer((int) $cookie->id_customer, (int) $cookie->id_lang); $displayorders = LoyaltyModule::getAllByIdCustomer((int) $cookie->id_customer, (int) $cookie->id_lang, false, true, (int) Tools::getValue('n') > 0 ? (int) Tools::getValue('n') : 10, (int) Tools::getValue('p') > 0 ? (int) Tools::getValue('p') : 1); $smarty->assign(array('orders' => $orders, 'displayorders' => $displayorders, 'pagination_link' => __PS_BASE_URI__ . 'modules/loyalty/loyalty-program.php', 'totalPoints' => (int) $customerPoints, 'voucher' => LoyaltyModule::getVoucherValue($customerPoints, (int) $cookie->id_currency), 'validation_id' => LoyaltyStateModule::getValidationId(), 'transformation_allowed' => $customerPoints > 0, 'page' => (int) Tools::getValue('p') > 0 ? (int) Tools::getValue('p') : 1, 'nbpagination' => (int) (Tools::getValue('n') > 0) ? (int) Tools::getValue('n') : 10, 'nArray' => array(10, 20, 50), 'max_page' => floor(sizeof($orders) / ((int) (Tools::getValue('n') > 0) ? (int) Tools::getValue('n') : 10)))); /* Discounts */ $nbDiscounts = 0; $discounts = array(); if ($ids_discount = LoyaltyModule::getDiscountByIdCustomer((int) $cookie->id_customer)) {
private function createDiscount($id_email_type, $amount, $id_customer, $dateValidity, $description) { $discount = new Discount(); $discount->id_discount_type = 1; $discount->value = (double) $amount; $discount->id_customer = (int) $id_customer; $discount->date_to = $dateValidity; $discount->date_from = date('Y-m-d H:i:s'); $discount->quantity = 1; $discount->quantity_per_user = 1; $discount->cumulable = 0; $discount->cumulable_reduction = 1; $discount->minimal = 0; $languages = Language::getLanguages(true); foreach ($languages as $language) { $discount->description[(int) $language['id_lang']] = $description; } $name = 'FLW-' . (int) $id_email_type . '-' . strtoupper(Tools::passwdGen(10)); $discount->name = $name; $discount->active = 1; $result = $discount->add(); if (!$result) { return false; } return $discount; }
/** * 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; $cart = new Cart((int) $id_cart); // Does order already exists ? if (!$this->active) { die(Tools::displayError()); } if (Validate::isLoadedObject($cart) && $cart->OrderExists() == false) { if ($secure_key !== false && $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->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $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_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $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->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; // 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($order->total_paid, 2) != number_format($order->total_paid_real, 2)) { $id_order_state = Configuration::get('PS_OS_ERROR'); } // Creating order if ($cart->OrderExists() == false) { $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`) VALUES '; $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart); Product::addCustomizationPrice($products, $customizedDatas); $outOfStock = false; $store_all_taxes = array(); 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 != Configuration::get('PS_OS_CANCELED') and $id_order_state != Configuration::get('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; } 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')}); /* Store tax info */ $id_country = (int) Country::getDefaultCountryId(); $id_state = 0; $id_county = 0; $rate = 0; $id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; $address_infos = Address::getCountryAndState($id_address); if ($address_infos['id_country']) { $id_country = (int) $address_infos['id_country']; $id_state = (int) $address_infos['id_state']; $id_county = (int) County::getIdCountyByZipCode($address_infos['id_state'], $address_infos['postcode']); } $allTaxes = TaxRulesGroup::getTaxes((int) Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product']), $id_country, $id_state, $id_county); // If its a freeOrder, there will be no calculation if ($order->total_products > 0) { // remove order discount quotepart on product price in order to obtain the real tax $ratio = $price / $order->total_products; $order_reduction_amount = (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)) * $ratio; $tmp_price = $price - $order_reduction_amount; foreach ($allTaxes as $res) { if (!isset($store_all_taxes[$res->id])) { $store_all_taxes[$res->id] = array(); $store_all_taxes[$res->id]['amount'] = 0; } $store_all_taxes[$res->id]['name'] = $res->name[(int) $order->id_lang]; $store_all_taxes[$res->id]['rate'] = $res->rate; $unit_tax_amount = $tmp_price * ($res->rate * 0.01); $tmp_price = $tmp_price + $unit_tax_amount; $store_all_taxes[$res->id]['amount'] += $unit_tax_amount * $product['cart_quantity']; } } /* End */ // 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 (!_PS_TAX_) { $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')}); } $product_price = (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, false); $group_reduction = (double) GroupReduction::getValueForProduct((int) $product['id_product'], $customer->id_default_group) * 100; if (!$group_reduction) { $group_reduction = (double) Group::getReduction((int) $order->id_customer); } $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; $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 . ', ' . $product_price . ', ' . (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) . ', ' . $group_reduction . ', ' . $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) . '\'),'; $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) { $customizationText .= $text['name'] . ':' . ' ' . $text['value'] . '<br />'; } } if (isset($customization['datas'][_CUSTOMIZE_FILE_])) { $customizationText .= count($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;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : ' ') . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $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 * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $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;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : ' ') . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $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) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td> </tr>'; } } // end foreach ($products) $query = rtrim($query, ','); $result = $db->Execute($query); /* Add carrier tax */ $shippingCostTaxExcl = $cart->getOrderShippingCost((int) $order->id_carrier, false); $allTaxes = TaxRulesGroup::getTaxes((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $order->id_carrier), $id_country, $id_state, $id_county); $nTax = 0; foreach ($allTaxes as $tax) { if (!isset($tax->id)) { continue; } if (!isset($store_all_taxes[$tax->id])) { $store_all_taxes[$tax->id] = array(); } if (!isset($store_all_taxes[$tax->id]['amount'])) { $store_all_taxes[$tax->id]['amount'] = 0; } $store_all_taxes[$tax->id]['name'] = $tax->name[(int) $order->id_lang]; $store_all_taxes[$tax->id]['rate'] = $tax->rate; if (!$nTax++) { $store_all_taxes[$tax->id]['amount'] += $shippingCostTaxExcl * (1 + $tax->rate * 0.01) - $shippingCostTaxExcl; } else { $store_all_taxes[$tax->id]['amount'] += $order->total_shipping - $order->total_shipping / (1 + $tax->rate * 0.01); } } /* Store taxes */ foreach ($store_all_taxes as $tax) { Db::getInstance()->Execute(' INSERT INTO `' . _DB_PREFIX_ . 'order_tax` (`id_order`, `tax_name`, `tax_rate`, `amount`) VALUES (' . (int) $order->id . ', \'' . pSQL($tax['name']) . '\', ' . (double) $tax['rate'] . ', ' . (double) $tax['amount'] . ')'); } // 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']); $value = $objDiscount->getValue(count($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id); if ($objDiscount->id_discount_type == 2 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) { $shrunk = true; } if ($shrunk and $total_discount_value + $value > $order->total_products_wt + $order->total_shipping + $order->total_wrapping) { $amount_to_add = $order->total_products_wt + $order->total_shipping + $order->total_wrapping - $total_discount_value; if ($objDiscount->id_discount_type == 2 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; $params['{firstname}'] = $customer->firstname; $params['{lastname}'] = $customer->lastname; $params['{id_order}'] = $order->id; $params['{order_name}'] = sprintf("#%06d", (int) $order->id); @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #', (int) $order->id_lang) . sprintf("%06d", (int) $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 != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('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) && $outOfStock && Configuration::get('PS_STOCK_MANAGEMENT')) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(Configuration::get('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); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED') and $customer->id) { $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; $data = array('{firstname}' => $customer->firstname, '{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}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{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_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_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'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang) . sprintf('%06d', $order->invoice_number) . '.pdf'; $fileAttachment['mime'] = 'application/pdf'; } else { $fileAttachment = null; } if (Validate::isEmail($customer->email)) { Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } } $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 cannot be loaded or an order has already been placed using this cart'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id)); die($errorMessage); } }
public function preProcess() { global $isVirtualCart, $cookie; parent::preProcess(); // Redirect to the good order process if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 0 and (strpos($_SERVER['PHP_SELF'], 'order.php') === false and strpos($_SERVER['PHP_SELF'], 'cart-summary-large.php') === false)) { Tools::redirect('order.php'); } if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1 and strpos($_SERVER['PHP_SELF'], 'order-opc.php') === false) { if (isset($_GET['step']) and $_GET['step'] == 3) { Tools::redirect('order-opc.php?isPaymentStep=true'); } Tools::redirect('order-opc.php'); } if (Configuration::get('PS_CATALOG_MODE')) { $this->errors[] = Tools::displayError('This store has not accepted your new order.'); } if (Tools::isSubmit('submitReorder') and $id_order = (int) Tools::getValue('id_order')) { $oldCart = new Cart(Order::getCartIdStatic((int) $id_order, (int) self::$cookie->id_customer)); $duplication = $oldCart->duplicate(); if (!$duplication or !Validate::isLoadedObject($duplication['cart'])) { $this->errors[] = Tools::displayError('Sorry, we cannot renew your order.'); } elseif (!$duplication['success']) { $this->errors[] = Tools::displayError('Missing items - we are unable to renew your order'); } else { self::$cookie->id_cart = $duplication['cart']->id; self::$cookie->write(); if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) { Tools::redirect('order-opc.php'); } Tools::redirect('order.php'); } } if (Tools::isSubmit('submit_instructions')) { $instructions = Tools::getValue('special_instructions'); self::$cart->gift_message = pSQL($instructions); self::$cart->update(); Tools::redirect('order?step=3'); } if ($this->nbProducts) { /* check discount validity */ $cartDiscounts = self::$cart->getDiscounts(); $discountInvalid = false; foreach ($cartDiscounts as $k => $cartDiscount) { if ($error = self::$cart->checkDiscountValidity(new Discount((int) $cartDiscount['id_discount']), $cartDiscounts, self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING), self::$cart->getProducts())) { self::$cart->deleteDiscount((int) $cartDiscount['id_discount']); $discountInvalid = true; } } if ($discountInvalid) { Tools::redirect('order-opc.php'); } if (Tools::getValue('redeem_points')) { $points = (int) Tools::getValue('redeem_points'); if ($points < 1) { self::$smarty->assign('redeem_points', $points); $this->errors[] = Tools::displayError('You can redeem minimum of 1 coin in an order.'); } $orderTotal = self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS); $redemption_status = VBRewards::checkPointsValidity($cookie->id_customer, $points + self::$cart->getPoints(), $orderTotal); if ($redemption_status === CAN_REDEEM_COINS) { self::$cart->addPoints($points); self::$smarty->assign('redeem_points', (int) self::$cart->getPoints()); } else { if ($redemption_status === INSUFFICIENT_VALID_ORDERS) { $this->errors[] = Tools::displayError('Coins can be redeemed from second purchase onwards.'); } else { if ($redemption_status === MIN_CRITERIA_NOT_MET) { $this->errors[] = Tools::displayError('Order value should be more than 100 USD to redeem coins'); } } } $this->adjustPoints(); } elseif (Tools::getValue('deletePoints')) { self::$cart->deletePoints(); } if (Tools::isSubmit('submitAddDiscount') and Tools::getValue('discount_name')) { $discountName = Tools::getValue('discount_name'); if (!Validate::isDiscountName($discountName)) { $this->errors[] = Tools::displayError('Voucher name invalid.'); } else { $discount = new Discount((int) Discount::getIdByName($discountName)); if (Validate::isLoadedObject($discount)) { if ($tmpError = self::$cart->checkDiscountValidity($discount, self::$cart->getDiscounts(), self::$cart->getOrderTotal(), self::$cart->getProducts(), true)) { $this->errors[] = $tmpError; } } else { $this->errors[] = Tools::displayError('Voucher name invalid.'); } if (!sizeof($this->errors)) { self::$cart->addDiscount((int) $discount->id); Tools::redirect('order-opc.php'); } } self::$smarty->assign(array('errors' => $this->errors, 'discount_name' => Tools::safeOutput($discountName))); $this->adjustPoints(); } elseif (isset($_GET['deleteDiscount']) and Validate::isUnsignedId($_GET['deleteDiscount'])) { self::$cart->deleteDiscount((int) $_GET['deleteDiscount']); Tools::redirect('order-opc.php'); } /* Is there only virtual product in cart */ if ($isVirtualCart = self::$cart->isVirtualCart()) { $this->_setNoCarrier(); } } //if enough stock, show free gift message $free_products = array(66254, 66255, 66256); $sql = "select quantity from ps_product where id_product in (" . implode(",", $free_products) . ")"; $result = Db::getInstance()->ExecuteS($sql); $free_gift_stock = $has_free_gift = false; foreach ($result as $row) { if (intval($row['quantity']) > 0) { $free_gift_stock = true; break; } } $total_products_wt = self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS); $cv = Tools::convertPrice($total_products_wt, (int) self::$cookie->id_currency, false); /*if( $cv > 50) { if( $free_gift_stock ) { $cart_products = self::$cart->getProducts(); foreach($cart_products as $cproduct) { $id_product = $cproduct['id_product']; if( in_array($id_product, $free_products )) { $has_free_gift = true; break; } } } if( !$has_free_gift && $free_gift_stock ) { self::$smarty->assign("spl_voucher_message","Here is the free <a href='/1222-free-gifts'>gift product</a> for you.Valid still stock lasts. Read <a href='/content/30-womens-day-special-discount'>T&C</a> here"); } } else { $free_products = array(66254, 66255, 66256); foreach($free_products as $p) self::$cart->deleteProduct($p); self::$smarty->assign("spl_voucher_message","We have a free <a href='/1222-free-gifts'>gift product</a> for you if the shopping cart value is atleast USD 50."); } self::$smarty->assign('back', Tools::safeOutput(Tools::getValue('back'))); if (self::$cart->gift_message) { self::$smarty->assign('cart_instructions', 1); self::$smarty->assign('special_instructions', self::$cart->gift_message); }*/ //buy1 get 1 $products = self::$cart->getProducts(true); $offeredProducts = 0; // this is a very interesting array, keeps as many rows as there are items in your cart // if there is an item with quantity 2, it will have two rows in that array, // ie item will have as many rows as the quantity of the item in cart. $offerproducts = array(); foreach ($products as $product) { $productObj = new Product($product['id_product'], true); $tags = $productObj->getTags(1); //print_r($productObj); if (in_array('buy1get1', $tags)) { self::$smarty->assign("spl_voucher_message", "You are eligible for Buy 1 Get 1 Offer"); //counting the b1g1 products $offeredProducts = $offeredProducts + $product['cart_quantity']; } else { if (in_array('buy2get3', $tags)) { self::$smarty->assign("spl_voucher_message", "You are eligible for buy 3 pay for 2 offer"); //counting the b1g1 products $offeredProducts = $offeredProducts + $product['cart_quantity']; } } //adding rows to interesting array $b1g1products for ($q = 0; $q < $product['cart_quantity']; $q++) { array_push($offerproducts, $product); } } //sorting products in ascending order of price usort($offerproducts, function ($prod1, $prod2) { return $prod1['price'] - $prod2['price']; }); ///echo "<pre>";print_r($offerproducts); if (in_array('buy1get1', $tags)) { $noOfferedAdvantageAvailable = (int) ($offeredProducts / 2); } elseif (in_array('buy2get3', $tags)) { $noOfferedAdvantageAvailable = (int) ($offeredProducts / 3); } $discount = 0; for ($p = 0; $p < $noOfferedAdvantageAvailable; $p++) { //print_r("offerproducts".$offerproducts[$p]['price']); $discount = $discount + $offerproducts[$p]['price']; //print_r($discount); } if ((int) self::$cart->id_currency != 2) { $discount = Tools::convertPrice($discount, (int) self::$cart->id_currency, false); } $discount = round($discount, 2); $b1g1DiscountInCart = null; $b2g3DiscountInCart = null; $allCartDiscounts = self::$cart->getDiscounts(); //print_r($allCartDiscounts); foreach ($allCartDiscounts as $cartDiscount) { if (strpos($cartDiscount['name'], 'B1G1') === 0) { $b1g1DiscountInCart = new Discount((int) Discount::getIdByName($cartDiscount['name'])); //echo "buy1get1"; } else { if (strpos($cartDiscount['name'], 'B2G3') === 0) { $b2g3DiscountInCart = new Discount((int) Discount::getIdByName($cartDiscount['name'])); //echo "buy2get3"; } } } if (in_array('buy1get1', $tags)) { if ($discount > 0 && empty($b1g1DiscountInCart)) { $new_discount = new Discount(); $new_discount->id_discount_type = 2; $new_discount->value = $discount; // coupon value $new_discount->name = "B1G1" . Tools::rand_string(5); $new_discount->id_currency = 2; $new_discount->quantity = 1; $new_discount->quantity_per_user = 0; $new_discount->date_from = date('Y-m-d H:i:s'); $new_discount->date_to = '2015-08-10 20:00:00'; //validity $new_discount->cumulable_reduction = 1; $languages = Language::getLanguages(); foreach ($languages as $language) { $new_discount->description[$language['id_lang']] = "Buy1 Get1"; } // coupon description $new_discount->add(); $id_discount = Discount::getIdByName($new_discount->name); self::$cart->addDiscount($id_discount); } else { if (!empty($b1g1DiscountInCart)) { $b1g1DiscountInCart->value = (double) $discount; // coupon value if ($b1g1DiscountInCart->value > 0) { $b1g1DiscountInCart->update(); } else { $b1g1DiscountInCart->delete(); } } } } else { if (in_array('buy2get3', $tags)) { if ($discount > 0 && empty($b2g3DiscountInCart)) { $new_discount = new Discount(); $new_discount->id_discount_type = 2; $new_discount->value = $discount; // coupon value $new_discount->name = "B2G3" . Tools::rand_string(5); $new_discount->id_currency = 2; $new_discount->quantity = 1; $new_discount->quantity_per_user = 0; $new_discount->date_from = date('Y-m-d H:i:s'); $new_discount->date_to = '2015-08-10 20:00:00'; //validity $new_discount->cumulable_reduction = 1; $languages = Language::getLanguages(); foreach ($languages as $language) { $new_discount->description[$language['id_lang']] = "Buy2 Get3"; } // coupon description $new_discount->add(); $id_discount = Discount::getIdByName($new_discount->name); self::$cart->addDiscount($id_discount); } else { if (!empty($b2g3DiscountInCart)) { $b2g3DiscountInCart->value = (double) $discount; // coupon value if ($b2g3DiscountInCart->value > 0) { $b2g3DiscountInCart->update(); } else { $b2g3DiscountInCart->delete(); } } } } } /*//pick3pay2 $products = self::$cart->getProducts(true); //print_r($products); $nP3P2Products = 0; // this is a very interesting array, keeps as many rows as there are items in your cart // if there is an item with quantity 2, it will have two rows in that array, // ie item will have as many rows as the quantity of the item in cart. $p3p2products = array(); foreach($products as $product) { $productObj = new Product($product['id_product'], true); $tags = $productObj->getTags(1); if(in_array('pick3pay2', $tags)){ self::$smarty->assign("spl_voucher_message", "Pick 3 and Pay for 2 only offer"); $nP3P2Products = $nP3P2Products + $product['cart_quantity']; for($q = 0; $q < $product['cart_quantity']; $q++){ array_push($p3p2products, $product); } } } //sorting products in ascending order of price usort($p3p2products, function($prod1, $prod2){ return $prod1['price'] - $prod2['price']; }); $noP3P2AdvantageAvailable = (int)($nP3P2Products/3); print_r($noP3P2AdvantageAvailable); $discount = 0; for($p = 0; $p < $noP3P2AdvantageAvailable; $p++){ $discount = $discount + $p3p2products[$p]['price']; } if((int)self::$cart->id_currency != 2){ $discount = Tools::convertPrice($discount, (int)self::$cart->id_currency, false); } $discount = round($discount, 2); $p3p2DiscountInCart = null; $allCartDiscounts = self::$cart->getDiscounts(); foreach ($allCartDiscounts as $cartDiscount) { //print_r($cartDiscount);print_r('<br/>');die; if(strpos('P3P2', $cartDiscount['name']) == 0){ $p3p2DiscountInCart = new Discount((int) (Discount::getIdByName($cartDiscount['name']))); } } if($discount > 0 && empty($p3p2DiscountInCart)){ $new_discount = new Discount(); $new_discount->id_discount_type = 2; $new_discount->value = $discount; // coupon value $new_discount->name = "P3P2" . Tools::rand_string(5); $new_discount->id_currency = 2; $new_discount->quantity = 1; $new_discount->quantity_per_user = 100; $new_discount->date_from = date('Y-m-d H:i:s'); $new_discount->date_to = '2015-09-10 20:00:00'; //validity $new_discount->cumulable_reduction = 1; $languages = Language::getLanguages(); foreach ($languages as $language) $new_discount->description[$language['id_lang']] = "Pick3 Pay2"; // coupon description $new_discount->add(); $id_discount = Discount::getIdByName($new_discount->name); print_r($id_discount); self::$cart->addDiscount($id_discount); }else if(!empty($p3p2DiscountInCart)){ $p3p2DiscountInCart->value = (float) $discount; // coupon value if($p3p2DiscountInCart->value > 0) $p3p2DiscountInCart->update(); else $p3p2DiscountInCart->delete(); }*/ }
/** * 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); } }
$voucher->description[$lang['id_lang']] = $name[$sel]; } $voucher->name = $code; if ($trigger[$sel]['discountType'] == 'amount') { $voucher->id_discount_type = 2; } else { $voucher->id_discount_type = 1; } $voucher->value = $trigger[$sel]['discount']; $voucher->quantity = 1; $voucher->quantity_per_user = 1; } $voucher->id_customer = $customer['id_customer']; $voucher->date_from = date('Y-m-d'); $voucher->date_to = date('Y-m-d', time() + 31 * 24 * 3600); $voucher->active = 1; $voucher->add(); } /* mail sending */ if ($res = $mailjet->sendMail($subject, $temp, $customer['email'])) { DB::getInstance()->execute(' INSERT INTO `' . _DB_PREFIX_ . 'mj_trigger`(id_customer,id_target,type,date) VALUES(' . $customer['id_customer'] . ',' . $customer[$sql_target[$sel]] . ',' . $sel . ',\'' . date('Y-m-d') . '\')'); } } } } echo 'OK'; } else { echo 'KO'; }
/** * @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(); }
private function createDiscount($id_email_type, $amount, $id_customer, $dateValidity, $description) { $discount = new Discount(); $discount->id_discount_type = 1; $discount->value = floatval($amount); $discount->id_customer = intval($id_customer); $discount->date_to = $dateValidity; $discount->date_from = date('Y-m-d H:i:s'); $discount->quantity = 1; $discount->quantity_per_user = 1; $discount->cumulable = 0; $discount->cumulable_reduction = 1; $discount->minimal = 0; $discount->description[1] = $description; $discount->description[2] = $description; $name = 'FLW-' . intval($id_email_type) . '-' . strtoupper(Tools::passwdGen(10)); $discount->name = $name; $discount->active = 1; $result = $discount->add(); if (!$result) { return false; } return $discount; }
public static function createOrderDiscount($order, $productList, $qtyList, $name, $shipping_cost = false, $id_category = 0, $subcategory = 0) { $languages = Language::getLanguages($order); $products = $order->getProducts(false, $productList, $qtyList); $total = $order->getTotalProductsWithTaxes($products); if ($shipping_cost) { $total += $order->total_shipping; } // create discount $voucher = new Discount(); $voucher->id_discount_type = 2; foreach ($languages as $language) { $voucher->description[$language['id_lang']] = strval($name) . intval($order->id); } $voucher->value = floatval($total); $voucher->name = 'V0C' . intval($order->id_customer) . 'O' . intval($order->id); $voucher->id_customer = intval($order->id_customer); $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = 1; $voucher->cumulable_reduction = 1; $voucher->minimal = floatval($voucher->value); $voucher->active = 1; $now = time(); $voucher->date_from = date('Y-m-d H:i:s', $now); $voucher->date_to = date('Y-m-d H:i:s', $now + 60 * 60 * 24 * 184); if (!$voucher->validateFieldsLang(false) or !$voucher->add()) { return false; } // set correct name $voucher->name = 'V' . intval($voucher->id) . 'C' . intval($order->id_customer) . 'O' . $order->id; if (!$voucher->update()) { return false; } return $voucher; }
/** * Added Dotpay discount for reducing shipping cost * @return bool */ private function addDotpayDiscount() { if (!Validate::isInt($this->config->getDotpayDiscountId())) { $voucher = new Discount(); $voucher->id_discount_type = Discount::AMOUNT; $voucher->name = array((int) Configuration::get('PS_LANG_DEFAULT') => 'Discount for online shopping'); $voucher->description = array((int) Configuration::get('PS_LANG_DEFAULT') => 'Online payment'); $voucher->value = 0; $voucher->code = md5(date("d-m-Y H-i-s")); $voucher->quantity = 9999999; $voucher->quantity_per_user = 9999999; $voucher->cumulable = 1; $voucher->cumulable_reduction = 1; $voucher->active = 1; $voucher->cart_display = 1; $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.25 * 50); if (!$voucher->add()) { return false; } $this->config->setDotpayDiscountId($voucher->id); } return true; }
public function registerDiscount($id_customer, $register = false, $id_currency = 0) { $configurations = Configuration::getMultiple(array('REFERRAL_DISCOUNT_TYPE', 'REFERRAL_PERCENTAGE', 'REFERRAL_DISCOUNT_VALUE_' . (int) $id_currency)); $discount = new Discount(); $discount->id_discount_type = (int) $configurations['REFERRAL_DISCOUNT_TYPE']; /* % */ if ($configurations['REFERRAL_DISCOUNT_TYPE'] == 1) { $discount->value = (double) $configurations['REFERRAL_PERCENTAGE']; } elseif ($configurations['REFERRAL_DISCOUNT_TYPE'] == 2 and isset($configurations['REFERRAL_DISCOUNT_VALUE_' . (int) $id_currency])) { $discount->value = (double) $configurations['REFERRAL_DISCOUNT_VALUE_' . (int) $id_currency]; } else { $discount->value = 0; } $discount->quantity = 1; $discount->quantity_per_user = 1; $discount->date_from = date('Y-m-d H:i:s', time()); $discount->date_to = date('Y-m-d H:i:s', time() + 31536000); // + 1 year $discount->name = $this->getDiscountPrefix() . Tools::passwdGen(6); $discount->description = Configuration::getInt('REFERRAL_DISCOUNT_DESCRIPTION'); $discount->id_customer = (int) $id_customer; $discount->id_currency = (int) $id_currency; if ($discount->add()) { if ($register != false) { if ($register == 'sponsor') { $this->id_discount_sponsor = (int) $discount->id; } elseif ($register == 'sponsored') { $this->id_discount = (int) $discount->id; } return $this->save(); } return true; } return false; }
} $cart->addCartRule($voucher->id); } else { $voucher = new Discount(); $voucher->id_discount_type = 2; $voucher->value = $amount; $languages = Language::getLanguages(true); $voucher->name = 'Fid\'Bag'; $voucher->description = 'Discount Fid\'Bag'; $voucher->id_customer = (int) $cart->id_customer; $voucher->id_currency = (int) $cart->id_currency; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = 1; $voucher->cumulable_reduction = 1; $voucher->minimal = (double) $voucher->value; $voucher->include_tax = 1; $voucher->active = 1; $voucher->cart_display = 1; $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.25); if (!$voucher->validateFieldsLang(false) || !$voucher->add()) { die('0'); } $cart->addDiscount($voucher->id); Discount::getVouchersToCartDisplay(1, $cart->id_customer); } } $values = array('total' => Tools::ps_round($cart->getOrderTotal(), $currency->decimals), 'discount' => $amount); die(Tools::jsonEncode($values));
public static function createOrderDiscount($order, $productList, $qtyList, $name, $shipping_cost = false, $id_category = 0, $subcategory = 0) { $languages = Language::getLanguages($order); $products = $order->getProducts(false, $productList, $qtyList); // Totals are stored in the order currency (or at least should be) $total = $order->getTotalProductsWithTaxes($products); $discounts = $order->getDiscounts(true); $total_tmp = $total; foreach ($discounts as $discount) { if ($discount['id_discount_type'] == 1) { $total -= $total_tmp * ($discount['value'] / 100); } elseif ($discount['id_discount_type'] == 2) { $total -= $discount['value'] * ($total_tmp / $order->total_products_wt); } } if ($shipping_cost) { $total += $order->total_shipping; } // create discount $voucher = new Discount(); $voucher->id_discount_type = 2; foreach ($languages as $language) { $voucher->description[$language['id_lang']] = strval($name) . (int) $order->id; } $voucher->value = (double) $total; $voucher->name = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id; $voucher->id_customer = (int) $order->id_customer; $voucher->id_currency = (int) $order->id_currency; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = 1; $voucher->cumulable_reduction = 1; $voucher->minimal = (double) $voucher->value; $voucher->active = 1; $voucher->cart_display = 1; $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.25); /* 1 year */ if (!$voucher->validateFieldsLang(false) or !$voucher->add()) { return false; } // set correct name $voucher->name = 'V' . (int) $voucher->id . 'C' . (int) $order->id_customer . 'O' . $order->id; if (!$voucher->update()) { return false; } return $voucher; }
public static function addCoupons($idCustomer) { global $cookie; if ((int) $cookie->id_country === 110) { $vouchers = array("6" => array('INR 300 off on order over INR 1500', Tools::ps_round(Tools::convertPrice(300, Currency::getCurrencyInstance(4), false)), Tools::ps_round(Tools::convertPrice(1500, Currency::getCurrencyInstance(4), false)), 3600 * 24 * 30 * 1), "7" => array('INR 700 off on order over INR 3000', Tools::ps_round(Tools::convertPrice(700, Currency::getCurrencyInstance(4), false)), Tools::ps_round(Tools::convertPrice(3000, Currency::getCurrencyInstance(4), false)), 3600 * 24 * 30 * 1), "8" => array('INR 1500 off on order over INR 5000', Tools::ps_round(Tools::convertPrice(1500, Currency::getCurrencyInstance(4), false)), Tools::ps_round(Tools::convertPrice(5000, Currency::getCurrencyInstance(4), false)), 3600 * 24 * 30 * 1)); } else { $vouchers = array("6" => array('USD 15 off on order over USD 100', 15, 100.0, 3600 * 24 * 30 * 1), "7" => array('USD 30 off on order over USD 200', 30, 200.0, 3600 * 24 * 30 * 2), "8" => array('USD 55 off on order over USD 300', 55, 300.0, 3600 * 24 * 30 * 3)); } foreach ($vouchers as $idCoupon => $coupon) { $couponCode = "" . $idCustomer . $idCoupon . Tools::rand_string(3); // create discount $languages = Language::getLanguages($order); $voucher = new Discount(); $voucher->id_discount_type = 2; foreach ($languages as $language) { $voucher->description[$language['id_lang']] = $coupon[0]; } // coupon description $voucher->value = (double) $coupon[1]; // coupon value $voucher->name = $couponCode; $voucher->id_customer = $idCustomer; $voucher->id_currency = 2; //USD $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = 0; $voucher->cumulable_reduction = 1; $voucher->minimal = (double) $coupon[2]; // min order value $voucher->active = 1; $voucher->cart_display = 1; $now = time(); $voucher->date_from = date('Y-m-d H:i:s', $now); $voucher->date_to = date('Y-m-d H:i:s', $now + $coupon[3]); //validity if (!$voucher->validateFieldsLang(false) or !$voucher->add()) { return false; } } }