How to create refund and register payment XML-RPC odoo - odoo

How can i create a refund and register payment for that refund in odoo via xml-rpc. The code that i have so far it creates the invoice for refund but it doesn't register any payment for that invoice, so the costumer refund invoice stays in open state even though a voucher is created and posted.
$invoiceData = $OERP->searchread(array(array('id','=',$invoiceId )), 'account.invoice');
$invoiceDatas = array();
foreach($invoiceData as $data)
{
$invoiceDatas["amount_total"] = $data["amount_total"];
$invoiceDatas["partner_id"] = $data["partner_id"];
$invoiceDatas["account_id"] = $data["account_id"];
$invoiceDatas["invoice_line"] = $data["invoice_line"];
$invoiceDatas["reference"] = $data["reference"];
$invoiceDatas["period_id"] = $data["period_id"];
}
$invoiceLineData = $OERP->searchread(array(array('invoice_id','=', intval($invoiceId) )), 'account.invoice.line');
foreach($invoiceLineData as $data)
{
$invoiceLine["product_id"] = $data["product_id"];
$invoiceLine["price_unit"] = $data["price_unit"];
}
$createRefundParams = array(
'date_invoice' => date('Y/m/d'),
'partner_id' => $invoiceDatas["partner_id"][0],
'journal_id' => 3,// $journalId,
'account_id' => $invoiceDatas["account_id"][0],
'name'=>'front end refundi',
'type'=>'out_refund' // dallon invoicen nga refund
);
$createRefund = $OERP->create($createRefundParams, 'account.invoice');
$invoiceProduct = array(
'invoice_id'=>$createRefund,
'product_id'=>$invoiceLine["product_id"][0],
'name'=>'refund',
'price_unit'=>$invoiceLine["price_unit"],
);
$createRefundLines = $OERP->create($invoiceProduct,"account.invoice.line");
$validateRefund = $OERP->workflow('account.invoice', 'invoice_open', $createRefund);
$amount_total = -$invoiceDatas['amount_total'];
$newInvoice = $OERP -> searchread(array(array('id','=',$createRefund)),'account.invoice' );
$moveId = array();
foreach($newInvoice as $data)
{
$moveId["move_id"] = $data["move_id"];
}
$createVoucher = array(
'date' => date('Y/m/d'),
'partner_id' => $invoiceDatas['partner_id'][0],
'amount' =>$amount_total ,
'journal_id' => 7,// $journalId,
'account_id' => 25,
'period_id' => $invoiceDatas['period_id'][0],
'type' => 'receipt'
);
$voucherResult = $OERP->create($createVoucher, 'account.voucher');
$invoice_object_line = $OERP->searchread(array(array('move_id', '=', $moveId["move_id"][0])), 'account.move.line');
$voucherLineItems = array(
'journal_id' => 7,// $journalId,
'period_id' => $invoiceDatas['period_id'][0],
'date' => date('Y/m/d'),
'date_due' => date('Y/m/d'),
'name' => 'Payment for refund',
'payment_option' => 'without_writeoff',
'amount_original' => -$amount_total,
// 'amount'=>-$amount_total,
'amount_unreconciled' => -$amount_total,
'voucher_id' => $voucherResult,//$voucher_id,
'partner_id' => $invoiceDatas['partner_id'][0],
'account_id' => $invoiceDatas['account_id'][0],
'move_line_id' => $invoice_object_line[0]["id"],
'type' => 'cr'
);
$createVoucherLine = $OERP->create($voucherLineItems, 'account.voucher.line');
$performa_voucher_result = $OERP->workflow('account.voucher', 'proforma_voucher', intval($voucherResult));
$invoiceMovId = $OERP->searchread(array(array('id','=',$createRefund)),'account.invoice' );
$button_validate_result = $OERP->button_click('account.move', 'button_validate', $invoiceMovId[0]["move_id"][0]);

I figured it out the answer to create an invoice refund here is the code if it helps anyone
$invoiceId = $_REQUEST["invoiceID"];
$OERP = new OpenERP();
$OERPUserID = $OERP->login($_SESSION['OERP-username'], $_SESSION['OERP-password']);
$invoiceData = $OERP->searchread(array(array('id','=',$invoiceId )), 'account.invoice');
$invoiceDatas = array();
foreach($invoiceData as $data)
{
$invoiceDatas["amount_total"] = $data["amount_total"];
$invoiceDatas["partner_id"] = $data["partner_id"];
$invoiceDatas["account_id"] = $data["account_id"];
$invoiceDatas["invoice_line"] = $data["invoice_line"];
$invoiceDatas["reference"] = $data["reference"];
$invoiceDatas["period_id"] = $data["period_id"];
}
$invoiceLineData = $OERP->searchread(array(array('invoice_id','=', intval($invoiceId) )), 'account.invoice.line');
foreach($invoiceLineData as $data)
{
$invoiceLine["product_id"] = $data["product_id"];
$invoiceLine["price_unit"] = $data["price_unit"];
}
//create Refund
$createRefundParams = array(
'date_invoice' => date('Y/m/d'),
'partner_id' => $invoiceDatas["partner_id"][0],
'journal_id' => 3,// $journalId,
'account_id' => $invoiceDatas["account_id"][0],
// 'reference'=>$invoiceDatas["reference"],
'name'=>'front end refundi',
'type'=>'out_refund' // dallon invoicen nga refund
);
$createRefund = $OERP->create($createRefundParams, 'account.invoice');
$invoiceProduct = array(
'invoice_id'=>$createRefund,
'product_id'=>$invoiceLine["product_id"][0],
'name'=>'refund',//$invoiceLine["product_id"][1],
'account_id'=>19,
'price_unit'=>$invoiceLine["price_unit"]
);
$createRefundLines = $OERP->create($invoiceProduct,"account.invoice.line");
$validateRefund = $OERP->workflow('account.invoice', 'invoice_open', $createRefund);
//================ Payments ===========================
$amount_total = -$invoiceDatas['amount_total'];
$newInvoice = $OERP -> searchread(array(array('id','=',$createRefund)),'account.invoice' );
$moveId = array();
foreach($newInvoice as $data)
{
$moveId["move_id"] = $data["move_id"];
}
$createVoucher = array(
'date' => date('Y/m/d'),
'partner_id' => $invoiceDatas['partner_id'][0],
'amount' =>$amount_total ,
'journal_id' => 7,// $journalId,
'account_id' => 25,
'period_id' => $invoiceDatas['period_id'][0],
'type' => 'receipt'
);
// $createRefund
$voucherResult = $OERP->create($createVoucher, 'account.voucher');
$invoice_object_line = $OERP->searchread(array(array('move_id', '=', $moveId["move_id"][0])), 'account.move.line');
$voucherLineItems = array(
//notice that amount values are positive since there is an extra minus in variable intialization
'journal_id' => 7,// $journalId,
'period_id' => $invoiceDatas['period_id'][0],
'date' => date('Y/m/d'),
'date_due' => date('Y/m/d'),
'name' => 'Payment for refund',
'payment_option' => 'without_writeoff',
'amount_original' => -$amount_total,
'amount'=>-$amount_total,
'amount_unreconciled' => -$amount_total,
'voucher_id' => $voucherResult,//$voucher_id,
'partner_id' => $invoiceDatas['partner_id'][0],
'account_id' => $invoiceDatas['account_id'][0],
'move_line_id' => $invoice_object_line[0]["id"],
'type' => 'dr'
);
$createVoucherLine = $OERP->create($voucherLineItems, 'account.voucher.line');
$performa_voucher_result = $OERP->workflow('account.voucher', 'proforma_voucher', intval($voucherResult));
$invoiceMovId = $OERP->searchread(array(array('id','=',$createRefund)),'account.invoice' );
$button_validate_result = $OERP->button_click('account.move', 'button_validate', $invoiceMovId[0]["move_id"][0]);

