Initial commit

This commit is contained in:
2019-11-20 07:44:43 +01:00
commit 5bf49c4a81
41188 changed files with 5459177 additions and 0 deletions

View File

@@ -0,0 +1,842 @@
<?php
/**
* installmentpayment.php, Allows you to set a percentage payment for orders
* @author Magavenue <contact@magavenue.com>
* @copyright Magavenue
* @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
* @category modules
*
* @note If you want to customize the module, contact us at contact@magavenue.com
*/
use PrestaShop\PrestaShop\Adapter\ServiceLocator;
class Cart extends CartCore
{
public function getSummaryDetails($id_lang = null, $refresh = false)
{
$summary = $this->getSummaryDetailsInstallment($id_lang, $refresh);
if (!Module::isEnabled('freelivery')) {
return $summary;
}
if (!isset(Context::getContext()->cart)) {
return $summary;
}
$ps_free_price = Tools::convertPrice(Configuration::get('PS_SHIPPING_FREE_PRICE'), Currency::getCurrencyInstance(Context::getContext()->cart->id_currency));
$total = $summary['total_products_wt'];
if ((int) Configuration::get('FREELIVERY_CALCULATION_RULE')) {
$total += $summary['total_discounts'];
}
$ps_remaining = $ps_free_price - $total;
$freelivery_remaining = isset($GLOBALS['freelivery_remaining']) ? $GLOBALS['freelivery_remaining'] : false;
if ($summary['total_shipping'] == 0 || ($total >= $ps_free_price && $ps_free_price > 0)) {
$summary['freelivery_remaining'] = 0;
} elseif ($ps_remaining < $freelivery_remaining && $ps_free_price > 0) {
$summary['freelivery_remaining'] = $ps_remaining;
} else {
$summary['freelivery_remaining'] = (float) $freelivery_remaining;
}
$summary['free_ship'] = $summary['freelivery_remaining'] > 0 ? 0 : 1; // Can't set to true/false because of old 1.6 versions
return $summary;
}
public function getPackageShippingCost($id_carrier = null, $use_tax = true, Country $default_country = null, $product_list = null, $id_zone = null)
{
$_GET['id_cart_freelivery'] = $this->id;
return parent::getPackageShippingCost($id_carrier, $use_tax, $default_country, $product_list, $id_zone);
}
public static function debugBacktraceUrl($start = 0, $limit = null)
{
$backtrace = debug_backtrace();
array_shift($backtrace);
for ($i = 0; $i < $start; ++$i) {
array_shift($backtrace);
}
$data = array();
$i = 0;
foreach ($backtrace as $id => $trace) {
if ((int) $limit && ( ++$i > $limit)) {
break;
}
$relative_file = (isset($trace['file'])) ? 'in /' . ltrim(str_replace(array(_PS_ROOT_DIR_, '\\'), array('', '/'), $trace['file']), '/') : '';
$current_line = (isset($trace['line'])) ? ':' . $trace['line'] : '';
$fileName = ((isset($trace['class'])) ? $trace['class'] : '') . ((isset($trace['type'])) ? $trace['type'] : '') . $trace['function'];
$data[$relative_file] = $fileName;
}
return $data;
}
/**
* This function returns the total cart amount
*
* Possible values for $type:
* Cart::ONLY_PRODUCTS
* Cart::ONLY_DISCOUNTS
* Cart::BOTH
* Cart::BOTH_WITHOUT_SHIPPING
* Cart::ONLY_SHIPPING
* Cart::ONLY_WRAPPING
* Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING
* Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING
*
* @param bool $withTaxes With or without taxes
* @param int $type Total type
* @param bool $use_cache Allow using cache of the method CartRule::getContextualValue
* @return float Order total
*/
public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true, $gross = false, $small = false)
{
$address_factory = ServiceLocator::get('\\PrestaShop\\PrestaShop\\Adapter\\AddressFactory');
$price_calculator = ServiceLocator::get('\\PrestaShop\\PrestaShop\\Adapter\\Product\\PriceCalculator');
$configuration = ServiceLocator::get('\\PrestaShop\\PrestaShop\\Core\\ConfigurationInterface');
$ps_tax_address_type = $configuration->get('PS_TAX_ADDRESS_TYPE');
$ps_use_ecotax = $configuration->get('PS_USE_ECOTAX');
$ps_round_type = $configuration->get('PS_ROUND_TYPE');
$ps_ecotax_tax_rules_group_id = $configuration->get('PS_ECOTAX_TAX_RULES_GROUP_ID');
$compute_precision = $configuration->get('_PS_PRICE_COMPUTE_PRECISION_');
$pre_commande = false;
$backtrace = $this->debugBacktraceUrl();
$i = 1;
foreach ($backtrace as $backtracekey => $backtracevalue) {
if ($i == 1 && strpos($backtracekey, '/modules/') !== false && (int) Configuration::get('ACOMPTE_CHOICE') == 1 || $i == 1 && strpos($backtracekey, '/modules/') !== false && isset(Context::getContext()->cookie->installmentpayment_type) && (int) Context::getContext()->cookie->installmentpayment_type > 0) {
$small = true;
}
$i++;
}
if (!$this->id) {
return 0;
}
$type = (int) $type;
$array_type = array(
Cart::ONLY_PRODUCTS,
Cart::ONLY_DISCOUNTS,
Cart::BOTH,
Cart::BOTH_WITHOUT_SHIPPING,
Cart::ONLY_SHIPPING,
Cart::ONLY_WRAPPING,
Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING,
Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING,
);
$virtual_context = Context::getContext()->cloneContext();
$virtual_context->cart = $this;
if (!in_array($type, $array_type)) {
die(Tools::displayError());
}
$with_shipping = in_array($type, array(Cart::BOTH, Cart::ONLY_SHIPPING));
if ($type == Cart::ONLY_DISCOUNTS && !CartRule::isFeatureActive()) {
return 0;
}
$virtual = $this->isVirtualCart();
if ($virtual && $type == Cart::ONLY_SHIPPING) {
return 0;
}
if ($virtual && $type == Cart::BOTH) {
$type = Cart::BOTH_WITHOUT_SHIPPING;
}
if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
if (is_null($products) && is_null($id_carrier)) {
$shipping_fees = $this->getTotalShippingCost(null, (bool) $with_taxes);
} else {
$shipping_fees = $this->getPackageShippingCost((int) $id_carrier, (bool) $with_taxes, null, $products);
}
} else {
$shipping_fees = 0;
}
if ($type == Cart::ONLY_SHIPPING) {
return $shipping_fees;
}
if ($type == Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING) {
$type = Cart::ONLY_PRODUCTS;
}
$param_product = true;
if (is_null($products)) {
$param_product = false;
$products = $this->getProducts();
}
if ($type == Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING) {
foreach ($products as $key => $product) {
if ($product['is_virtual']) {
unset($products[$key]);
}
}
$type = Cart::ONLY_PRODUCTS;
}
$order_total = 0;
if (Tax::excludeTaxeOption()) {
$with_taxes = false;
}
$products_total = array();
$ecotax_total = 0;
foreach ($products as $product) {
if ($virtual_context->shop->id != $product['id_shop']) {
$virtual_context->shop = new Shop((int) $product['id_shop']);
}
if ($ps_tax_address_type == 'id_address_invoice') {
$id_address = (int) $this->id_address_invoice;
} else {
$id_address = (int) $product['id_address_delivery'];
} // Get delivery address of the product from the cart
if (!$address_factory->addressExists($id_address)) {
$id_address = null;
}
$null = null;
$price = $price_calculator->getProductPrice(
(int) $product['id_product'],
$with_taxes,
(int) $product['id_product_attribute'],
6,
null,
false,
true,
$product['cart_quantity'],
false,
(int) $this->id_customer ? (int) $this->id_customer : null,
(int) $this->id,
$id_address,
$null,
$ps_use_ecotax,
true,
$virtual_context
);
$address = $address_factory->findOrCreate($id_address, true);
if ($with_taxes) {
$id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product'], $virtual_context);
$tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
} else {
$id_tax_rules_group = 0;
}
if (in_array($ps_round_type, array(Order::ROUND_ITEM, Order::ROUND_LINE))) {
if (!isset($products_total[$id_tax_rules_group])) {
$products_total[$id_tax_rules_group] = 0;
}
} elseif (!isset($products_total[$id_tax_rules_group . '_' . $id_address])) {
$products_total[$id_tax_rules_group . '_' . $id_address] = 0;
}
switch ($ps_round_type) {
case Order::ROUND_TOTAL:
$products_total[$id_tax_rules_group . '_' . $id_address] += $price * (int) $product['cart_quantity'];
break;
case Order::ROUND_LINE:
$product_price = $price * $product['cart_quantity'];
$products_total[$id_tax_rules_group] += Tools::ps_round($product_price, $compute_precision);
break;
case Order::ROUND_ITEM:
default:
$product_price = $price;
$products_total[$id_tax_rules_group] += Tools::ps_round($product_price, $compute_precision) * (int) $product['cart_quantity'];
break;
}
}
foreach ($products_total as $key => $price) {
$order_total += $price;
}
$order_total_products = $order_total;
if ($type == Cart::ONLY_DISCOUNTS) {
$order_total = 0;
}
$wrapping_fees = 0;
$include_gift_wrapping = (!$configuration->get('PS_ATCP_SHIPWRAP') || $type !== Cart::ONLY_PRODUCTS);
if ($this->gift && $include_gift_wrapping) {
$wrapping_fees = Tools::convertPrice(Tools::ps_round($this->getGiftWrappingPrice($with_taxes), $compute_precision), Currency::getCurrencyInstance((int) $this->id_currency));
}
if ($type == Cart::ONLY_WRAPPING) {
return $wrapping_fees;
}
$order_total_discount = 0;
$order_shipping_discount = 0;
if (!in_array($type, array(Cart::ONLY_SHIPPING, Cart::ONLY_PRODUCTS)) && CartRule::isFeatureActive()) {
if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
$cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_ALL);
} else {
$cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_REDUCTION);
foreach ($this->getCartRules(CartRule::FILTER_ACTION_GIFT) as $tmp_cart_rule) {
$flag = false;
foreach ($cart_rules as $cart_rule) {
if ($tmp_cart_rule['id_cart_rule'] == $cart_rule['id_cart_rule']) {
$flag = true;
}
}
if (!$flag) {
$cart_rules[] = $tmp_cart_rule;
}
}
}
$id_address_delivery = 0;
if (isset($products[0])) {
$id_address_delivery = (is_null($products) ? $this->id_address_delivery : $products[0]['id_address_delivery']);
}
$package = array('id_carrier' => $id_carrier, 'id_address' => $id_address_delivery, 'products' => $products);
$flag = false;
foreach ($cart_rules as $cart_rule) {
if (($with_shipping || $type == Cart::ONLY_DISCOUNTS) && $cart_rule['obj']->free_shipping && !$flag) {
$order_shipping_discount = (float) Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_SHIPPING, ($param_product ? $package : null), $use_cache), $compute_precision);
$flag = true;
}
if ((int) $cart_rule['obj']->gift_product) {
$in_order = false;
if (is_null($products)) {
$in_order = true;
} else {
foreach ($products as $product) {
if ($cart_rule['obj']->gift_product == $product['id_product'] && $cart_rule['obj']->gift_product_attribute == $product['id_product_attribute']) {
$in_order = true;
}
}
}
if ($in_order) {
$order_total_discount += $cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_GIFT, $package, $use_cache);
}
}
if ($cart_rule['obj']->reduction_percent > 0 || $cart_rule['obj']->reduction_amount > 0) {
$order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_REDUCTION, $package, $use_cache), $compute_precision);
}
}
$order_total_discount = min(Tools::ps_round($order_total_discount, 2), (float) $order_total_products) + (float) $order_shipping_discount;
$order_total -= $order_total_discount;
}
if ($type == Cart::BOTH) {
$order_total += $shipping_fees + $wrapping_fees;
}
if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS) {
return 0;
}
if ($type == Cart::ONLY_DISCOUNTS) {
return $order_total_discount;
}
$page_name = Dispatcher::getInstance()->getController();
$pages_name = array();
$controllers = Dispatcher::getControllers(_PS_FRONT_CONTROLLER_DIR_);
foreach ($controllers as $key => $value) {
if ($key != 'orderconfirmation' && $key != 'pagenotfound') {
$pages_name[] = $key;
}
}
$groups = Db::getInstance()->executeS('SELECT id_group FROM ' . _DB_PREFIX_ . 'customer_group WHERE id_customer = ' . (int) Context::getContext()->customer->id);
$groupIdsTakenFromDb = Configuration::get('ACOMPTE_GROUP');
$selectedgroups = @unserialize($groupIdsTakenFromDb);
if ($selectedgroups === false && $selectedgroups !== 'b:0;') {
$selectedgroups = array();
}
$group_accepted = false;
foreach ($groups as $group) {
if (in_array($group['id_group'], $selectedgroups)) {
$group_accepted = true;
break;
}
}
$categoryIdsTakenFromDb = Configuration::get('ACOMPTE_CATS');
$selectedcategories = @unserialize($categoryIdsTakenFromDb);
if ($selectedcategories === false && $selectedcategories !== 'b:0;') {
$selectedcategories = array();
}
if ($group_accepted && ($type == Cart::BOTH || ($virtual && $type == Cart::BOTH_WITHOUT_SHIPPING)) && ((float) Configuration::get('ACOMPTE_MIN_AMOUNT') == 0 || $order_total > (float) Configuration::get('ACOMPTE_MIN_AMOUNT')) && !empty($selectedcategories)) {
if (is_array($this->_products) && !empty($this->_products)) {
foreach ($this->_products as $product) {
if (in_array((int) $product['id_category_default'], $selectedcategories)) {
$pre_commande = true;
break;
} else {
/**/
$sql = 'SELECT id_product FROM `' . _DB_PREFIX_ . 'category_product` WHERE `id_product` = ' . (int) $product['id_product'] . ' AND `id_category` IN (';
foreach ($selectedcategories as $category) {
$sql .= (int) $category . ',';
}
$sql = rtrim($sql, ',') . ')';
/**/
if (Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql)) {
$pre_commande = true;
break;
}
}
}
}
if ($pre_commande && ((isset(Context::getContext()->cookie->installmentpayment_type) && (int) Context::getContext()->cookie->installmentpayment_type > 0) || (int) Configuration::get('ACOMPTE_CHOICE') == 1 || $page_name == 'installmentpayment')) {
if (((!in_array($page_name, $pages_name) || (($page_name == 'order' && Tools::getValue('step') == 3) || $page_name == 'order-opc')) && !$gross) || $small) {
if ((int) Configuration::get('ACOMPTE_TOTALTYPE') != 0 || (int) Configuration::get('ACOMPTE_SHIPPING') != 0) {
$order_total = 0;
if ((int) Configuration::get('ACOMPTE_TOTALTYPE') == 0) {
foreach ($products_total as $key => $price) {
if (Configuration::get('PS_ROUND_TYPE') == Order::ROUND_TOTAL) {
$tmp = explode('_', $key);
$address = Address::initialize((int) $tmp[1], true);
$tax_calculator = TaxManagerFactory::getManager($address, $tmp[0])->getTaxCalculator();
$order_total += Tools::ps_round($price + $tax_calculator->getTaxesTotalAmount($price), _PS_PRICE_COMPUTE_PRECISION_);
} else {
$order_total += $price;
}
}
} else {
foreach ($products as $product) { // products refer to the cart details
if ($virtual_context->shop->id != $product['id_shop']) {
$virtual_context->shop = new Shop((int) $product['id_shop']);
}
if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
$id_address = (int) $this->id_address_invoice;
} else {
$id_address = (int) $product['id_address_delivery']; // Get delivery address of the product from the cart
}
if (!Address::addressExists($id_address)) {
$id_address = null;
}
$price = Product::getPriceStatic(
(int) $product['id_product'],
false,
(int) $product['id_product_attribute'],
6,
null,
false,
true,
$product['cart_quantity'],
false,
(int) $this->id_customer ? (int) $this->id_customer : null,
(int) $this->id,
$id_address,
null,
false,
true,
$virtual_context
);
$order_total += $price * $product['cart_quantity'];
}
}
if ((int) Configuration::get('ACOMPTE_SHIPPING') == 0) {
$order_total += $shipping_fees + $wrapping_fees;
}
}//else
$id_defaultgroup = Db::getInstance()->executeS('SELECT id_default_group FROM ' . _DB_PREFIX_ . 'customer WHERE id_customer = ' . (int) Context::getContext()->customer->id);
if(is_array($id_defaultgroup))
{
$id_defaultgroup = $id_defaultgroup[0]['id_default_group'];
}
$sql = 'SELECT price FROM `' . _DB_PREFIX_ . 'installmentpayment_group` WHERE id_group=' . (int) $id_defaultgroup;
$data = Db::getInstance()->getRow($sql);
if(!empty($data)){
$order_total = $order_total - ($order_total * (100 - $data['price']) / 100);
}
else
{
if ((int) Configuration::get('ACOMPTE_TYPE') == 1) {
if ($order_total > (float) Configuration::get('ACOMPTE_PERCENTAGE')) {
$order_total = (float) Configuration::get('ACOMPTE_PERCENTAGE');
}
} else {
$order_total = $order_total - ($order_total * (100 - Configuration::get('ACOMPTE_PERCENTAGE')) / 100);
}
}
}
if ($page_name == 'installmentpayment' || (isset(Context::getContext()->cookie->installmentpayment_id_order) && !empty(Context::getContext()->cookie->installmentpayment_id_order))) {
if (Tools::getValue('select') != '') {
Context::getContext()->cookie->__set('installmentpayment_id_order', (int) Tools::getValue('select'));
}
$order = new Order((int) Context::getContext()->cookie->installmentpayment_id_order);
$sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'installmentpayment` WHERE id_cart=' . (int) $order->id_cart;
$installment = Db::getInstance()->getRow($sql);
if (isset($installment['rest']) && (float) $installment['rest'] > 0) {
$rest_paid = $installment['rest'];
$order_total = $rest_paid;
}
}
}
}
return Tools::ps_round((float) $order_total, _PS_PRICE_COMPUTE_PRECISION_);
}
public function getOrderTotalGross($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true, $small = false)
{
return $this->getOrderTotal($with_taxes, $type, $products, $id_carrier, $use_cache, true);
}
public function getOrderTotalSmall($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true, $small = true)
{
return $this->getOrderTotal($with_taxes, $type, $products, $id_carrier, $use_cache, true, true);
}
/**
* Return useful informations for cart
*
* @return array Cart details
*/
public function getSummaryDetailsInstallment($id_lang = null, $refresh = false)
{
$context = Context::getContext();
if (!$id_lang) {
$id_lang = $context->language->id;
}
$delivery = new Address((int) $this->id_address_delivery);
$invoice = new Address((int) $this->id_address_invoice);
$formatted_addresses = array(
'delivery' => AddressFormat::getFormattedLayoutData($delivery),
'invoice' => AddressFormat::getFormattedLayoutData($invoice)
);
$base_total_tax_inc = $this->getOrderTotalGross(true);
$base_total_tax_exc = $this->getOrderTotalGross(false);
$total_tax = $base_total_tax_inc - $base_total_tax_exc;
if ($total_tax < 0) {
$total_tax = 0;
}
$currency = new Currency($this->id_currency);
$products = $this->getProducts($refresh);
$gift_products = array();
$cart_rules = $this->getCartRules();
$total_shipping = $this->getTotalShippingCost();
$total_shipping_tax_exc = $this->getTotalShippingCost(null, false);
$total_products_wt = $this->getOrderTotalGross(true, Cart::ONLY_PRODUCTS);
$total_products = $this->getOrderTotalGross(false, Cart::ONLY_PRODUCTS);
$total_discounts = $this->getOrderTotalGross(true, Cart::ONLY_DISCOUNTS);
$total_discounts_tax_exc = $this->getOrderTotalGross(false, Cart::ONLY_DISCOUNTS);
foreach ($cart_rules as &$cart_rule) {
if ($cart_rule['free_shipping'] && (empty($cart_rule['code']) || preg_match('/^' . CartRule::BO_ORDER_CODE_PREFIX . '[0-9]+/', $cart_rule['code']))) {
$cart_rule['value_real'] -= $total_shipping;
$cart_rule['value_tax_exc'] -= $total_shipping_tax_exc;
$cart_rule['value_real'] = Tools::ps_round($cart_rule['value_real'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
$cart_rule['value_tax_exc'] = Tools::ps_round($cart_rule['value_tax_exc'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
if ($total_discounts > $cart_rule['value_real']) {
$total_discounts -= $total_shipping;
}
if ($total_discounts_tax_exc > $cart_rule['value_tax_exc']) {
$total_discounts_tax_exc -= $total_shipping_tax_exc;
}
$total_shipping = 0;
$total_shipping_tax_exc = 0;
}
if ($cart_rule['gift_product']) {
foreach ($products as $key => &$product) {
if (empty($product['gift']) && $product['id_product'] == $cart_rule['gift_product'] && $product['id_product_attribute'] == $cart_rule['gift_product_attribute']) {
$total_products_wt = Tools::ps_round($total_products_wt - $product['price_wt'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
$total_products = Tools::ps_round($total_products - $product['price'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
$total_discounts = Tools::ps_round($total_discounts - $product['price_wt'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
$total_discounts_tax_exc = Tools::ps_round($total_discounts_tax_exc - $product['price'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
$cart_rule['value_real'] = Tools::ps_round($cart_rule['value_real'] - $product['price_wt'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
$cart_rule['value_tax_exc'] = Tools::ps_round($cart_rule['value_tax_exc'] - $product['price'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
$product['total_wt'] = Tools::ps_round($product['total_wt'] - $product['price_wt'], (int) $currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
$product['total'] = Tools::ps_round($product['total'] - $product['price'], (int) $currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
$product['cart_quantity'] --;
if (!$product['cart_quantity']) {
unset($products[$key]);
}
$gift_product = $product;
$gift_product['cart_quantity'] = 1;
$gift_product['price'] = 0;
$gift_product['price_wt'] = 0;
$gift_product['total_wt'] = 0;
$gift_product['total'] = 0;
$gift_product['gift'] = true;
$gift_products[] = $gift_product;
break; // One gift product per cart rule
}
}
}
}
foreach ($cart_rules as $key => &$cart_rule) {
if ((float) $cart_rule['value_real'] == 0 && (int) $cart_rule['free_shipping'] == 0) {
unset($cart_rules[$key]);
}
}
return array(
'delivery' => $delivery,
'delivery_state' => State::getNameById($delivery->id_state),
'invoice' => $invoice,
'invoice_state' => State::getNameById($invoice->id_state),
'formattedAddresses' => $formatted_addresses,
'products' => array_values($products),
'gift_products' => $gift_products,
'discounts' => array_values($cart_rules),
'is_virtual_cart' => (int) $this->isVirtualCart(),
'total_discounts' => $total_discounts,
'total_discounts_tax_exc' => $total_discounts_tax_exc,
'total_wrapping' => $this->getOrderTotalGross(true, Cart::ONLY_WRAPPING),
'total_wrapping_tax_exc' => $this->getOrderTotalGross(false, Cart::ONLY_WRAPPING),
'total_shipping' => $total_shipping,
'total_shipping_tax_exc' => $total_shipping_tax_exc,
'total_products_wt' => $total_products_wt,
'total_products' => $total_products,
'total_price' => $base_total_tax_inc,
'total_tax' => $total_tax,
'total_price_without_tax' => $base_total_tax_exc,
'is_multi_address_delivery' => $this->isMultiAddressDelivery() || ((int) Tools::getValue('multi-shipping') == 1),
'free_ship' => $total_shipping ? 0 : 1,
'carrier' => new Carrier($this->id_carrier, $id_lang),
);
}
/**
* Return cart products
*
* @result array Products
*/
public function getProducts($refresh = false, $id_product = false, $id_country = null, $fullInfos = true)
{
if (Dispatcher::getInstance()->getController() != "pagenotfound" || strpos($_SERVER['REQUEST_URI'], '/modules/paypal') === false) {
return parent::getProducts();
}
if (!$this->id) {
return array();
}
if ($this->_products !== null && !$refresh) {
if (is_int($id_product)) {
foreach ($this->_products as $product) {
if ($product['id_product'] == $id_product) {
return array($product);
}
}
return array();
}
return $this->_products;
}
$sql = new DbQuery();
$sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
pl.`description_short`, pl.`available_now`, pl.`available_later`, product_shop.`id_category_default`, p.`id_supplier`,
p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`,
stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference, IFNULL(sp.`reduction_type`, 0) AS reduction_type');
$sql->from('cart_product', 'cp');
$sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
$sql->innerJoin('product_shop', 'product_shop', '(product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)');
$sql->leftJoin('product_lang', 'pl', '
p.`id_product` = pl.`id_product`
AND pl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop'));
$sql->leftJoin('category_lang', 'cl', '
product_shop.`id_category_default` = cl.`id_category`
AND cl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop'));
$sql->leftJoin('product_supplier', 'ps', 'ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`');
$sql->leftJoin('specific_price', 'sp', 'sp.`id_product` = cp.`id_product`'); // AND 'sp.`id_shop` = cp.`id_shop`
$sql->join(Product::sqlStock('cp', 'cp'));
$sql->where('cp.`id_cart` = ' . (int) $this->id);
if ($id_product) {
$sql->where('cp.`id_product` = ' . (int) $id_product);
}
$sql->where('p.`id_product` IS NOT NULL');
$sql->groupBy('unique_id');
$sql->orderBy('cp.`date_add`, p.`id_product`, cp.`id_product_attribute` ASC');
if (Customization::isFeatureActive()) {
$sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
$sql->leftJoin('customization', 'cu', 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = ' . (int) $this->id);
} else {
$sql->select('NULL AS customization_quantity, NULL AS id_customization');
}
if (Combination::isFeatureActive()) {
$sql->select('
product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
(p.`weight`+ pa.`weight`) weight_attribute,
IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity,
IF(product_attribute_shop.wholesale_price > 0, product_attribute_shop.wholesale_price, product_shop.`wholesale_price`) wholesale_price
');
$sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
$sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.`id_shop` = cp.`id_shop` AND product_attribute_shop.`id_product_attribute` = pa.`id_product_attribute`)');
$sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
$sql->leftJoin('image_lang', 'il', 'il.`id_image` = pai.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang);
} else {
$sql->select(
'p.`reference` AS reference, p.`ean13`,
p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity, product_shop.`wholesale_price` wholesale_price'
);
}
$result = Db::getInstance()->executeS($sql);
$products_ids = array();
$pa_ids = array();
if ($result) {
foreach ($result as $row) {
$products_ids[] = $row['id_product'];
$pa_ids[] = $row['id_product_attribute'];
}
}
Product::cacheProductsFeatures($products_ids);
Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
$this->_products = array();
if (empty($result)) {
return array();
}
$cart_shop_context = Context::getContext()->cloneContext();
foreach ($result as &$row) {
if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0) {
$row['ecotax'] = (float) $row['ecotax_attr'];
}
$row['stock_quantity'] = (int) $row['quantity'];
$row['quantity'] = (int) $row['cart_quantity'];
if (isset($row['id_product_attribute']) && (int) $row['id_product_attribute'] && isset($row['weight_attribute'])) {
$row['weight'] = (float) $row['weight_attribute'];
}
if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
$address_id = (int) $this->id_address_invoice;
} else {
$address_id = (int) $row['id_address_delivery'];
}
if (!Address::addressExists($address_id)) {
$address_id = null;
}
if ($cart_shop_context->shop->id != $row['id_shop']) {
$cart_shop_context->shop = new Shop((int) $row['id_shop']);
}
$address = Address::initialize($address_id, true);
$id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $row['id_product'], $cart_shop_context);
$tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
if (!Tools::getIsset('specific_price_output')) {
$specific_price_output = array();
}
$row['price'] = Product::getPriceStatic(
(int) $row['id_product'],
false,
isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null,
6,
null,
false,
true,
$row['cart_quantity'],
false,
(int) $this->id_customer ? (int) $this->id_customer : null,
(int) $this->id,
$address_id,
$specific_price_output,
false,
true,
$cart_shop_context
);
switch (Configuration::get('PS_ROUND_TYPE')) {
case Order::ROUND_TOTAL:
$row['total'] = $row['price'] * (int) $row['cart_quantity'];
$row['total_wt'] = $tax_calculator->addTaxes($row['price']) * (int) $row['cart_quantity'];
break;
case Order::ROUND_LINE:
$row['total'] = Tools::ps_round($row['price'] * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
$row['total_wt'] = Tools::ps_round($tax_calculator->addTaxes($row['price']) * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
break;
case Order::ROUND_ITEM:
default:
$row['total'] = Tools::ps_round($row['price'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity'];
$row['total_wt'] = Tools::ps_round($tax_calculator->addTaxes($row['price']), _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity'];
break;
}
$row['price_wt'] = $tax_calculator->addTaxes($row['price']);
$row['description_short'] = Tools::nl2br($row['description_short']);
if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0) {
$cache_id = 'Cart::getProducts_' . '-pai_id_image-' . (int) $row['id_product'] . '-' . (int) $this->id_lang . '-' . (int) $row['id_shop'];
if (!Cache::isStored($cache_id)) {
$row2 = Db::getInstance()->getRow('
SELECT image_shop.`id_image` id_image, il.`legend`
FROM `' . _DB_PREFIX_ . 'image` i
JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (i.id_image = image_shop.id_image AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $row['id_shop'] . ')
LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
WHERE i.`id_product` = ' . (int) $row['id_product'] . ' AND image_shop.`cover` = 1');
Cache::store($cache_id, $row2);
}
$row2 = Cache::retrieve($cache_id);
if (!$row2) {
$row2 = array('id_image' => false, 'legend' => false);
} else {
$row = array_merge($row, $row2);
}
} else {
$row['id_image'] = $row['pai_id_image'];
$row['legend'] = $row['pai_legend'];
}
$row['reduction_applies'] = ($specific_price_output && (float) $specific_price_output['reduction']);
$row['quantity_discount_applies'] = ($specific_price_output && $row['cart_quantity'] >= (int) $specific_price_output['from_quantity']);
$row['id_image'] = Product::defineProductImage($row, $this->id_lang);
$row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
$row['features'] = Product::getFeaturesStatic((int) $row['id_product']);
if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) {
$row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]);
}
$row = Product::getTaxesInformations($row, $cart_shop_context);
$this->_products[] = $row;
}
$categoryIdsTakenFromDb = Configuration::get('ACOMPTE_CATS');
$selectedcategories = @unserialize($categoryIdsTakenFromDb);
if ($selectedcategories === false && $selectedcategories !== 'b:0;') {
$selectedcategories = array();
}
$pre_commande = false;
if (is_array($this->_products) && !empty($this->_products)) { //&& count($this->_products)>0
foreach ($this->_products as $product) {
if (in_array((int) $product['id_category_default'], $selectedcategories)) {
$pre_commande = true;
break;
} else {
/**/
$sql = 'SELECT id_product FROM `' . _DB_PREFIX_ . 'category_product` WHERE `id_product` = ' . (int) $product['id_product'] . ' AND `id_category` IN (';
foreach ($selectedcategories as $category) {
$sql .= (int) $category . ',';
}
$sql = rtrim($sql, ',') . ')';
/**/
if (Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql)) {
$pre_commande = true;
break;
}
}
}
}
if (!$pre_commande) {
return parent::getProducts();
}
$order_total = $this->getOrderTotal(true);
$price_wt = $this->getOrderTotal(true);
$this->_products = array();
$row['cart_quantity'] = 1;
$row['price_wt'] = $price_wt;
$row['name'] = 'Acompte';
$row['attributes'] = '';
$row['id_product1'] = '';
$id_defaultgroup = Db::getInstance()->executeS('SELECT id_default_group FROM ' . _DB_PREFIX_ . 'customer WHERE id_customer = ' . (int) Context::getContext()->customer->id);
if(is_array($id_defaultgroup))
{
$id_defaultgroup = $id_defaultgroup[0]['id_default_group'];
}
$sql = 'SELECT price FROM `' . _DB_PREFIX_ . 'installmentpayment_group` WHERE id_group=' . (int) $id_defaultgroup;
$data = Db::getInstance()->getRow($sql);
if(!empty($data)){
$row['description_short'] = "Pourcentage " . $data['price'] . '%';
}
else
{
if ((int) Configuration::get('ACOMPTE_TYPE') == 1) {
if ($order_total > (float) Configuration::get('ACOMPTE_PERCENTAGE')) {
$row['description_short'] = "Acompte " . Configuration::get('ACOMPTE_PERCENTAGE');
}
} else {
$row['description_short'] = "Pourcentage " . Configuration::get('ACOMPTE_PERCENTAGE') . '%';
}
}
$this->_products[] = $row;
return $this->_products;
}
/**
* Return shipping total for the cart
*
* @param array $delivery_option Array of the delivery option for each address
* @param booleal $use_tax
* @param Country $default_country
* @return float Shipping total
*/
public function getTotalShippingCost($delivery_option = null, $use_tax = true, Country $default_country = null)
{
if (Dispatcher::getInstance()->getController() != "pagenotfound") {
return parent::getTotalShippingCost($delivery_option, $use_tax, $default_country);
}
return 0;
}
}

View File

@@ -0,0 +1,131 @@
<?php
/**
* installmentpayment.php, Allows you to set a percentage payment for orders
* @author Magavenue <contact@magavenue.com>
* @copyright Magavenue
* @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
* @category modules
*
* @note If you want to customize the module, contact us at contact@magavenue.com
*/
class Hook extends HookCore
{
public static function getHookModuleExecList($hook_name = null)
{
$context = Context::getContext();
$cache_id = 'hook_module_exec_list_' . (isset($context->shop->id) ? '_' . $context->shop->id : '') . ((isset($context->customer)) ? '_' . $context->customer->id : '');
if (!Cache::isStored($cache_id) || $hook_name == 'displayPayment' || $hook_name == 'displayBackOfficeHeader') {
$frontend = true;
$groups = array();
$use_groups = Group::isFeatureActive();
if (isset($context->employee)) {
$frontend = false;
} else {
if ($use_groups) {
if (isset($context->customer) && $context->customer->isLogged()) {
$groups = $context->customer->getGroups();
} elseif (isset($context->customer) && $context->customer->isLogged(true)) {
$groups = array((int) Configuration::get('PS_GUEST_GROUP'));
} else {
$groups = array((int) Configuration::get('PS_UNIDENTIFIED_GROUP'));
}
}
}
$sql = new DbQuery();
$sql->select('h.`name` as hook, m.`id_module`, h.`id_hook`, m.`name` as module');
$sql->from('module', 'm');
if ($hook_name != 'displayBackOfficeHeader') {
$sql->join(Shop::addSqlAssociation('module', 'm', true, 'module_shop.enable_device & ' . (int) Context::getContext()->getDevice()));
$sql->innerJoin('module_shop', 'ms', 'ms.`id_module` = m.`id_module`');
}
$sql->innerJoin('hook_module', 'hm', 'hm.`id_module` = m.`id_module`');
$sql->innerJoin('hook', 'h', 'hm.`id_hook` = h.`id_hook`');
if ($hook_name != 'displayPayment') {
$sql->where('h.name != "displayPayment"');
} elseif ($frontend) {
if (Validate::isLoadedObject($context->country)) {
$sql->where('(h.name = "displayPayment" AND (SELECT id_country FROM ' . _DB_PREFIX_ . 'module_country mc WHERE mc.id_module = m.id_module AND id_country = ' . (int) $context->country->id . ' AND id_shop = ' . (int) $context->shop->id . ' LIMIT 1) = ' . (int) $context->country->id . ')');
}
if (Validate::isLoadedObject($context->currency)) {
$sql->where('(h.name = "displayPayment" AND (SELECT id_currency FROM ' . _DB_PREFIX_ . 'module_currency mcr WHERE mcr.id_module = m.id_module AND id_currency IN (' . (int) $context->currency->id . ', -1, -2) LIMIT 1) IN (' . (int) $context->currency->id . ', -1, -2))');
}
}
if (Validate::isLoadedObject($context->shop)) {
$sql->where('hm.id_shop = ' . (int) $context->shop->id);
}
if ($frontend) {
if ($use_groups) {
$sql->leftJoin('module_group', 'mg', 'mg.`id_module` = m.`id_module`');
if (Validate::isLoadedObject($context->shop)) {
$sql->where('mg.id_shop = ' . ((int) $context->shop->id) . (count($groups) ? ' AND mg.`id_group` IN (' . implode(', ', $groups) . ')' : ''));
} elseif (count($groups)) {
$sql->where('mg.`id_group` IN (' . implode(', ', $groups) . ')');
}
}
}
$sql->groupBy('hm.id_hook, hm.id_module');
$sql->orderBy('hm.`position`');
$list = array();
if ($result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql)) {
foreach ($result as $row) {
$enable = true;
if (Db::getInstance()->getValue('SELECT `id_hook` FROM `' . _DB_PREFIX_ . 'hook` WHERE `id_hook` = ' . (int) $row['id_hook'] . ' AND `name` = \'displayPayment\'')) {
if (isset(Context::getContext()->cookie->installmentpayment_type) && (int) Context::getContext()->cookie->installmentpayment_type > 0) {
$paymentIdsTakenFromDb = Configuration::get('ACOMPTE_PAYMENT');
$selectedpayments = @unserialize($paymentIdsTakenFromDb);
if ($selectedpayments === false && $selectedpayments !== 'b:0;') {
$selectedpayments = array();
}
if (!empty($selectedpayments)) {
if (!in_array($row['id_module'], $selectedpayments)) {
$enable = false;
}
}
}
}
if ($enable) {
$row['hook'] = Tools::strtolower($row['hook']);
if (!isset($list[$row['hook']])) {
$list[$row['hook']] = array();
}
$list[$row['hook']][] = array(
'id_hook' => $row['id_hook'],
'module' => $row['module'],
'id_module' => $row['id_module'],
);
}
}
}
if ($hook_name != 'displayPayment' && $hook_name != 'displayBackOfficeHeader') {
Cache::store($cache_id, $list);
self::$_hook_modules_cache_exec = $list;
}
} else {
$list = Cache::retrieve($cache_id);
}
if ($hook_name) {
$retro_hook_name = Tools::strtolower(Hook::getRetroHookName($hook_name));
$hook_name = Tools::strtolower($hook_name);
$return = array();
$inserted_modules = array();
if (isset($list[$hook_name])) {
$return = $list[$hook_name];
}
foreach ($return as $module) {
$inserted_modules[] = $module['id_module'];
}
if (isset($list[$retro_hook_name])) {
foreach ($list[$retro_hook_name] as $retro_module_call) {
if (!in_array($retro_module_call['id_module'], $inserted_modules)) {
$return[] = $retro_module_call;
}
}
}
return (count($return) > 0 ? $return : false);
} else {
return $list;
}
}
}

View File

@@ -0,0 +1,665 @@
<?php
/**
* installmentpayment.php, Allows you to set a percentage payment for orders
* @author Magavenue <contact@magavenue.com>
* @copyright Magavenue
* @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
* @category modules
*
* @note If you want to customize the module, contact us at contact@magavenue.com
*/
abstract class PaymentModule extends PaymentModuleCore
{
/**
* Validate an order in database
* Function called from a payment module
*
* @param int $id_cart
* @param int $id_order_state
* @param float $amount_paid Amount really paid by customer (in the default currency)
* @param string $payment_method Payment method (eg. 'Credit card')
* @param null $message Message to attach to order
* @param array $extra_vars
* @param null $currency_special
* @param bool $dont_touch_amount
* @param bool $secure_key
* @param Shop $shop
*
* @return bool
* @throws PrestaShopException
*/
/*
* module: installmentpayment
* date: 2019-07-11 18:27:47
* version: 1.0.24
*/
public function validateOrder(
$id_cart,
$id_order_state,
$amount_paid,
$payment_method = 'Unknown',
$message = null,
$extra_vars = array(),
$currency_special = null,
$dont_touch_amount = false,
$secure_key = false,
Shop $shop = null
) {
if (isset(Context::getContext()->cookie->installmentpayment_type) && (int) Context::getContext()->cookie->installmentpayment_type > 0 && (int) Configuration::get('ACOMPTE_STATUSES') > 0) {
$id_order_state = (int) Configuration::get('ACOMPTE_STATUSES');
}
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int) $id_cart, true);
}
if (!isset($this->context)) {
$this->context = Context::getContext();
}
$this->context->cart = new Cart($id_cart);
$this->context->customer = new Customer($this->context->cart->id_customer);
$this->context->cart->setTaxCalculationMethod();
$this->context->language = new Language($this->context->cart->id_lang);
$this->context->shop = ($shop ? $shop : new Shop($this->context->cart->id_shop));
ShopUrl::resetMainDomainCache();
$id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency;
$this->context->currency = new Currency($id_currency, null, $this->context->shop->id);
if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
$context_country = $this->context->country;
}
$order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id);
if (!Validate::isLoadedObject($order_status)) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int) $id_cart, true);
throw new PrestaShopException('Can\'t load Order status');
}
if (!$this->active) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int) $id_cart, true);
die(Tools::displayError());
}
if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) {
if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int) $id_cart, true);
die(Tools::displayError());
}
$delivery_option_list = $this->context->cart->getDeliveryOptionList();
$package_list = $this->context->cart->getPackageList();
$cart_delivery_option = $this->context->cart->getDeliveryOption();
foreach ($delivery_option_list as $id_address => $package) {
if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) {
foreach ($package as $key => $val) {
$cart_delivery_option[$id_address] = $key;
break;
}
}
}
$order_list = array();
$order_detail_list = array();
do {
$reference = Order::generateReference();
} while (Order::getByReference($reference)->count());
$this->currentOrderReference = $reference;
$order_creation_failed = false;
$cart_total_paid = (float) Tools::ps_round((float) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2);
foreach ($cart_delivery_option as $id_address => $key_carriers) {
foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) {
foreach ($data['package_list'] as $id_package) {
$package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier);
$package_list[$id_address][$id_package]['id_carrier'] = $id_carrier;
}
}
}
CartRule::cleanCache();
$cart_rules = $this->context->cart->getCartRules();
foreach ($cart_rules as $cart_rule) {
if (($rule = new CartRule((int) $cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) {
if ($error = $rule->checkValidity($this->context, true, true)) {
$this->context->cart->removeCartRule((int) $rule->id);
if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) {
if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
Tools::redirect('index.php?controller=order-opc&submitAddDiscount=1&discount_name=' . urlencode($rule->code));
}
Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name=' . urlencode($rule->code));
} else {
$rule_name = isset($rule->name[(int) $this->context->cart->id_lang]) ? $rule->name[(int) $this->context->cart->id_lang] : $rule->code;
$error = Tools::displayError(sprintf('CartRule ID %1s (%2s) used in this cart is not valid and has been withdrawn from cart', (int) $rule->id, $rule_name));
PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int) $this->context->cart->id);
}
}
}
}
foreach ($package_list as $id_address => $packageByAddress) {
foreach ($packageByAddress as $id_package => $package) {
if (isset(Context::getContext()->cookie->installmentpayment_id_order) && !empty(Context::getContext()->cookie->installmentpayment_id_order)) {
$installmentpayment_id_order = Context::getContext()->cookie->installmentpayment_id_order;
$order = new Order($installmentpayment_id_order);
$payment_method = Module::getInstanceByName($this->name);
$sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'installmentpayment` WHERE id_cart=' . (int) $order->id_cart;
$installment = Db::getInstance()->getRow($sql);
if (isset($installment['rest']) && (float) $installment['rest'] > 0) {
$rest_paid = $installment['rest'];
$this->currentOrder = (int) $installmentpayment_id_order;
}
$payment = new OrderPayment();
$payment->order_reference = Tools::substr($order->reference, 0, 9);
$payment->id_currency = $order->id_currency;
$payment->amount = $rest_paid;
if ($order->total_paid != 0) {
$payment->payment_method = $payment_method->displayName;
} else {
$payment->payment_method = null;
}
$payment->conversion_rate = 1;
if (isset($extra_vars['transaction_id'])) {
$transaction_id = $extra_vars['transaction_id'];
} else {
$transaction_id = null;
}
$payment->transaction_id = $transaction_id;
$payment->save();
$id_order_invoice = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `id_order_invoice`
FROM `' . _DB_PREFIX_ . 'order_invoice`
WHERE number = ' . (int) $order->invoice_number);
PrestaShopLogger::addLog('PaymentModule::validateOrder - LOG DEV4 ligne 158 _' . $payment->amount . '_' . $transaction_id . '_' . $id_order_invoice, 3, null, 'Cart', (int) $order->id, true);
$res = Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'order_invoice_payment` (`id_order_invoice`, `id_order_payment`, `id_order`)
VALUES(' . (int) $id_order_invoice . ', ' . (int) $payment->id . ', ' . (int) $installmentpayment_id_order . ')');
$total = $order->total_paid;
$acompte = $total;
$id_cart = $order->id_cart;
$rest = 0;
$data_insert = array(
'id_cart' => (int) $id_cart,
'total' => $total,
'payer' => $acompte,
'rest' => $rest,
'state' => 0,
);
Db::getInstance()->update('installmentpayment', $data_insert, 'id_cart=' . (int) $id_cart);
return true;
} else {
$order = new Order();
}
$order->product_list = $package['product_list'];
if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
$address = new Address($id_address);
$this->context->country = new Country($address->id_country, $this->context->cart->id_lang);
if (!$this->context->country->active) {
throw new PrestaShopException('The delivery address country is not active.');
}
}
$carrier = null;
if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
$carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang);
$order->id_carrier = (int) $carrier->id;
$id_carrier = (int) $carrier->id;
} else {
$order->id_carrier = 0;
$id_carrier = 0;
}
$order->id_customer = (int) $this->context->cart->id_customer;
$order->id_address_invoice = (int) $this->context->cart->id_address_invoice;
$order->id_address_delivery = (int) $id_address;
$order->id_currency = $this->context->currency->id;
$order->id_lang = (int) $this->context->cart->id_lang;
$order->id_cart = (int) $this->context->cart->id;
$order->reference = $reference;
$order->id_shop = (int) $this->context->shop->id;
$order->id_shop_group = (int) $this->context->shop->id_shop_group;
$order->secure_key = ($secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key));
$order->payment = $payment_method;
if (isset($this->name)) {
$order->module = $this->name;
}
$order->recyclable = $this->context->cart->recyclable;
$order->gift = (int) $this->context->cart->gift;
$order->gift_message = $this->context->cart->gift_message;
$order->mobile_theme = $this->context->cart->mobile_theme;
$order->conversion_rate = $this->context->currency->conversion_rate;
$amount_paid = !$dont_touch_amount ? Tools::ps_round((float) $amount_paid, 2) : $amount_paid;
$order->total_paid_real = 0;
$order->total_products = (float) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
$order->total_products_wt = (float) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
$order->total_discounts_tax_excl = (float) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
$order->total_discounts_tax_incl = (float) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
$order->total_discounts = $order->total_discounts_tax_incl;
$order->total_shipping_tax_excl = (float) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list);
$order->total_shipping_tax_incl = (float) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list);
$order->total_shipping = $order->total_shipping_tax_incl;
if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
$order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
}
$order->total_wrapping_tax_excl = (float) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
$order->total_wrapping_tax_incl = (float) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
$order->total_wrapping = $order->total_wrapping_tax_incl;
$order->total_paid_tax_excl = (float) Tools::ps_round((float) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_paid_tax_incl = (float) Tools::ps_round((float) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
$total_in_order = $order->total_paid_tax_incl;
$order->total_paid = (float) Tools::ps_round((float) $this->context->cart->getOrderTotalGross(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_); //$order->total_paid_tax_incl;
$order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE');
$order->invoice_date = '0000-00-00 00:00:00';
$order->delivery_date = '0000-00-00 00:00:00';
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int) $id_cart, true);
}
$result = $order->add();
if (!$result) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int) $id_cart, true);
throw new PrestaShopException('Can\'t save Order');
}
if ($order_status->logable && (number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_))) {
PrestaShopLogger::addLog('lg 235 id_order:' . (int) $order->id . ' M=' . $cart_total_paid . ' H=' . $amount_paid . 'G=' . $total_in_order, 1, null, 'OKKKKKK', (int) $id_cart, true);
}
$order_list[] = $order;
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int) $id_cart, true);
}
$order_detail = new OrderDetail(null, null, $this->context);
$order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
$order_detail_list[] = $order_detail;
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int) $id_cart, true);
}
if (!is_null($carrier)) {
$order_carrier = new OrderCarrier();
$order_carrier->id_order = (int) $order->id;
$order_carrier->id_carrier = (int) $id_carrier;
$order_carrier->weight = (float) $order->getTotalWeight();
$order_carrier->shipping_cost_tax_excl = (float) $order->total_shipping_tax_excl;
$order_carrier->shipping_cost_tax_incl = (float) $order->total_shipping_tax_incl;
$order_carrier->add();
}
}
}
if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
$this->context->country = $context_country;
}
if (!$this->context->country->active) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int) $id_cart, true);
throw new PrestaShopException('The order address country is not active.');
}
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int) $id_cart, true);
}
if ($order_status->logable) {
if (isset($extra_vars['transaction_id'])) {
$transaction_id = $extra_vars['transaction_id'];
} else {
$transaction_id = null;
}
if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int) $id_cart, true);
throw new PrestaShopException('Can\'t save Order Payment');
} else {
PrestaShopLogger::addLog('PaymentModule::validateOrder - LOG DEV4 ligne 293_' . $amount_paid . '_' . $transaction_id, 3, null, 'Cart', (int) $order->id, true);
}
}
$cart_rule_used = array();
CartRule::cleanCache();
foreach ($order_detail_list as $key => $order_detail) {
$order = $order_list[$key];
if (!$order_creation_failed && isset($order->id)) {
if (!$secure_key) {
$message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation');
}
if (isset($message) & !empty($message)) {
$msg = new Message();
$message = strip_tags($message, '<br>');
if (Validate::isCleanHtml($message)) {
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int) $id_cart, true);
}
$msg->message = $message;
$msg->id_order = (int) $order->id;
$msg->private = 1;
$msg->add();
}
}
$virtual_product = true;
$product_var_tpl_list = array();
foreach ($order->product_list as $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')});
$product_price = Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt;
$product_var_tpl = array(
'reference' => $product['reference'],
'name' => $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : ''),
'unit_price' => Tools::displayPrice($product_price, $this->context->currency, false),
'price' => Tools::displayPrice($product_price * $product['quantity'], $this->context->currency, false),
'quantity' => $product['quantity'],
'customization' => array()
);
$customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart);
if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
$product_var_tpl['customization'] = array();
foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
$customization_text = '';
if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
$customization_text .= $text['name'] . ': ' . $text['value'] . '<br />';
}
}
if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
$customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />';
}
$customization_quantity = (int) $product['customization_quantity'];
$product_var_tpl['customization'][] = array(
'customization_text' => $customization_text,
'customization_quantity' => $customization_quantity,
'quantity' => Tools::displayPrice($customization_quantity * $product_price, $this->context->currency, false)
);
}
}
$product_var_tpl_list[] = $product_var_tpl;
if (!$product['is_virtual']) {
$virtual_product &= false;
}
} // end foreach ($product)
$product_list_txt = '';
$product_list_html = '';
if (count($product_var_tpl_list) > 0) {
$product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
$product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
}
$cart_rules_list = array();
$total_reduction_value_ti = 0;
$total_reduction_value_tex = 0;
foreach ($cart_rules as $cart_rule) {
$package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list);
$values = array(
'tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package),
'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package)
);
if (!$values['tax_excl']) {
continue;
}
if (count($order_list) == 1 && $values['tax_incl'] > ($order->total_products_wt - $total_reduction_value_ti) && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) {
$voucher = new CartRule($cart_rule['obj']->id); // We need to instantiate the CartRule without lang parameter to allow saving it
unset($voucher->id);
$voucher->code = empty($voucher->code) ? Tools::substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2';
if (preg_match('/\-([0-9]{1,2})\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) {
$voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . ((int) $matches[1] + 1), $voucher->code);
}
if ($voucher->reduction_tax) {
$voucher->reduction_amount = ($total_reduction_value_ti + $values['tax_incl']) - $order->total_products_wt;
if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) {
$voucher->reduction_amount -= $order->total_shipping_tax_incl;
}
} else {
$voucher->reduction_amount = ($total_reduction_value_tex + $values['tax_excl']) - $order->total_products;
if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) {
$voucher->reduction_amount -= $order->total_shipping_tax_excl;
}
}
if ($voucher->reduction_amount <= 0) {
continue;
}
$voucher->id_customer = $order->id_customer;
$voucher->quantity = 1;
$voucher->quantity_per_user = 1;
$voucher->free_shipping = 0;
if ($voucher->add()) {
CartRule::copyConditions($cart_rule['obj']->id, $voucher->id);
$params = array(
'{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false),
'{voucher_num}' => $voucher->code,
'{firstname}' => $this->context->customer->firstname,
'{lastname}' => $this->context->customer->lastname,
'{id_order}' => $order->reference,
'{order_name}' => $order->getUniqReference()
);
Mail::Send(
(int) $order->id_lang,
'voucher',
sprintf(Mail::l('New voucher for your order %s', (int) $order->id_lang), $order->reference),
$params,
$this->context->customer->email,
$this->context->customer->firstname . ' ' . $this->context->customer->lastname,
null,
null,
null,
null,
_PS_MAIL_DIR_,
false,
(int) $order->id_shop
);
}
$values['tax_incl'] = $order->total_products_wt - $total_reduction_value_ti;
$values['tax_excl'] = $order->total_products - $total_reduction_value_tex;
}
$total_reduction_value_ti += $values['tax_incl'];
$total_reduction_value_tex += $values['tax_excl'];
$order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping);
if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) {
$cart_rule_used[] = $cart_rule['obj']->id;
$cart_rule_to_update = new CartRule($cart_rule['obj']->id);
$cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1);
$cart_rule_to_update->update();
}
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['obj']->name,
'voucher_reduction' => ($values['tax_incl'] != 0.00 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false)
);
}
$cart_rules_list_txt = '';
$cart_rules_list_html = '';
if (count($cart_rules_list) > 0) {
$cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
$cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
}
$old_message = Message::getMessageByCartId((int) $this->context->cart->id);
if ($old_message) {
$update_message = new Message((int) $old_message['id_message']);
$update_message->id_order = (int) $order->id;
$update_message->update();
$customer_thread = new CustomerThread();
$customer_thread->id_contact = 0;
$customer_thread->id_customer = (int) $order->id_customer;
$customer_thread->id_shop = (int) $this->context->shop->id;
$customer_thread->id_order = (int) $order->id;
$customer_thread->id_lang = (int) $this->context->language->id;
$customer_thread->email = $this->context->customer->email;
$customer_thread->status = 'open';
$customer_thread->token = Tools::passwdGen(12);
$customer_thread->add();
$customer_message = new CustomerMessage();
$customer_message->id_customer_thread = $customer_thread->id;
$customer_message->id_employee = 0;
$customer_message->message = $update_message->message;
$customer_message->private = 0;
if (!$customer_message->add()) {
$this->errors[] = Tools::displayError('An error occurred while saving message');
}
}
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true);
}
Hook::exec('actionValidateOrder', array(
'cart' => $this->context->cart,
'order' => $order,
'customer' => $this->context->customer,
'currency' => $this->context->currency,
'orderStatus' => $order_status
));
foreach ($this->context->cart->getProducts() as $product) {
if ($order_status->logable) {
ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
}
}
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true);
}
$new_history = new OrderHistory();
$new_history->id_order = (int) $order->id;
$new_history->changeIdOrderState((int) $id_order_state, $order, true);
$new_history->addWithemail(true, $extra_vars);
if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) {
$history = new OrderHistory();
$history->id_order = (int) $order->id;
$history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true);
$history->addWithemail();
}
unset($order_detail);
$order = new Order($order->id);
if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) {
$invoice = new Address($order->id_address_invoice);
$delivery = new Address($order->id_address_delivery);
$delivery_state = $delivery->id_state ? new State($delivery->id_state) : false;
$invoice_state = $invoice->id_state ? new State($invoice->id_state) : false;
$data = array(
'{firstname}' => $this->context->customer->firstname,
'{lastname}' => $this->context->customer->lastname,
'{email}' => $this->context->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="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="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}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => ($virtual_product || !isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $product_list_html,
'{products_txt}' => $product_list_txt,
'{discounts}' => $cart_rules_list_html,
'{discounts_txt}' => $cart_rules_list_txt,
'{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
'{days}' => Configuration::get('ACOMPTE_DAYS'),
'{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)
);
$sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'installmentpayment` WHERE id_cart=' . (int) $order->id_cart;
$installment = Db::getInstance()->getRow($sql);
if (isset($installment['rest']) && (float) $installment['rest'] > 0) {
$smartynew = new Smarty;
$smartynew->assign('totalpay', Tools::displayPrice($order->total_paid_tax_incl, $this->context->currency, false));
$smartynew->assign('title', $this->l('Acompte'));
$contentExtra = $smartynew->fetch(_PS_MODULE_DIR_ . 'installmentpayment/views/templates/hook/invoice.extra.tpl');
$data['{total_paid}'] = Tools::displayPrice($order->total_paid, $this->context->currency, false) . $contentExtra ;
}
if (is_array($extra_vars)) {
$data = array_merge($data, $extra_vars);
}
if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) {
$pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty);
$file_attachement = array();
$file_attachement['content'] = $pdf->render(false);
$file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf';
$file_attachement['mime'] = 'application/pdf';
} else {
$file_attachement = null;
}
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true);
}
if (file_exists(_PS_MODULE_DIR_ . 'installmentpayment/mails/' . Language::getIsoById((int) $this->context->language->id) . '/order_conf.txt') and file_exists(_PS_MODULE_DIR_ .'installmentpayment/mails/' . Language::getIsoById((int) $this->context->language->id) . '/order_conf.html')) {
if (Validate::isEmail($this->context->customer->email)) {
Mail::Send(
(int) $order->id_lang,
'order_conf',
Mail::l('Order confirmation', (int) $order->id_lang),
$data,
$this->context->customer->email,
$this->context->customer->firstname . ' ' . $this->context->customer->lastname,
null,
null,
$file_attachement,
null,
_PS_MODULE_DIR_ . 'installmentpayment/mails/' . Language::getIsoById((int) $this->context->language->id) . '/order_conf.html',
false,
(int) $order->id_shop
);
}
}
else
{
if (Validate::isEmail($this->context->customer->email)) {
Mail::Send(
(int) $order->id_lang,
'order_conf',
Mail::l('Order confirmation', (int) $order->id_lang),
$data,
$this->context->customer->email,
$this->context->customer->firstname . ' ' . $this->context->customer->lastname,
null,
null,
$file_attachement,
null,
_PS_MAIL_DIR_,
false,
(int) $order->id_shop
);
}
}
}
if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
$product_list = $order->getProducts();
foreach ($product_list as $product) {
if (StockAvailable::dependsOnStock($product['product_id'])) {
StockAvailable::synchronize($product['product_id'], $order->id_shop);
}
}
}
} else {
$error = Tools::displayError('Order creation failed');
PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', (int) $order->id_cart);
die($error);
}
} // End foreach $order_detail_list
foreach ($order->getOrderDetailList() as $detail) {
$order_detail = new OrderDetail($detail['id_order_detail']);
$order_detail->updateTaxAmount($order);
}
if (isset($order) && $order->id) {
$this->currentOrder = (int) $order->id;
}
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true);
}
return true;
} else {
$error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart');
PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', (int) $this->context->cart->id);
die($error);
}
if ((int) $this->context->cookie->id_cart) {
$this->context->cookie->__unset('id_cart');
}
}
}