Related

Prestashop 1.7.4.x - Missing variables values when using order_conf as new email template

I have missing variables when using a new email template.
I have not changed any core code for this email template.
Is anyone can help me on this ?
[ I'm using Prestashop 1.7.4.x ]
Finally i found one solution for this. Maybe someone will get help from my solution.
I've modified classes/order/OrderHistory.php and replace following code.
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{order_name}' => $order->getUniqReference()
);
Replaced above code with following one.
/*----------------------
-START OF INSERTED CODE-
----------------------*/
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$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);
}
/* GET THE DISCOUNTS */
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $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);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!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(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $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),
'{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)
);
/*---------------------
!-END OF INSERTED CODE-
---------------------*/
I have also added following function to current class file.
protected function getEmailTemplateContent($template_name, $mail_type, $var)
{
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
}
$theme_template_path = _PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
$default_mail_template_path = _PS_MAIL_DIR_.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
if (Tools::file_exists_cache($theme_template_path)) {
$default_mail_template_path = $theme_template_path;
}
if (Tools::file_exists_cache($default_mail_template_path)) {
Context::getContext()->smarty->assign('list', $var);
return Context::getContext()->smarty->fetch($default_mail_template_path);
}
return ' ';
}
Bit late in the game, but I found this thread trying to do the same thing: use the "order_conf" template in a state where order details are not available.
Based on #viral answer to his own question, I had a few problems, so here is what I did to get things working in Presta Shop V1.7.3.2
Create file [WEBROOT]/override/classes/order/OrderHistory.php
Doing this, rather than changing core code will allow you to update Presta Shop without loosing your changes.
In that file I added the following content:
<?php
/**
* Make complete Order details available to email templates
*/
use PrestaShop\PrestaShop\Core\Stock\StockManager;
use PrestaShop\PrestaShop\Adapter\StockManager as StockManagerAdapter;
class OrderHistory extends OrderHistoryCore {
public function sendEmail($order, $template_vars = false)
{
$result = Db::getInstance()->getRow('
SELECT osl.`template`, c.`lastname`, 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'])) {
ShopUrl::cacheMainDomainForShop($order->id_shop);
$topic = $result['osname'];
// JOHN
$this->context = Context::getContext();
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$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);
}
/* GET THE DISCOUNTS */
$cart_rules_list = array();
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $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);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
$invoice = new Address((int)$order->id_address_invoice);
$delivery = new Address((int)$order->id_address_delivery);
$delivery_state = $delivery->id_state ? new State((int)$delivery->id_state) : false;
$invoice_state = $invoice->id_state ? new State((int)$invoice->id_state) : false;
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!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(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $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),
'{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)
);
// END JOHN
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);
}
}
if ($template_vars) {
$data = array_merge($data, $template_vars);
}
$data['{total_paid}'] = Tools::displayPrice((float)$order->total_paid, new Currency((int)$order->id_currency), false);
if (Validate::isLoadedObject($order)) {
// Attach invoice and / or delivery-slip if they exists and status is set to attach them
if (($result['pdf_invoice'] || $result['pdf_delivery'])) {
$context = Context::getContext();
$invoice = $order->getInvoicesCollection();
$file_attachement = array();
if ($result['pdf_invoice'] && (int)Configuration::get('PS_INVOICE') && $order->invoice_number) {
Hook::exec('actionPDFInvoiceRender', array('order_invoice_list' => $invoice));
$pdf = new PDF($invoice, PDF::TEMPLATE_INVOICE, $context->smarty);
$file_attachement['invoice']['content'] = $pdf->render(false);
$file_attachement['invoice']['name'] = Configuration::get('PS_INVOICE_PREFIX', (int)$order->id_lang, null, $order->id_shop).sprintf('%06d', $order->invoice_number).'.pdf';
$file_attachement['invoice']['mime'] = 'application/pdf';
}
if ($result['pdf_delivery'] && $order->delivery_number) {
$pdf = new PDF($invoice, PDF::TEMPLATE_DELIVERY_SLIP, $context->smarty);
$file_attachement['delivery']['content'] = $pdf->render(false);
$file_attachement['delivery']['name'] = Configuration::get('PS_DELIVERY_PREFIX', Context::getContext()->language->id, null, $order->id_shop).sprintf('%06d', $order->delivery_number).'.pdf';
$file_attachement['delivery']['mime'] = 'application/pdf';
}
} else {
$file_attachement = null;
}
if (!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
)) {
return false;
}
}
ShopUrl::resetMainDomainCache();
}
return true;
}
/**
* Added by John
*/
protected function getEmailTemplateContent($template_name, $mail_type, $var) {
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
return '';
}
$pathToFindEmail = array(
_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.$this->context->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.'en'.DIRECTORY_SEPARATOR.$template_name,
_PS_MAIL_DIR_.$this->context->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
_PS_MAIL_DIR_.'en'.DIRECTORY_SEPARATOR.$template_name,
);
foreach ($pathToFindEmail as $path) {
if (Tools::file_exists_cache($path)) {
$this->context->smarty->assign('list', $var);
return $this->context->smarty->fetch($path);
}
}
return 'Template Not Found';
}
}
f you search for "John" in that code, you will find the modifications from the standard "sendEmail" function and the over-ridden version.
Hope it's of help to someone.
Can't seem to make it work in 1.7.5.2..
Placed in /override/classes/order .
Erase the cache after that, every time you made changes. In prod/class_index.php. I made it work under 1.7.3.3
I was able to bring the variables to the shipped.html email template. The only problem is that the variables: {products} and {discounts} are not being displayed. Do you guys have any suggestion?
I´m using warehouse as theme and prestashop version is 1.7.8.7
HTML Preview: https://ibb.co/X8x91K6
Email Result: https://ibb.co/xSx5Pwb
As you can see in email result the variables aren´t fullfilled.