View File

@@ -0,0 +1,35 @@
<?php
/*
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2014 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;

View File

@@ -0,0 +1,424 @@
<?php
/**
* installmentpayment.php, Allows you to set a percentage payment for orders
* @author Magavenue <contact@magavenue.com>
* @copyright Magavenue
* @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
* @category modules
*
* @note If you want to customize the module, contact us at contact@magavenue.com
*/
class OrderHistory extends OrderHistoryCore
{
public function addWithemail($autodate = true, $template_vars = false, Context $context = null)
{
$order = new Order($this->id_order);
if (!$this->add($autodate)) {
return false;
}
if (!$this->sendEmail($order, $template_vars)) {
return false;
}
return true;
}
public function sendEmail($order, $template_vars = false)
{
$file_attachement = array();
$context = Context::getContext();
$order = new Order($this->id_order);
$new_order_state = new OrderState($this->id_order_state, Configuration::get('PS_LANG_DEFAULT'));
$result = Db::getInstance()->getRow(
'SELECT osl.`template`, c.`lastname`,c.`id_customer`, c.`firstname`, osl.`name` AS osname,
c.`email`, os.`module_name`, os.`id_order_state`, os.`pdf_invoice`, os.`pdf_delivery`
FROM `' . _DB_PREFIX_ . 'order_history` oh
LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON oh.`id_order` = o.`id_order`
LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON o.`id_customer` = c.`id_customer`
LEFT JOIN `' . _DB_PREFIX_ . 'order_state` os ON oh.`id_order_state` = os.`id_order_state`
LEFT JOIN `' . _DB_PREFIX_ . 'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state`
AND osl.`id_lang` = o.`id_lang`)
WHERE oh.`id_order_history` = ' . (int) $this->id . ' AND os.`send_email` = 1'
);
if (isset($result['template']) && Validate::isEmail($result['email'])) {
$topic = $result['osname'];
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int) $this->id_order,
'{order_name}' => $order->getUniqReference()
);
if ($template_vars) {
$data = array_merge($data, $template_vars);
}
if ($result['module_name']) {
$module = Module::getInstanceByName($result['module_name']);
if (Validate::isLoadedObject($module) &&
isset($module->extra_mail_vars) &&
is_array($module->extra_mail_vars)) {
$data = array_merge($data, $module->extra_mail_vars);
}
}
$sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'installmentpayment` WHERE id_cart=' . (int) $order->id_cart;
$installment = Db::getInstance()->getRow($sql);
if (isset($installment['rest']) && (float) $installment['rest'] > 0) {
$data['{total_paid}'] = Tools::displayPrice((float) $order->total_paid_tax_incl, new Currency((int) $order->id_currency), false);
} else {
$data['{total_paid}'] = Tools::displayPrice((float) $order->total_paid, new Currency((int) $order->id_currency), false);
}
$data['{order_name}'] = $order->getUniqReference();
$virtual_products = $order->getVirtualProducts();
if ($virtual_products && $new_order_state && $new_order_state->logable) {
$assign = array();
foreach ($virtual_products as $key => $virtual_product) {
$id_product_download = ProductDownload::getIdFromIdProduct($virtual_product['product_id']);
$product_download = new ProductDownload($id_product_download);
if ($product_download->display_filename != '') {
$assign[$key]['name'] = $product_download->display_filename;
$dl_link = $product_download->getTextLink(false, $virtual_product['download_hash'])
. '&id_order=' . $order->id
. '&secure_key=' . $order->secure_key;
$assign[$key]['link'] = $dl_link;
if ($virtual_product['download_deadline'] != '0000-00-00 00:00:00') {
$assign[$key]['deadline'] = Tools::displayDate($virtual_product['download_deadline'], $order->id_lang);
}
if ($product_download->nb_downloadable != 0) {
$assign[$key]['downloadable'] = $product_download->nb_downloadable;
}
}
}
$context->smarty->assign('virtualProducts', $assign);
$context->smarty->assign('id_order', $order->id);
$iso = Language::getIsoById((int) ($order->id_lang));
$links = $context->smarty->fetch(_PS_MAIL_DIR_ . $iso . '/download-product.tpl');
$tmp_array = array('{nbProducts}' => count($virtual_products), '{virtualProducts}' => $links);
$data = array_merge($data, $tmp_array);
if (!empty($assign)) {
Mail::Send(
(int) $order->id_lang,
'download_product',
Mail::l(
'Virtual product to download',
$order->id_lang
),
$data,
$result['email'],
$result['firstname'] . ' ' . $result['lastname'],
null,
null,
null,
null,
_PS_MAIL_DIR_,
false,
(int) $order->id_shop
);
}
}
if (Validate::isLoadedObject($order)) {
if ((int) $result['id_order_state'] === 2 &&
(int) Configuration::get('PS_INVOICE') &&
$order->invoice_number) {
$context = Context::getContext();
$pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $context->smarty);
$file_attachement['content'] = $pdf->render(false);
$file_attachement['name'] = Configuration::get(
'PS_INVOICE_PREFIX',
(int) $order->id_lang,
null,
$order->id_shop
)
. sprintf('%06d', $order->invoice_number) . '.pdf';
$file_attachement['mime'] = 'application/pdf';
} else {
$file_attachement = null;
}
$result['email'] = $result['email'];
Mail::Send(
(int) $order->id_lang,
$result['template'],
$topic,
$data,
$result['email'],
$result['firstname'] . ' ' . $result['lastname'],
null,
null,
$file_attachement,
null,
_PS_MAIL_DIR_,
false,
(int) $order->id_shop
);
}
if (Validate::isLoadedObject($order) && !Tools::getIsset('sendStateEmail')) {
$customerGroupe = Customer::getGroupsStatic($result['id_customer']);
if ((int) $this->id_order_state === (int) Configuration::get('IMPRIMEUR_ORDERSTATE') &&
in_array(7, $customerGroupe) &&
(int) $result['id_order_state'] != 2) {
$context = Context::getContext();
$pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $context->smarty);
$file_attachement['content'] = $pdf->render(false);
$file_attachement['name'] = Configuration::get(
'PS_INVOICE_PREFIX',
(int) $order->id_lang,
null,
$order->id_shop
)
. sprintf('%06d', $order->invoice_number) . '.pdf';
$file_attachement['mime'] = 'application/pdf';
Mail::Send(
(int) $order->id_lang,
$result['template'],
$topic,
$data,
Configuration::get('IMPRIMEUR_EMAIL'),
$result['firstname'] . ' ' . $result['lastname'],
null,
null,
$file_attachement,
null,
_PS_MAIL_DIR_,
false,
(int) $order->id_shop
);
}
}
}
return true;
}
/**
* Sets the new state of the given order
*
* @param int $new_order_state
* @param int/object $id_order
* @param bool $use_existing_payment
*/
public function changeIdOrderState($new_order_state, $id_order, $use_existing_payment = false)
{
if (!$new_order_state || !$id_order) {
return;
}
if (!is_object($id_order) && is_numeric($id_order)) {
$order = new Order((int) $id_order);
} elseif (is_object($id_order)) {
$order = $id_order;
} else {
return;
}
ShopUrl::cacheMainDomainForShop($order->id_shop);
$new_os = new OrderState((int) $new_order_state, $order->id_lang);
$old_os = $order->getCurrentOrderState();
if (in_array($new_os->id, array(Configuration::get('PS_OS_PAYMENT'), Configuration::get('PS_OS_WS_PAYMENT')))) {
Hook::exec('actionPaymentConfirmation', array('id_order' => (int) $order->id), null, false, true, false, $order->id_shop);
}
Hook::exec('actionOrderStatusUpdate', array('newOrderStatus' => $new_os, 'id_order' => (int) $order->id), null, false, true, false, $order->id_shop);
if (Validate::isLoadedObject($order) && ($new_os instanceof OrderState)) {
$context = Context::getContext();
$virtual_products = $order->getVirtualProducts();
if ($virtual_products && (!$old_os || !$old_os->logable) && $new_os && $new_os->logable) {
$assign = array();
foreach ($virtual_products as $key => $virtual_product) {
$id_product_download = ProductDownload::getIdFromIdProduct($virtual_product['product_id']);
$product_download = new ProductDownload($id_product_download);
if ($product_download->display_filename != '') {
$assign[$key]['name'] = $product_download->display_filename;
$dl_link = $product_download->getTextLink(false, $virtual_product['download_hash'])
. '&id_order=' . (int) $order->id
. '&secure_key=' . $order->secure_key;
$assign[$key]['link'] = $dl_link;
if (isset($virtual_product['download_deadline']) && $virtual_product['download_deadline'] != '0000-00-00 00:00:00') {
$assign[$key]['deadline'] = Tools::displayDate($virtual_product['download_deadline']);
}
if ($product_download->nb_downloadable != 0) {
$assign[$key]['downloadable'] = (int) $product_download->nb_downloadable;
}
}
}
$customer = new Customer((int) $order->id_customer);
$links = '<ul>';
foreach ($assign as $product) {
$links .= '<li>';
$links .= '<a href="' . $product['link'] . '">' . Tools::htmlentitiesUTF8($product['name']) . '</a>';
if (isset($product['deadline'])) {
$links .= '&nbsp;' . Tools::htmlentitiesUTF8(Tools::displayError('expires on', false)) . '&nbsp;' . $product['deadline'];
}
if (isset($product['downloadable'])) {
$links .= '&nbsp;' . Tools::htmlentitiesUTF8(sprintf(Tools::displayError('downloadable %d time(s)', false), (int) $product['downloadable']));
}
$links .= '</li>';
}
$links .= '</ul>';
$data = array(
'{lastname}' => $customer->lastname,
'{firstname}' => $customer->firstname,
'{id_order}' => (int) $order->id,
'{order_name}' => $order->getUniqReference(),
'{nbProducts}' => count($virtual_products),
'{virtualProducts}' => $links
);
if (!empty($assign)) {
Mail::Send((int) $order->id_lang, 'download_product', Mail::l('The virtual product that you bought is available for download', $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
}
}
$manager = null;
if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
$manager = StockManagerFactory::getManager();
}
$error_or_canceled_statuses = array(Configuration::get('PS_OS_ERROR'), Configuration::get('PS_OS_CANCELED'));
$employee = null;
if (!(int) $this->id_employee || !Validate::isLoadedObject(($employee = new Employee((int) $this->id_employee)))) {
if (!Validate::isLoadedObject($old_os) && $context != null) {
$employee = $context->employee; // filled if from BO and order created (because no old_os)
if ($employee) {
$this->id_employee = $employee->id;
}
} else {
$employee = null;
}
}
foreach ($order->getProductsDetail() as $product) {
if (Validate::isLoadedObject($old_os)) {
if ($new_os->logable && !$old_os->logable) {
ProductSale::addProductSale($product['product_id'], $product['product_quantity']);
if (!Pack::isPack($product['product_id']) &&
in_array($old_os->id, $error_or_canceled_statuses) &&
!StockAvailable::dependsOnStock($product['id_product'], (int) $order->id_shop)) {
StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], -(int) $product['product_quantity'], $order->id_shop);
}
} elseif (!$new_os->logable && $old_os->logable) {// if becoming unlogable => removes sale
ProductSale::removeProductSale($product['product_id'], $product['product_quantity']);
if (!Pack::isPack($product['product_id']) &&
in_array($new_os->id, $error_or_canceled_statuses) &&
!StockAvailable::dependsOnStock($product['id_product'])) {
StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], (int) $product['product_quantity'], $order->id_shop);
}
} elseif (!$new_os->logable && !$old_os->logable &&
in_array($new_os->id, $error_or_canceled_statuses) &&
!in_array($old_os->id, $error_or_canceled_statuses) &&
!StockAvailable::dependsOnStock($product['id_product'])) {// if waiting for payment => payment error/canceled
StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], (int) $product['product_quantity'], $order->id_shop);
}
}
if ($new_os->shipped == 1 && (!Validate::isLoadedObject($old_os) || $old_os->shipped == 0) &&
Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') &&
Warehouse::exists($product['id_warehouse']) &&
$manager != null &&
(int) $product['advanced_stock_management'] == 1) {
$warehouse = new Warehouse($product['id_warehouse']);
$manager->removeProduct(
$product['product_id'],
$product['product_attribute_id'],
$warehouse,
($product['product_quantity'] - $product['product_quantity_refunded'] - $product['product_quantity_return']),
Configuration::get('PS_STOCK_CUSTOMER_ORDER_REASON'),
true,
(int) $order->id,
0,
$employee
);
} elseif ($new_os->shipped == 0 && Validate::isLoadedObject($old_os) && $old_os->shipped == 1 &&
Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') &&
Warehouse::exists($product['id_warehouse']) &&
$manager != null &&
(int) $product['advanced_stock_management'] == 1) {// @since.1.5.0 : if the order was shipped, and is not anymore, we need to restock products
if (Pack::isPack($product['product_id'])) {
$pack_products = Pack::getItems($product['product_id'], Configuration::get('PS_LANG_DEFAULT', null, null, $order->id_shop));
foreach ($pack_products as $pack_product) {
if ($pack_product->advanced_stock_management == 1) {
$mvts = StockMvt::getNegativeStockMvts($order->id, $pack_product->id, 0, $pack_product->pack_quantity * $product['product_quantity']);
foreach ($mvts as $mvt) {
$manager->addProduct(
$pack_product->id,
0,
new Warehouse($mvt['id_warehouse']),
$mvt['physical_quantity'],
null,
$mvt['price_te'],
true,
null,
$employee
);
}
if (!StockAvailable::dependsOnStock($product['id_product'])) {
StockAvailable::updateQuantity($pack_product->id, 0, (int) $pack_product->pack_quantity * $product['product_quantity'], $order->id_shop);
}
}
}
} else {// else, it's not a pack, re-stock using the last negative stock mvts
$mvts = StockMvt::getNegativeStockMvts($order->id, $product['product_id'], $product['product_attribute_id'], ($product['product_quantity'] - $product['product_quantity_refunded'] - $product['product_quantity_return']));
foreach ($mvts as $mvt) {
$manager->addProduct(
$product['product_id'],
$product['product_attribute_id'],
new Warehouse($mvt['id_warehouse']),
$mvt['physical_quantity'],
null,
$mvt['price_te'],
true
);
}
}
}
}
}
$this->id_order_state = (int) $new_order_state;
if (!Validate::isLoadedObject($new_os) || !Validate::isLoadedObject($order)) {
die(Tools::displayError('Invalid new order status'));
}
$order->current_state = $this->id_order_state;
$order->valid = $new_os->logable;
$order->update();
if ($new_os->invoice && !$order->invoice_number) {
$order->setInvoice($use_existing_payment);
} elseif ($new_os->delivery && !$order->delivery_number) {
$order->setDeliverySlip();
}
if ($new_os->paid == 1 && (!isset(Context::getContext()->cookie->installmentpayment_type) || (int) Context::getContext()->cookie->installmentpayment_type <= 0)) {
$invoices = $order->getInvoicesCollection();
if ($order->total_paid != 0) {
$payment_method = Module::getInstanceByName($order->module);
}
foreach ($invoices as $invoice) {
$rest_paid = $invoice->getRestPaid();
if ($rest_paid > 0 && (!isset(Context::getContext()->cookie->installmentpayment_type) || (int) Context::getContext()->cookie->installmentpayment_type <= 0)) {
$sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'installmentpayment` WHERE id_cart=' . (int) $order->id_cart;
$installment = Db::getInstance()->getRow($sql);
if (isset($installment['rest']) && (float) $installment['rest'] > 0) {
$rest_paid = $installment['payer'];
}
$payment = new OrderPayment();
$payment->order_reference = Tools::substr($order->reference, 0, 9);
$payment->id_currency = $order->id_currency;
$payment->amount = $rest_paid;
if ($order->total_paid != 0) {
$payment->payment_method = $payment_method->displayName;
} else {
$payment->payment_method = null;
}
if ($payment->id_currency == $order->id_currency) {
$order->total_paid_real += $payment->amount;
} else {
$order->total_paid_real += Tools::ps_round(Tools::convertPrice($payment->amount, $payment->id_currency, false), 2);
}
$order->save();
$payment->conversion_rate = 1;
$payment->save();
PrestaShopLogger::addLog('ORDERHISTORY::changeIdOrderState - LOG DEV4 ligne 426 _' . $payment->amount . '_', 3, null, 'Cart', (int) $order->id, true);
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'order_invoice_payment` (`id_order_invoice`, `id_order_payment`, `id_order`)
VALUES(' . (int) $invoice->id . ', ' . (int) $payment->id . ', ' . (int) $order->id . ')');
}
}
}
if ($new_os->delivery) {
$order->setDelivery();
}
Hook::exec('actionOrderStatusPostUpdate', array('newOrderStatus' => $new_os, 'id_order' => (int) $order->id,), null, false, true, false, $order->id_shop);
ShopUrl::resetMainDomainCache();
}
}