Show a pdf on CakePhp after creating and seving it

it's my first post so sorry in case i will do some mistakes. I am getting mad from this morning because of this function:
public function viewpdf0($agent_id = null, $month = null, $year = null){
if(!empty($agent_id)){
$this->create_remittance($agent_id, $month, $year);
$this->layout = '/pdf/default';
$this->render('/Pdf/remittance_0');
sleep(1);
$this->redirect('/files/remittances/STAT_'.str_pad($month, 2, '0', STR_PAD_LEFT).'_'.str_pad($year, 0, '0', STR_PAD_LEFT).'_'.$agent['Registry']['hash'].'_TEMP.pdf');
}
}
The problem started when i decided to take off the calculations from the viewpdf0 function and putting it into the create_remittance function.
When i click on the button "Print Pdf" i get the following error:
Missind Controller for files. This mean that the Cakephp is processing the redirect thinking to find a controller called files!!!!
It's very strange, because if i put again the calculation functions directly inside the viewpdf0 function it works.
Below part of the create_remittance function:
public function create_remittance($agent_id = null, $month = null, $year = null) {
$agent = $this->Registry->findById($agent_id);
$this->set('agent', $agent);
$conditions = array();
array_push($conditions , array('Dossier.active' => '1'));
array_push($conditions , array('Edossier.active' => '1'));
array_push($conditions , array('OR' =>
array(
array(
'Dossier.item_parent_id' => '43'
),
array(
'Dossier.item_parent_id' => '44'
)
)
));
//20:POLIZZA EMESSA - 17:PERFEZIONATA - 14:ATTESA DOC. ORIGINALI - 18:CARICATA
array_push($conditions , array('Dossier.state_id' => array(20,17,14,18)));
array_push($conditions , array('EXTRACT(MONTH FROM "Edossier"."date_emissione") =' => $month));
array_push($conditions , array('EXTRACT(YEAR FROM "Edossier"."date_emissione") =' => $year));
array_push($conditions , array('Dossier.agent_id' => $agent_id));
$query = array(
'fields' => array( 'DISTINCT Dossier.id',
'Agent.surname'
),
'joins' => array(
array('table' => 'items',
'alias' => 'Item',
'type' => 'LEFT',
'conditions' => array('Dossier.item_id = Item.id'),
),
array('table' => 'edossiers',
'alias' => 'Edossier',
'type' => 'LEFT',
'conditions' => array('Edossier.dossier_id = Dossier.id'),
),
array('table' => 'registries',
'alias' => 'Registry',
'type' => 'LEFT',
'conditions' => array('Dossier.registry_id = Registry.id'),
),
array('table' => 'registries',
'alias' => 'Agency',
'type' => 'LEFT',
'conditions' => array('Dossier.insurance_agency_id = Agency.id'),
),
array('table' => 'registries',
'alias' => 'Company',
'type' => 'LEFT',
'conditions' => array('Dossier.insurance_company_id = Company.id'),
),
array('table' => 'states',
'alias' => 'State',
'type' => 'LEFT',
'conditions' => array('Dossier.state_id = State.id'),
),
array('table' => 'categories',
'alias' => 'Product',
'type' => 'LEFT',
'conditions' => array('Dossier.item_parent_id = Product.id'),
),
array('table' => 'registries',
'alias' => 'Agent',
'type' => 'LEFT',
'conditions' => array('Dossier.agent_id = Agent.id'),
),
array('table' => 'states',
'alias' => 'RenewedState',
'type' => 'LEFT',
'conditions' => array('Dossier.renewed_state_id = RenewedState.id'),
),
),
'conditions' => $conditions,
'recursive' => -1
);
$dossiers = $this->Dossier->find('all', $query);
$this->set('dossiers', $dossiers);
$debug_dossier = '';
$edossiers = array();
$edossiers3 = array();
$dossier_ids = array();
$total_gross = 0;
$total_taxes = 0;
$total_equity = 0;
$total_fees_gross = 0;
$total_bill_tax = 0;
foreach($dossiers as $dossier){
// Query su type=1 ossia rata di pagamento
$edossier_all = $this->Edossier->find('all', array(
'conditions' => array(
'Edossier.active' => '1',
'Edossier.dossier_id' => $dossier['Dossier']['id'],
'Edossier.type' => '1',
'Edossier.month' => $month,
'Edossier.year' => $year
),
'order' => array(
'Edossier.id ASC'
)
));
// Query su type=2 ossia storno di pagamento
$edossier3_all = $this->Edossier->find('all', array(
'conditions' => array(
'Edossier.active' => '1',
'Edossier.dossier_id' => $dossier['Dossier']['id'],
'Edossier.type' => '2',
'Edossier.month' => $month,
'Edossier.year' => $year
),
'order' => array(
'Edossier.id ASC'
)
));
foreach($edossier_all as $edossier){
if(!empty($edossier)){
$item = $this->Item->findById($edossier['Dossier']['item_id']);
$agent_name = $this->Registry->findById($edossier['Dossier']['agent_id']);
$state = $this->State->findById($edossier['Dossier']['state_id']);
$registry = $this->Registry->findById($edossier['Dossier']['registry_id']);
$cashflow = $this->Cashflow->findByHash($edossier['Edossier']['cashflow_hash']);
$edossier['Agent'] = $agent_name;
$edossier['Item'] = $item;
$edossier['State'] = $state;
$edossier['Registry'] = $registry;
$edossier['Cashflow'] = $cashflow;
array_push($edossiers, $edossier);
$total_gross = $total_gross + $edossier['Edossier']['gross'];
$total_taxes = $total_taxes + $edossier['Edossier']['taxes'];
$total_equity = $total_equity + $edossier['Edossier']['equity'];
$total_fees_gross = $total_fees_gross + $edossier['Edossier']['fees_gross'];
$total_bill_tax = $total_bill_tax + $edossier['Edossier']['bill_tax'];
}
}
foreach($edossier3_all as $edossier3){
if(!empty($edossier3)){
$total_gross = $total_gross - $edossier3['Edossier']['value'];
$total_taxes = $total_taxes - $edossier3['Edossier']['taxes'];
$total_equity = $total_equity - $edossier3['Edossier']['equity'];
$total_fees_gross = $total_fees_gross - $edossier3['Edossier']['fees_gross'];
$total_bill_tax = $total_bill_tax - $edossier3['Edossier']['bill_tax'];
array_push($edossiers3, $edossier3);
}
}
array_push($dossier_ids, $dossier['Dossier']['id']);
$debug_dossier .= $dossier['Dossier']['id'] .',';
}
//Trovo tutte le rate pagate per conteggiare il totale pagato, nelle successive righe
$edossiers2 = $this->Edossier->find('all', array(
'conditions' => array(
'Edossier.active' => '1',
'Edossier.dossier_id' => $dossier_ids,
'Edossier.payed' => '1',
'Edossier.month' => $month,
'Edossier.year' => $year
)
));
$edossier_ids = array();
foreach($edossiers as $edossier){
array_push($edossier_ids, $edossier['Edossier']['id']);
}
$total_payed = 0;
foreach($edossiers2 as $edossier2){
//$cashflow = $this->Cashflow->findByHash($edossier2['Edossier']['cashflow_hash']);
//$total_payed = $total_payed + $cashflow['Cashflow']['qty'];
$cashflows = $this->Cashflow->find('all', array(
'conditions' => array(
'Cashflow.edossier_id' => $edossier2['Edossier']['id'],
'Cashflow.active' => '1'
)
));
foreach ($cashflows as $cashflow) {
$total_payed = $total_payed + $cashflow['Cashflow']['qty'];
}
}
$this->set('total_gross', $total_gross);
$this->set('total_taxes', $total_taxes);
$this->set('total_equity', $total_equity);
$this->set('total_fees_gross', $total_fees_gross);
$this->set('total_bill_tax', $total_bill_tax);
$this->set('total_payed', $total_payed);
$this->set('edossiers3', $edossiers3);
$this->set('edossiers2', $edossiers2);
$this->set('edossiers', $edossiers);
$this->set('agent', $agent);
$this->set('dossier_ids', $dossier_ids);
$this->set('edossier_ids', $edossier_ids);
$this->set('month', $month);
$this->set('year', $year);
$this->set('debug_dossier', $debug_dossier);
}
I solved the issue just inserting an array return in the function create_remittance and in the function viewpdf0 i fixed in this way:
$remittance = $this->create_remittance($agent_id, $month, $year);
Thank you.

Prestashop add another field to the the address form

I have been trying to add another two non-mandatory fields to the address pages, (user page, admin page, etc)
I created two columns in the ps_address and named address3 and address4 and changed available files in version 1.6.0.11 according to this article
I was able to add the new adreess3 and address4 fields in the country address settings. But there is no text field to add address3 and address4 in the AddressesController and the customer add addresses list.
Following is my modified AddressesController file.
<?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
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class AdminAddressesControllerCore extends AdminController
{
/** #var array countries list */
protected $countries_array = array();
public function __construct()
{
$this->bootstrap = true;
$this->required_database = true;
$this->required_fields = array('company', 'address2', 'address3', 'address4', 'postcode', 'other', 'phone', 'phone_mobile', 'vat_number', 'dni');
$this->table = 'address';
$this->className = 'Address';
$this->lang = false;
$this->addressType = 'customer';
$this->explicitSelect = true;
$this->context = Context::getContext();
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?'),
'icon' => 'icon-trash'
)
);
$this->allow_export = true;
if (!Tools::getValue('realedit'))
$this->deleted = true;
$countries = Country::getCountries($this->context->language->id);
foreach ($countries as $country)
$this->countries_array[$country['id_country']] = $country['name'];
$this->fields_list = array(
'id_address' => array('title' => $this->l('ID'), 'align' => 'center', 'class' => 'fixed-width-xs'),
'firstname' => array('title' => $this->l('First Name'), 'filter_key' => 'a!firstname'),
'lastname' => array('title' => $this->l('Last Name'), 'filter_key' => 'a!lastname'),
'address1' => array('title' => $this->l('Address')),
'postcode' => array('title' => $this->l('Zip/Postal Code'), 'align' => 'right'),
'city' => array('title' => $this->l('City')),
'country' => array('title' => $this->l('Country'), 'type' => 'select', 'list' => $this->countries_array, 'filter_key' => 'cl!id_country'));
parent::__construct();
$this->_select = 'cl.`name` as country';
$this->_join = '
LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON (cl.`id_country` = a.`id_country` AND cl.`id_lang` = '.(int)$this->context->language->id.')
LEFT JOIN `'._DB_PREFIX_.'customer` c ON a.id_customer = c.id_customer
';
$this->_where = 'AND a.id_customer != 0 '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER, 'c');
}
public function initToolbar()
{
parent::initToolbar();
if (!$this->display)
$this->toolbar_btn['import'] = array(
'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type=addresses',
'desc' => $this->l('Import')
);
}
public function initPageHeaderToolbar()
{
if (empty($this->display))
$this->page_header_toolbar_btn['new_address'] = array(
'href' => self::$currentIndex.'&addaddress&token='.$this->token,
'desc' => $this->l('Add new address', null, null, false),
'icon' => 'process-icon-new'
);
parent::initPageHeaderToolbar();
}
public function renderForm()
{
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Addresses'),
'icon' => 'icon-envelope-alt'
),
'input' => array(
array(
'type' => 'text_customer',
'label' => $this->l('Customer'),
'name' => 'id_customer',
'required' => false,
),
array(
'type' => 'text',
'label' => $this->l('Identification Number'),
'name' => 'dni',
'required' => false,
'col' => '4',
'hint' => $this->l('DNI / NIF / NIE')
),
array(
'type' => 'text',
'label' => $this->l('Address alias'),
'name' => 'alias',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' <>;=#{}'
),
array(
'type' => 'textarea',
'label' => $this->l('Other'),
'name' => 'other',
'required' => false,
'cols' => 15,
'rows' => 3,
'hint' => $this->l('Forbidden characters:').' <>;=#{}'
),
),
'submit' => array(
'title' => $this->l('Save'),
)
);
$id_customer = (int)Tools::getValue('id_customer');
if (!$id_customer && Validate::isLoadedObject($this->object))
$id_customer = $this->object->id_customer;
if ($id_customer)
{
$customer = new Customer((int)$id_customer);
$token_customer = Tools::getAdminToken('AdminCustomers'.(int)(Tab::getIdFromClassName('AdminCustomers')).(int)$this->context->employee->id);
}
$this->tpl_form_vars = array(
'customer' => isset($customer) ? $customer : null,
'tokenCustomer' => isset ($token_customer) ? $token_customer : null
);
// Order address fields depending on country format
$addresses_fields = $this->processAddressFormat();
// we use delivery address
$addresses_fields = $addresses_fields['dlv_all_fields'];
// get required field
$required_fields = AddressFormat::getFieldsRequired();
// Merge with field required
$addresses_fields = array_unique(array_merge($addresses_fields, $required_fields));
$temp_fields = array();
foreach ($addresses_fields as $addr_field_item)
{
if ($addr_field_item == 'company')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Company'),
'name' => 'company',
'required' => in_array('company', $required_fields),
'col' => '4',
'hint' => $this->l('Invalid characters:').' <>;=#{}'
);
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('VAT number'),
'col' => '2',
'name' => 'vat_number',
'required' => in_array('vat_number', $required_fields)
);
}
elseif ($addr_field_item == 'lastname')
{
if (isset($customer) &&
!Tools::isSubmit('submit'.strtoupper($this->table)) &&
Validate::isLoadedObject($customer) &&
!Validate::isLoadedObject($this->object))
$default_value = $customer->lastname;
else
$default_value = '';
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Last Name'),
'name' => 'lastname',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' 0-9!&lt;&gt;,;?=+()##"�{}_$%:',
'default_value' => $default_value,
);
}
elseif ($addr_field_item == 'firstname')
{
if (isset($customer) &&
!Tools::isSubmit('submit'.strtoupper($this->table)) &&
Validate::isLoadedObject($customer) &&
!Validate::isLoadedObject($this->object))
$default_value = $customer->firstname;
else
$default_value = '';
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('First Name'),
'name' => 'firstname',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' 0-9!&lt;&gt;,;?=+()##"�{}_$%:',
'default_value' => $default_value,
);
}
elseif ($addr_field_item == 'address1')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address'),
'name' => 'address1',
'col' => '6',
'required' => true,
);
}
elseif ($addr_field_item == 'address2')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address').' (2)',
'name' => 'address2',
'col' => '6',
'required' => in_array('address2', $required_fields),
);
}
elseif ($addr_field_item == 'address3')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address').' (3)',
'name' => 'address3',
'col' => '6',
'required' => in_array('address3', $required_fields),
);
}
elseif ($addr_field_item == 'address4')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address').' (4)',
'name' => 'address4',
'col' => '6',
'required' => in_array('address4', $required_fields),
);
}
elseif ($addr_field_item == 'postcode')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Zip/Postal Code'),
'name' => 'postcode',
'col' => '2',
'required' => true,
);
}
elseif ($addr_field_item == 'city')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('City'),
'name' => 'city',
'col' => '4',
'required' => true,
);
}
elseif ($addr_field_item == 'country' || $addr_field_item == 'Country:name')
{
$temp_fields[] = array(
'type' => 'select',
'label' => $this->l('Country'),
'name' => 'id_country',
'required' => in_array('Country:name', $required_fields) || in_array('country', $required_fields),
'col' => '4',
'default_value' => (int)$this->context->country->id,
'options' => array(
'query' => Country::getCountries($this->context->language->id),
'id' => 'id_country',
'name' => 'name'
)
);
$temp_fields[] = array(
'type' => 'select',
'label' => $this->l('State'),
'name' => 'id_state',
'required' => false,
'col' => '4',
'options' => array(
'query' => array(),
'id' => 'id_state',
'name' => 'name'
)
);
}
elseif ($addr_field_item == 'phone')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Home phone'),
'name' => 'phone',
'required' => in_array('phone', $required_fields) || Configuration::get('PS_ONE_PHONE_AT_LEAST'),
'col' => '4',
'hint' => Configuration::get('PS_ONE_PHONE_AT_LEAST') ? sprintf($this->l('You must register at least one phone number.')) : ''
);
}
elseif ($addr_field_item == 'phone_mobile')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Mobile phone'),
'name' => 'phone_mobile',
'required' => in_array('phone_mobile', $required_fields) || Configuration::get('PS_ONE_PHONE_AT_LEAST'),
'col' => '4',
'hint' => Configuration::get('PS_ONE_PHONE_AT_LEAST') ? sprintf($this->l('You must register at least one phone number.')) : ''
);
}
}
// merge address format with the rest of the form
array_splice($this->fields_form['input'], 3, 0, $temp_fields);
return parent::renderForm();
}
public function processSave()
{
if (Tools::getValue('submitFormAjax'))
$this->redirect_after = false;
// Transform e-mail in id_customer for parent processing
if (Validate::isEmail(Tools::getValue('email')))
{
$customer = new Customer();
$customer->getByEmail(Tools::getValue('email'), null, false);
if (Validate::isLoadedObject($customer))
$_POST['id_customer'] = $customer->id;
else
$this->errors[] = Tools::displayError('This email address is not registered.');
}
elseif ($id_customer = Tools::getValue('id_customer'))
{
$customer = new Customer((int)$id_customer);
if (Validate::isLoadedObject($customer))
$_POST['id_customer'] = $customer->id;
else
$this->errors[] = Tools::displayError('This customer ID is not recognized.');
}
else
$this->errors[] = Tools::displayError('This email address is not valid. Please use an address like bob#example.com.');
if (Country::isNeedDniByCountryId(Tools::getValue('id_country')) && !Tools::getValue('dni'))
$this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
/* If the selected country does not contain states */
$id_state = (int)Tools::getValue('id_state');
$id_country = (int)Tools::getValue('id_country');
$country = new Country((int)$id_country);
if ($country && !(int)$country->contains_states && $id_state)
$this->errors[] = Tools::displayError('You have selected a state for a country that does not contain states.');
/* If the selected country contains states, then a state have to be selected */
if ((int)$country->contains_states && !$id_state)
$this->errors[] = Tools::displayError('An address located in a country containing states must have a state selected.');
$postcode = Tools::getValue('postcode');
/* Check zip code format */
if ($country->zip_code_format && !$country->checkZipCode($postcode))
$this->errors[] = Tools::displayError('Your Zip/postal code is incorrect.').'<br />'.Tools::displayError('It must be entered as follows:').' '.str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format)));
elseif(empty($postcode) && $country->need_zip_code)
$this->errors[] = Tools::displayError('A Zip/postal code is required.');
elseif ($postcode && !Validate::isPostCode($postcode))
$this->errors[] = Tools::displayError('The Zip/postal code is invalid.');
if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile'))
$this->errors[] = Tools::displayError('You must register at least one phone number.');
/* If this address come from order's edition and is the same as the other one (invoice or delivery one)
** we delete its id_address to force the creation of a new one */
if ((int)Tools::getValue('id_order'))
{
$this->_redirect = false;
if (isset($_POST['address_type']))
$_POST['id_address'] = '';
}
// Check the requires fields which are settings in the BO
$address = new Address();
$this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
if (empty($this->errors))
return parent::processSave();
else
// if we have errors, we stay on the form instead of going back to the list
$this->display = 'edit';
/* Reassignation of the order's new (invoice or delivery) address */
$address_type = ((int)Tools::getValue('address_type') == 2 ? 'invoice' : ((int)Tools::getValue('address_type') == 1 ? 'delivery' : ''));
if ($this->action == 'save' && ($id_order = (int)Tools::getValue('id_order')) && !count($this->errors) && !empty($address_type))
{
if (!Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'orders SET `id_address_'.$address_type.'` = '.Db::getInstance()->Insert_ID().' WHERE `id_order` = '.$id_order))
$this->errors[] = Tools::displayError('An error occurred while linking this address to its order.');
else
Tools::redirectAdmin(Tools::getValue('back').'&conf=4');
}
}
public function processAdd()
{
if (Tools::getValue('submitFormAjax'))
$this->redirect_after = false;
return parent::processAdd();
}
/**
* Get Address formats used by the country where the address id retrieved from POST/GET is.
*
* #return array address formats
*/
protected function processAddressFormat()
{
$tmp_addr = new Address((int)Tools::getValue('id_address'));
$selected_country = ($tmp_addr && $tmp_addr->id_country) ? $tmp_addr->id_country : (int)Configuration::get('PS_COUNTRY_DEFAULT');
$inv_adr_fields = AddressFormat::getOrderedAddressFields($selected_country, false, true);
$dlv_adr_fields = AddressFormat::getOrderedAddressFields($selected_country, false, true);
$inv_all_fields = array();
$dlv_all_fields = array();
$out = array();
foreach (array('inv','dlv') as $adr_type)
{
foreach (${$adr_type.'_adr_fields'} as $fields_line)
foreach (explode(' ', $fields_line) as $field_item)
${$adr_type.'_all_fields'}[] = trim($field_item);
$out[$adr_type.'_adr_fields'] = ${$adr_type.'_adr_fields'};
$out[$adr_type.'_all_fields'] = ${$adr_type.'_all_fields'};
}
return $out;
}
/**
* Method called when an ajax request is made
* #see AdminController::postProcess()
*/
public function ajaxProcess()
{
if (Tools::isSubmit('email'))
{
$email = pSQL(Tools::getValue('email'));
$customer = Customer::searchByName($email);
if (!empty($customer))
{
$customer = $customer['0'];
echo Tools::jsonEncode(array('infos' => pSQL($customer['firstname']).'_'.pSQL($customer['lastname']).'_'.pSQL($customer['company'])));
}
}
die;
}
/**
* Object Delete
*/
public function processDelete()
{
if (Validate::isLoadedObject($object = $this->loadObject()))
if (!$object->isUsed())
$this->deleted = false;
return parent::processDelete();
}
/**
* Delete multiple items
*
* #return boolean true if succcess
*/
protected function processBulkDelete()
{
if (is_array($this->boxes) && !empty($this->boxes))
{
$deleted = false;
foreach ($this->boxes as $id)
{
$to_delete = new Address((int)$id);
if ($to_delete->isUsed())
{
$deleted = true;
break;
}
}
$this->deleted = $deleted;
}
return parent::processBulkDelete();
}
}
I also tried clearing cache using the Advanced Parameters > Performance and also did a manual cache clearance as well.
What might the problem be as to not showing the new address fields in backend or the frontend?
Try also delete (no worries it will be rebuid) class_index.php file at cache folder of Your store