View File

@@ -0,0 +1,36 @@
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @version Release: $Revision$
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;

View File

@@ -0,0 +1,72 @@
<?php
/**
* installmentpayment.php, Allows you to set a percentage payment for orders
* @author Magavenue <contact@magavenue.com>
* @copyright Magavenue
* @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
* @category modules
*
* @note If you want to customize the module, contact us at contact@magavenue.com
*/
class HTMLTemplateInvoice extends HTMLTemplateInvoiceCore
{
public function getHeader()
{
if (Tools::getIsset('installmentpayment')) {
$this->title = HTMLTemplateInvoice::l('Facture acompte n°') . $this->order->id;
}
return parent::getHeader();
}
public function getFilename()
{
if (Tools::getIsset('installmentpayment')) {
$id_lang = Context::getContext()->language->id;
$id_shop = (int) $this->order->id_shop;
return Configuration::get('PS_INVOICE_PREFIX', $id_lang, null, $id_shop) . sprintf('%06d', $this->order->id) . '.pdf';
}
return parent::getFilename();
}
public function getContent()
{
parent::getContent();
$iso_code = Context::getContext()->language->iso_code;
$sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'installmentpayment` WHERE id_cart=' . (int) $this->order->id_cart;
$installmentpayment = Db::getInstance()->getRow($sql);
if (isset($installmentpayment['rest']) && $installmentpayment['rest'] > 0) {
$data = array(
'paid' => $installmentpayment['payer'],
'rest' => $installmentpayment['rest'],
'acompte' => Tools::getIsset('installmentpayment') ? 1 : 0
);
$this->smarty->assign($data);
}
if (Tools::getIsset('installmentpayment')) {
$tpls = array(
'style_tab' => $this->smarty->fetch($this->getTemplate('invoice.style-tab')),
'addresses_tab' => $this->smarty->fetch($this->getTemplate('invoice.addresses-tab')),
'summary_tab' => $this->smarty->fetch(_PS_MODULE_DIR_ . 'installmentpayment/views/templates/hook/pdf/invoice.empty.tpl'),
'tax_tab' => $this->smarty->fetch(_PS_MODULE_DIR_ . 'installmentpayment/views/templates/hook/pdf/invoice.tax-tab2_' . $iso_code . '.tpl'),
'product_tab' => $this->smarty->fetch(_PS_MODULE_DIR_ . 'installmentpayment/views/templates/hook/pdf/invoice.empty2.tpl'),
'payment_tab' => $this->smarty->fetch(_PS_MODULE_DIR_ . 'installmentpayment/views/templates/hook/pdf/invoice.empty2.tpl'),
'total_tab' => $this->smarty->fetch(_PS_MODULE_DIR_ . 'installmentpayment/views/templates/hook/pdf/invoice.total-tab2_' . $iso_code . '.tpl')
);
} else {
$tpls = array(
'style_tab' => $this->smarty->fetch($this->getTemplate('invoice.style-tab')),
'addresses_tab' => $this->smarty->fetch($this->getTemplate('invoice.addresses-tab')),
'summary_tab' => $this->smarty->fetch($this->getTemplate('invoice.summary-tab')),
'product_tab' => $this->smarty->fetch($this->getTemplate('invoice.product-tab')),
'tax_tab' => $this->getTaxTabContent(),
'payment_tab' => $this->smarty->fetch($this->getTemplate('invoice.payment-tab')),
'total_tab' => $this->smarty->fetch(_PS_MODULE_DIR_ . 'installmentpayment/views/templates/hook/invoice.total-tab_' . $iso_code . '.tpl')
);
}
$this->smarty->assign($tpls);
$country = new Country((int) $this->order->id_address_invoice);
return $this->smarty->fetch($this->getTemplateByCountry($country->iso_code));
}
}

View File

@@ -0,0 +1,36 @@
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @version Release: $Revision$
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;