How To Integrate Easypay.pt API With Opengateway

I need to integrate Easypay.pt with opengateway so if any one know somehting about this i would like to know if some one can help for this i will appreciate thanks
function Settings () {
$settings = array();
$settings['name'] = 'Easypay';
$settings['class_name'] = 'easypay';
$settings['external'] = FALSE;
$settings['no_credit_card'] = FALSE;
$settings['description'] =
'Easypay is a portuguese company that offers a universal payment
platform and is certified by SIBS, Unicre, Visa and MasterCard. Our
primary mission is helping the market to shorten the payment
processing time and offer greater flexibility and convenience in
payment.';
$settings['is_preferred'] = 1;
$settings['setup_fee'] = '$0.00';
$settings['monthly_fee'] = '$30.00';
$settings['transaction_fee'] = '2.5% + $0.30';
$settings['purchase_link'] = 'https://www.easypay.pt/_s/api_easypay_01BG.php';
$settings['allows_updates'] = 0;
$settings['url_live'] = 'https://www.easypay.pt/_s/api_easypay_01BG.php ';
$settings['url_test'] = 'http://test.easypay.pt/_s/api_easypay_01BG.php';
$settings['allows_refunds'] = 1;
$settings['requires_customer_information'] = 1;
$settings['requires_customer_ip'] = 1;
$settings['required_fields'] = array(
'enabled',
'mode',
'ep_cin',
'ep_user',
'ep_ref_type',
'ep_entity',
't_key',
'ep_language',
'ep_country'
);
$settings['field_details'] = array(
'enabled' => array(
'text' => 'Enable this gateway?',
'type' => 'radio',
'options' => array(
'1' => 'Enabled',
'0' => 'Disabled'
)
),
'mode' => array(
'text' => 'Mode',
'type' => 'select',
'options' => array(
'live' => 'Live Mode',
'test' => 'Test Mode'
)
),
'ep_cin' => array(
'text' => 'Client Identification Number',
'type' => 'text'
),
'ep_user' => array(
'text' => 'Username',
'type' => 'text'
),
'ep_ref_type' => array(
'text' => 'Type of Identifier',
'type' => 'select',
'options' => array(
'auto' => 'Auto',
)
),
'ep_type' => array(
'text' => 'Type',
'type' => 'select',
'options' => array(
'boleto' => 'Boleto',
)
),
'ep_entity' => array(
'text' => 'Entity in use by Your Account.',
'type' => 'text',
),
't_key' => array(
'text' => 'Transaction key',
'type' => 'text',
),
'ep_language' => array(
'text' => 'Language',
'type' => 'select',
'options' => array(
'PT' => 'PT',
)
),
'ep_country' => array(
'text' => 'Currency',
'type' => 'select',
'options' => array(
'PT' => 'PT',
)
)
);
return $settings;
}
function TestConnection($client_id, $gateway) {
// Get the proper URL
switch($gateway['mode']) {
case 'live':
$post_url = $gateway['url_live'];
break;
case 'test':
$post_url = $gateway['url_test'];
break;
}
$post = array();
$post['ep_cin'] = $gateway['ep_cin'];
$post['ep_user'] = $gateway['ep_user'];
$post['ep_entity'] = $gateway['ep_entity'];
$post['ep_ref_type'] = $gateway['ep_ref_type'];
$post['ep_type'] = 'boleto';
$post['t_value'] = '504.4';
$post['ep_country'] = $gateway['ep_country'];
$post['ep_language'] = $gateway['ep_language'];
$post['s_code'] = 'sssssssssssyour code ddddddd';
$post['t_key'] = $gateway['t_key'];;
$response = $this->Process($post_url, $post);
$status=$response->ep_status;
//$CI =& get_instance();
if($status != 'err1') {
return TRUE;
} else {
return FALSE;
}
}
//--------------------------------------------------------------------
function Process($url, $post, $order_id = FALSE) {
$response = simplexml_load_file(
$url . "ep_cin=" . $post['ep_cin'] . "&ep_user=" . $post['ep_user']
. "&ep_entity=" . $post['ep_entity'] . "&ep_ref_type=" . $post['ep_ref_type']
. "&ep_type=" . $post['ep_type'] . "&ep_country=" . $post['ep_country']
. "&ep_language='" . $post['ep_language'] . "'&s_code=" . $post['s_code']
. "&t_key=" . $post['t_key'] . "&t_value=" . $post['t_value']
);
return $response;
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
private function response_to_array($string) {
$string = urldecode($string);
$pairs = explode('&', $string);
$values = array();
foreach($pairs as $pair) {
list($key, $value) = explode('=', $pair);
$values[$key] = $value;
}
return $values;
}

Rename nama in upload ZF2 + AWS S3

How can I rename the name of a file before to upload zf2 and Amazon S3?
This is my code:
$files = $request->getFiles();
$bucketname = 'mybucket';
$result = $aws->putObject(array(
'Bucket' => $bucketname,
'Key' => 'user/5/'.$files['image-file']['name'],
'Body' => EntityBody::factory(fopen($files['image-file']['tmp_name'], 'r')),
'ACL' => CannedAcl::PUBLIC_READ,
'ContentType' => 'image/jpeg'
));
I can not use the module https://github.com/aws/aws-sdk-php-zf2
This is a working example t upload the image in zf2,rename it and save to database
namespace Admin\Form;
use Zend\Form\Form;
class SubcategoryimageForm extends Form
{
public function __construct($name = null)
{
parent::__construct('Subcategoryimage');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/form-data');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'subcategory_link_id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'alt',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Alt Text',
),
));
$this->add(array(
'name' => 'fileupload',
'attributes' => array(
'type' => 'file',
),
'options' => array(
'label' => 'File Upload',
),
));
$this->add ( array (
'name' => 'detail',
'attributes' => array (
'type' => 'textarea'
),
'options' => array (
'label' => 'Detail'
)
) );
$this->add ( array (
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'active',
'tabindex' => 3,
'options' => array (
'label' => 'Active',
'use_hidden_element' => true,
'checked_value' => '1',
'unchecked_value' => '0'
)
) );
$this->add(array(
'type' => 'Zend\Form\Element\Radio',
'name' => 'location',
'options' => array(
'label' => 'Please choose one of the choices',
'value_options' => array(
'1' => 'flag',
'2' => 'landing',
'3' => 'home page',
),
),
'attributes' => array(
'value' => '1' //set checked to '1'
)
));
$this->add ( array (
'name' => 'submit',
'type' => 'Submit',
'tabindex' => 5,
'size' => 20,
'required' => false,
'attributes' => array (
'value' => 'Upload File',
'id' => 'submitbutton'
)
) );
}
}
In your controller
//inculde the imagine modules
use Zend\Validatior\File\Size;
use Imagine\Gd\Imagine;
use Imagine\Image\Box;
use Imagine\Image\Point;
public function imageAction()
{
$id = ( int ) $this->params ()->fromRoute ( 'id', 0 );
if (! $id) {
return $this->redirect ()->toRoute ( 'category' );
}
$form = new SubcategoryimageForm();
$form->get ( 'subcategory_link_id' )->setAttribute ( 'value', $id );
$request = $this->getRequest();
if ($request->isPost()) {
// Make certain to merge the files info!
$image = new Subcategoryimage();
$form->setInputFilter($image->getInputFilter());
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
$size = new \Zend\Validator\File\ImageSize(array(
'minWidth' => 30, 'minHeight' => 30,
'maxWidth' => 1024, 'maxHeight' => 920,
)); //minimum bytes filesize
$isImage = new \Zend\Validator\File\IsImage();
$mimeType = new \Zend\Validator\File\MimeType(array('image/gif', 'image/jpg','image/jpeg','image/png','enableHeaderCheck' => true));
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $post['fileupload']['name']);
$adapter->setValidators(array($isImage), $post['fileupload']['name']);
$adapter->setValidators(array($mimeType), $post['fileupload']['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
$messages = $form->getMessages();
return $this->redirect ()->toRoute ( 'category' );
// print_r($messages);die('file errors');
} else {
//$adapter->setDestination(dirname(__DIR__).'imageurltosaveimage/');
$adapter->setDestination('imagepathtosave');
if ($adapter->receive($post['fileupload']['name'])) {
$image->exchangeArray($form->getData());
switch(strtolower($_FILES['fileupload']['type']))
{
case 'image/jpeg':
$filename = imagecreatefromjpeg('imagepath/'.$post['fileupload']['name']);
break;
case 'image/png':
$filename = imagecreatefrompng('imagepath/'.$post['fileupload']['name']);
break;
case 'image/gif':
$filename = imagecreatefromgif('imagepath/'.$post['fileupload']['name']);
break;
default:
exit('Unsupported type: '.$_FILES['fileupload']['type']);
}
ob_start();
imagejpeg($filename);
// large image
$large = base64_encode(ob_get_contents()); // returns output
$mainimgWidth = imagesx($filename);
$mainimgHeight = imagesy($filename);
$thumbWidth = intval($mainimgWidth / 4);
$thumbHeight = intval($mainimgHeight / 4);
$new = imagecreatetruecolor($thumbWidth, $thumbHeight);
$backgroundColor = imagecolorallocate($new, 255, 255, 255);
imagefill($new, 0, 0, $backgroundColor);
imagecopyresampled($new, $filename, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainimgWidth, $mainimgHeight);
/** Catch the imagedata */
ob_start();
imagejpeg($new);
$data = ob_get_clean();
// Destroy resources
imagedestroy($filename);
imagedestroy($new);
// Set new content-type and status code
$thumb = base64_encode($data);
// imagine library was intsalled by the composer in the test server by amarjit
ob_end_clean();
$imagine = new Imagine();
//rename files
$filedata = array(
'id' => $post ['id'],
'subcategory_link_id' => $post ['subcategory_link_id'],
'alt' => $post ['alt'],
'detail' => $post ['detail'],
'active' => $post ['active'],
'location' => $post ['location'],
'thumb' => $thumb,
'large' => $large,
'created' => date('Y-m-d H:i:s'),
'createdby' => 1,
);
$id = $this->getImageTable ()->save ( $filedata );
$imagine->open('ipathofimage/'.$post['fileupload']['name'])
->save('pathtosaveimages/newnameofimage-'.$id.'.jpg');
/**
* delete the origional uploaded file;
*/
unlink('pathtoimage/'.$post['fileupload']['name']);
return $this->redirect ()->toRoute ( 'category' );
}
}
}else{
$messages = $form->getMessages();
}
}
return array (
'id' => $id,
'form' => $form,
'entities' => $this->getImageTable ()->getImageContents($id),
);
}
To get the image from database
use below code in your action
public function getlandingimageAction()
{
$id = ( int ) $this->params ()->fromRoute ( 'id', 0 );
if (! $id) {
return $this->redirect ()->toRoute ( 'category' );
}
try {
$thumb = $this->getImageTable ()->getImage ( $id );
} catch ( \Exception $ex ) {
return $this->redirect ()->toRoute ( 'category', array (
'action' => 'index'
) );
}
$image = base64_decode($thumb);
/** check if the image is db */
if($image!=null)
{
$db_img = imagecreatefromstring($image);
Header("Content-type: image/jpeg");
imagejpeg($db_img);
}
else
{
/** check if the image is upload dir */
$url= "path/imagename".$id.'.jpg';
if(file_exists($url))
{
$db_img = imagecreatefromjpeg($url);
Header("Content-type: image/jpeg");
imagejpeg($db_img);
exit;
}
/** handle if the image does not exit */
/**
* This needs to be changed from t
*/
$imgurl= "paaathofimage/";
Header("Content-type: image/gif");
$i=imagecreatefromgif($imgurl."/images/noimg.gif");
imagegif($i);
}
exit;
}