Magento Refund programmatically - php

Hy,
i'm trying to create a refund programmatically :
//get order magento
$orderMagento = Mage::getModel('sales/order')->loadByIncrementId($realOrderIncrementId );
if($orderMagento->getStatus() == Mage_Sales_Model_Order::STATE_CANCELED){
//création de l'avoir
$convertOrder = new Mage_Sales_Model_Convert_Order ();
$creditMemo = $convertOrder->toCreditmemo ( $orderMagento );
$items = $orderMagento->getAllItems ();
$totalQty = 0;
foreach ( $items as $item ) {
$_eachCreditMemoItem = $convertOrder->itemToCreditmemoItem ( $item );
$_eachCreditMemoItem->setQty ($item->getQtyInvoiced());
$_eachCreditMemoItem->register ();
$creditMemo->addItem ( $_eachCreditMemoItem );
$totalQty += $item->getQtyInvoiced ();
}
$creditMemo->refund();
$creditMemo->setTotalQty ( $totalQty );
$orderCreditMemoStatusCode = Mage_Sales_Model_Order::STATE_CLOSED;
$orderCreditMemoStatusComment = '[OK]Remboursement des article : ';
$saveTransaction = Mage::getModel('core/resource_transaction')->addObject ($creditMemo )->addObject ( $orderMagento )->save ();
$orderMagento->addStatusToHistory ( $orderCreditMemoStatusCode, $orderCreditMemoStatusComment, false );
$orderMagento->save ();
}
This code create a credit memo but all amount are null (BaseGrandTotal = 0.00€, etc...)
So where is the problem ?
Thanks you

First of all thank you, I started implementing creditmemo by programming using your code, and the problem I had was that the credit memom was created but without products. I'll share my code so you can use it.
/*
I think your problem is with the content of the variable data, I'll give you an example:
array(6) {
["items"] => array(2) {
[11] => array(1) {
["qty"] => string(6) "2"
}
[13] => array(1) {
["qty"] => string(1) "0"
}
}
["do_offline"] => string(1) "1"
["comment_text"] => string(0) ""
["shipping_amount"] => string(1) "0"
["adjustment_positive"] => string(1) "0"
["adjustment_negative"] => string(1) "0"
["qtys"] => array(2) {
[11] => int(2)
[13] => int(0)
}
}
*/
/**
*
* #param array $dif array that contains my product information with qty and product_id and item_id
* #param type $info array("order_increment_id" => $order->getIncrementId(), "invoice_id" => $invoiceId);
* #return type
*/
protected function creaDevolucio($dif, $info){
$qtys = array();
foreach ($dif as $item) {
if (isset($item['qty'])) {
$qtys[$item['order_item_id']] = array("qty"=> $item['qty']);
}
if (isset($item['back_to_stock'])) {
$backToStock[$item['order_item_id']] = true;
}
}
$data = array(
"items" => $qtys,
"do_offline" => "1",
"comment_text" => "",
"shipping_amount" => "0",
"adjustment_positive" => "0",
"adjustment_negative" => "0",
);
if (!empty($data['comment_text'])) {
Mage::getSingleton('adminhtml/session')->setCommentText($data['comment_text']);
}
try {
$creditmemo = $this->_initCreditmemo($data, $info);
if ($creditmemo) {
if (($creditmemo->getGrandTotal() <=0) && (!$creditmemo->getAllowZeroGrandTotal())) {
Mage::throwException(
$this->__('Credit memo\'s total must be positive.')
);
}
$comment = '';
if (!empty($data['comment_text'])) {
$creditmemo->addComment(
$data['comment_text'],
isset($data['comment_customer_notify']),
isset($data['is_visible_on_front'])
);
if (isset($data['comment_customer_notify'])) {
$comment = $data['comment_text'];
}
}
if (isset($data['do_refund'])) {
$creditmemo->setRefundRequested(true);
}
if (isset($data['do_offline'])) {
$creditmemo->setOfflineRequested((bool)(int)$data['do_offline']);
}
$creditmemo->register();
if (!empty($data['send_email'])) {
$creditmemo->setEmailSent(true);
}
$creditmemo->getOrder()->setCustomerNoteNotify(!empty($data['send_email']));
$this->_saveCreditmemo($creditmemo);
$creditmemo->sendEmail(!empty($data['send_email']), $comment);
echo '<br>The credit memo has been created.';
Mage::getSingleton('adminhtml/session')->getCommentText(true);
return;
} else {
//$this->_forward('noRoute');
//return;
}
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
} catch (Exception $e) {
Mage::logException($e);
$this->_getSession()->addError($this->__('Cannot save the credit memo.'));
}
}
/**
*
* #param type $data contains products info to refund
* #param type $info array("order_increment_id" => $order->getIncrementId(), "invoice_id" => $invoiceId);
* #param type $update
* #return boolean
*/
protected function _initCreditmemo($data, $info, $update = false)
{
$creditmemo = false;
$invoice=false;
$creditmemoId = null;//$this->getRequest()->getParam('creditmemo_id');
$orderId = $info['order_increment_id'];//$this->getRequest()->getParam('order_id');
$invoiceId = $data['invoice_id'];
echo "<br>abans if. OrderId: ".$orderId;
if ($creditmemoId) {
$creditmemo = Mage::getModel('sales/order_creditmemo')->load($creditmemoId);
} elseif ($orderId) {
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
if ($invoiceId) {
$invoice = Mage::getModel('sales/order_invoice')
->load($invoiceId)
->setOrder($order);
echo '<br>loaded_invoice_number: '.$invoice->getId();
}
if (!$order->canCreditmemo()) {
echo '<br>cannot create credit memo';
if(!$order->isPaymentReview())
{
echo '<br>cannot credit memo Payment is in review';
}
if(!$order->canUnhold())
{
echo '<br>cannot credit memo Order is on hold';
}
if(abs($order->getTotalPaid()-$order->getTotalRefunded())<.0001)
{
echo '<br>cannot credit memo Amount Paid is equal or less than amount refunded';
}
if($order->getActionFlag('edit') === false)
{
echo '<br>cannot credit memo Action Flag of Edit not set';
}
if ($order->hasForcedCanCreditmemo()) {
echo '<br>cannot credit memo Can Credit Memo has been forced set';
}
return false;
}
$savedData = array();
if (isset($data['items'])) {
$savedData = $data['items'];
} else {
$savedData = array();
}
$qtys = array();
$backToStock = array();
foreach ($savedData as $orderItemId =>$itemData) {
if (isset($itemData['qty'])) {
$qtys[$orderItemId] = $itemData['qty'];
}
if (isset($itemData['back_to_stock'])) {
$backToStock[$orderItemId] = true;
}
}
$data['qtys'] = $qtys;
$service = Mage::getModel('sales/service_order', $order);
if ($invoice) {
$creditmemo = $service->prepareInvoiceCreditmemo($invoice, $data);
} else {
$creditmemo = $service->prepareCreditmemo($data);
}
/**
* Process back to stock flags
*/
foreach ($creditmemo->getAllItems() as $creditmemoItem) {
$orderItem = $creditmemoItem->getOrderItem();
$parentId = $orderItem->getParentItemId();
if (isset($backToStock[$orderItem->getId()])) {
$creditmemoItem->setBackToStock(true);
} elseif ($orderItem->getParentItem() && isset($backToStock[$parentId]) && $backToStock[$parentId]) {
$creditmemoItem->setBackToStock(true);
} elseif (empty($savedData)) {
$creditmemoItem->setBackToStock(Mage::helper('cataloginventory')->isAutoReturnEnabled());
} else {
$creditmemoItem->setBackToStock(false);
}
}
}
return $creditmemo;
}
/**
* Save creditmemo and related order, invoice in one transaction
* #param Mage_Sales_Model_Order_Creditmemo $creditmemo
*/
protected function _saveCreditmemo($creditmemo)
{
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($creditmemo)
->addObject($creditmemo->getOrder());
if ($creditmemo->getInvoice()) {
$transactionSave->addObject($creditmemo->getInvoice());
}
$transactionSave->save();
return $this;
}

Related

Can I edit the Amelia wordpress booking system to create a new customer without booking?

need my customers to be able to log into the site with the same details as they book with, as i can make a customer in amelia that adds itself to the default wordpress user list but when i make a wordpress user with the amelia customer role it does not transfer over across to amelia.
not a clue if this helps but found this in the plugin php.
<?php
namespace AmeliaBooking\Domain\Factory\User;
use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException;
use AmeliaBooking\Domain\Entity\User\Customer;
use AmeliaBooking\Domain\Entity\User\Manager;
use AmeliaBooking\Domain\Entity\User\Admin;
use AmeliaBooking\Domain\Entity\User\Provider;
use AmeliaBooking\Domain\Factory\Bookable\Service\ServiceFactory;
use AmeliaBooking\Domain\Factory\Google\GoogleCalendarFactory;
use AmeliaBooking\Domain\Factory\Outlook\OutlookCalendarFactory;
use AmeliaBooking\Domain\Factory\Schedule\PeriodServiceFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodServiceFactory;
use AmeliaBooking\Domain\ValueObjects\DateTime\Birthday;
use AmeliaBooking\Domain\ValueObjects\Gender;
use AmeliaBooking\Domain\ValueObjects\Json;
use AmeliaBooking\Domain\ValueObjects\String\Password;
use AmeliaBooking\Domain\ValueObjects\String\Status;
use AmeliaBooking\Domain\ValueObjects\Picture;
use AmeliaBooking\Domain\ValueObjects\String\Description;
use AmeliaBooking\Domain\ValueObjects\String\Email;
use AmeliaBooking\Domain\ValueObjects\Number\Integer\Id;
use AmeliaBooking\Domain\ValueObjects\String\Name;
use AmeliaBooking\Domain\ValueObjects\String\Phone;
use AmeliaBooking\Domain\Collection\Collection;
use AmeliaBooking\Domain\Factory\Schedule\DayOffFactory;
use AmeliaBooking\Domain\Factory\Schedule\TimeOutFactory;
use AmeliaBooking\Domain\Factory\Schedule\PeriodFactory;
use AmeliaBooking\Domain\Factory\Schedule\WeekDayFactory;
/**
* Class UserFactory
*
* #package AmeliaBooking\Domain\Factory\User
*/
class UserFactory
{
/**
* #param $data
*
* #return Admin|Customer|Manager|Provider
* #throws InvalidArgumentException
*/
public static function create($data)
{
if (!isset($data['type'])) {
$data['type'] = 'customer';
}
switch ($data['type']) {
case 'admin':
$user = new Admin(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'])
);
break;
case 'provider':
$weekDayList = [];
$dayOffList = [];
$specialDayList = [];
$serviceList = [];
$appointmentList = [];
if (isset($data['weekDayList'])) {
foreach ((array)$data['weekDayList'] as $weekDay) {
$timeOutList = [];
if (isset($weekDay['timeOutList'])) {
foreach ((array)$weekDay['timeOutList'] as $timeOut) {
$timeOutList[] = TimeOutFactory::create($timeOut);
}
$weekDay['timeOutList'] = $timeOutList;
}
$periodList = [];
if (isset($weekDay['periodList'])) {
foreach ((array)$weekDay['periodList'] as $period) {
$periodServiceList = [];
if (isset($period['periodServiceList'])) {
foreach ((array)$period['periodServiceList'] as $periodService) {
$periodServiceList[] = PeriodServiceFactory::create($periodService);
}
}
$period['periodServiceList'] = $periodServiceList;
$periodList[] = PeriodFactory::create($period);
}
$weekDay['periodList'] = $periodList;
}
$weekDayList[] = WeekDayFactory::create($weekDay);
}
}
if (isset($data['specialDayList'])) {
foreach ((array)$data['specialDayList'] as $specialDay) {
$periodList = [];
if (isset($specialDay['periodList'])) {
foreach ((array)$specialDay['periodList'] as $period) {
$periodServiceList = [];
if (isset($period['periodServiceList'])) {
foreach ((array)$period['periodServiceList'] as $periodService) {
$periodServiceList[] = SpecialDayPeriodServiceFactory::create($periodService);
}
}
$period['periodServiceList'] = $periodServiceList;
$periodList[] = SpecialDayPeriodFactory::create($period);
}
$specialDay['periodList'] = $periodList;
}
$specialDayList[] = SpecialDayFactory::create($specialDay);
}
}
if (isset($data['dayOffList'])) {
foreach ((array)$data['dayOffList'] as $dayOff) {
$dayOffList[] = DayOffFactory::create($dayOff);
}
}
if (isset($data['serviceList'])) {
foreach ((array)$data['serviceList'] as $service) {
$serviceList[$service['id']] = ServiceFactory::create($service);
}
}
$user = new Provider(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email']),
new Phone(isset($data['phone']) ? $data['phone'] : null),
new Collection($weekDayList),
new Collection($serviceList),
new Collection($dayOffList),
new Collection($specialDayList),
new Collection($appointmentList)
);
if (!empty($data['password'])) {
$user->setPassword(new Password($data['password']));
}
if (!empty($data['locationId'])) {
$user->setLocationId(new Id($data['locationId']));
}
if (!empty($data['googleCalendar']) && isset($data['googleCalendar']['token'])) {
$user->setGoogleCalendar(GoogleCalendarFactory::create($data['googleCalendar']));
}
if (!empty($data['outlookCalendar']) && isset($data['outlookCalendar']['token'])) {
$user->setOutlookCalendar(OutlookCalendarFactory::create($data['outlookCalendar']));
}
if (!empty($data['zoomUserId'])) {
$user->setZoomUserId(new Name($data['zoomUserId']));
}
if (!empty($data['id'])) {
$user->setId(new Id($data['id']));
}
break;
case 'manager':
$user = new Manager(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'])
);
break;
case 'customer':
default:
$user = new Customer(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'] ?: null),
new Phone(!empty($data['phone']) ? $data['phone'] : null),
new Gender(!empty($data['gender']) ? strtolower($data['gender']) : null)
);
break;
}
if (!empty($data['countryPhoneIso'])) {
$user->setCountryPhoneIso(new Name($data['countryPhoneIso']));
}
if (!empty($data['birthday'])) {
if (is_string($data['birthday'])) {
$user->setBirthday(new Birthday(\DateTime::createFromFormat('Y-m-d', $data['birthday'])));
} else {
$user->setBirthday(new Birthday($data['birthday']));
}
}
if (!empty($data['id'])) {
$user->setId(new Id($data['id']));
}
if (!empty($data['externalId'])) {
$user->setExternalId(new Id($data['externalId']));
}
if (!empty($data['pictureFullPath']) && !empty($data['pictureThumbPath'])) {
$user->setPicture(new Picture($data['pictureFullPath'], $data['pictureThumbPath']));
}
if (!empty($data['status'])) {
$user->setStatus(new Status($data['status']));
}
if (!empty($data['note'])) {
$user->setNote(new Description($data['note']));
}
return $user;
}
}
Try this. Found it on the support forums.
add_action( 'user_register', 'custom_amelia_registration_save', 10, 1 );
function custom_amelia_registration_save($user_id) {
global $wpdb;
$wpUser = get_user_by('ID', $user_id);
$ameliaUserId = $wpdb->get_col(
"SELECT id FROM wp_amelia_users WHERE email = '{$wpUser->user_email}'"
);
if (!$ameliaUserId && in_array('wpamelia-customer', $wpUser->roles)) {
$ameliaUserFirstName = $wpUser->user_first_name ?: $wpUser->user_nicename;
$ameliaUserLastName = $wpUser->user_last_name ?: $wpUser->user_nicename;
$wpdb->query("
INSERT INTO wp_amelia_users
(
type,
status,
externalId,
firstName,
lastName,
email
) VALUES (
'customer',
'visible',
{$user_id},
'{$ameliaUserFirstName}',
'{$ameliaUserLastName}',
'{$wpUser->user_email}'
)
");
}
}

Send a data from table to another table from a specific source field

Please help me about this one.
i have a table name 'aptimportdata' and 'aptimportdataaddress'.
the code below is a function for import a microsoft excel data to the website.
i want to send a data from table aptimportdata to aptimportdataaddress, but i don't know how, because in the excel file, there are 2 home address columns for one person, one with the columns name homeaddress1 to 4, and the other one is altaddress1 to 4, the "altaddress" is created for a person who have a home address more than 1.
now when i import the data from the website, the data is sent to the aptimportdata table and it doesn't have a problem when i upload the file from the website, but when i change the "altaddress" data destination table to aptimportdataaddress table, the website just give me an endless loading without a success report.
i already make a column for the "altaddress" in aptimportdataaddress table, but i cant find a solution how to make the "altaddress" data go to aptimportaddress table and its just the "altaddress" column data that i want to put at the aptimportdataaddress table.
if you need a screenshot for the what the table looks like, i'll send it.
this is my code :
= 5.3.3
* #copyright 2014 Sereware
* #developer Yudha Tama Aditiyara
* #application controller/apartement
*/
class import extends Controller
{
protected $_models = array('apartement/import/m_import');
public function dataexcel(){
$config['ajax_upload_dataexcel'] = site_url('apartement/import/ajax_upload_dataexcel');
$config['ajax_process_dataexcel'] = site_url('apartement/import/ajax_process_dataexcel/'.$this->d_page->page('noid'));
$this->load->view('apartement/import/dataexcel',$config);
}
public function ajax_upload_dataexcel(){
$id = str_replace('.','',microtime(true));
$upload = new Sereware\ExcelUpload(array('upload_dir' => SYSPATH.'files/'),false);
$upload->hasNormalFilename = true;
$this->d_page->obstart();
$upload->post();
ob_flush();
}
protected $apttower = array(
'h' => 1,'s'=>2,'y'=>3,'p'=>4
);
#{{{
protected function get_dataexcel(){
if (!isset($_REQUEST['file']) || !trim($_REQUEST['file']))return;
$file = $_REQUEST['file'];
$file = SYSPATH."files/" . $file . (pathinfo($file,PATHINFO_EXTENSION) !== 'xls' ? '.xls' : '');
if (!file_exists($file)) return;
$excel = new Sereware\Excel($file);
$data = $excel->getCells(0);
return $data;
}
protected function matcher_excelfield($dataexcelfields, $appimportdetails){
$fieldnames = array();
foreach($dataexcelfields as $indexField => $dataexcelfield) {
$dataexcelfield = strtolower(preg_replace('#[\n\r]#','',trim($dataexcelfield)));
if (isset($appimportdetails[$dataexcelfield])) {
$destfield = preg_replace('#[\n\r]#','',$appimportdetails[$dataexcelfield]->destfield);
$desttypefield = (int)$appimportdetails[$dataexcelfield]->desttypefield;
$isnormalized = $appimportdetails[$dataexcelfield]->isnormalized;
$defaultvalue = $appimportdetails[$dataexcelfield]->defaultvalue;
$appimportdetail = $appimportdetails[$dataexcelfield];
$appimportdetail_desttables = array_filter(explode(';',$appimportdetail->desttable));
foreach($appimportdetail_desttables as $tablename) {
$fieldnames[$tablename][$indexField] = array(
'destfield' => $destfield,
'desttypefield' => $desttypefield,
'isnormalized' => $isnormalized,
'defaultvalue' => $defaultvalue
);
}
}
}
return $fieldnames;
}
protected function normalize_dataexcel($destfield,$value){
$value = trim($value);
switch($destfield) {
case 25:
$value = str_replace('%','',$value);
break;
case 11:
if ($value){
$value = strtotime(str_replace('/', '-',(string)$value));
$value = date('Y-m-d',$value);
} else {
$value = null;
}
break;
case 34:
if (!$value) {
$value = -1;
} else {
$value = strtolower($value) === 'ok' ? 1 : 0;
}
break;
}
return $value;
}
public function ajax_process_dataexcel($idpage){
$appimport = $this->m_import->get_appimport();
$appimportdetails = $this->m_import->get_appimportdetails($appimport->idconnection,$appimport->noid);
$aptimportdatas = $this->m_import->get_aptimportdatas($appimport->idconnection);
$newid_aptimportdata = $this->m_import->get_maxid_aptimportdata();
$aptsyarats = $this->m_import->data_aptsyarats();
$aptdatabap = $this->m_import->data_aptbap();
$dataexcel = $this->get_dataexcel();
$dataexcelfields = $this->matcher_excelfield(array_shift($dataexcel),$appimportdetails);
$insert_data = array();
$update_data = array();
$insert_data_aptunitroom = array();
$insert_data_aptimportdataaddress = array();
$insert_data_aptunitroomsyarat = array();
$insert_data_aptdatabap = array();
$datamcarduser = $this->d_page->d_login->get_datamcarduser();
// var_dump(json_encode($dataexcelfields));
// exit();
foreach($dataexcel as $data) {
foreach($dataexcelfields as $tablename => $fieldnames) {
##-1
##-build data per-row
$ndata = array();
$ready = true;
$ndata['idcreate'] = $datamcarduser->noid;
$ndata['idupdate'] = $datamcarduser->noid;
$ndata['docreate'] = date('Y-m-d H:i:s');
$ndata['lastupdate'] = date('Y-m-d H:i:s');
foreach($fieldnames as $indexFieldExcel => $datafields) {
$fieldname = $datafields['destfield'];
$isnormalized = intval($datafields['isnormalized']);
$defaultvalue = $datafields['defaultvalue'];
$desttypefield = $datafields['desttypefield'];
if (!$isnormalized) {
$defaultvalue = $data[$indexFieldExcel];
}
$ndata[$fieldname] = $this->normalize_dataexcel($desttypefield,$defaultvalue);
}
##-2
if (isset($ndata['lotno']) && isset($aptimportdatas[$ndata['lotno']])) {
$metadata = $aptimportdatas[$ndata['lotno']];
if ($tablename === 'aptimportdata') {
$update_data[$tablename][$metadata['metadata']->noid] = $ndata;
// if (!empty($ndata['ppjbdate'])) {
// }
$update_data['aptunitroom'][$metadata['metadata']->noid] = array(
'statuslegal' => empty($ndata['ppjbdate']) ? 0 : 1,
'statusproject' => $ndata['isreadytoho']
);
$mimportlog_r = array_merge(array("noid" => $metadata['metadata']->noid), $ndata);
$insert_data['mimportlog'][] = $mimportlog_r;
continue;
}
$matchers = $metadata['matchers'];
$extrafields = $metadata['extrafields'];
if (isset($matchers[$tablename])) {
foreach($matchers[$tablename] as $_fieldname => $value) {
if ($value === (int)$ndata[$_fieldname]) {
$ready = false;
break;
}
}
}
##-
if ($ready) {
if (isset($extrafields[$tablename])) {
foreach($extrafields[$tablename] as $__fieldname => $_value) {
$ndata[$__fieldname] = $_value;
}
}
}
}
##-3
if ($ready) {
$lotno = false;
if ($tablename === 'aptimportdata') {
$lotno = $ndata['lotno'];
$ndata['noid'] = $newid_aptimportdata;
$insert_data_aptunitroom[] = array(
'noid' => $newid_aptimportdata,
'statusproject' => $ndata['isreadytoho'],
'statuslegal' => empty($ndata['ppjbdate']) ? -1 : 1
);
$insert_data_aptimportdataaddress[] = array(
'noid' => $newid_aptimportdata
);
foreach($aptsyarats as $key => &$aptsyaratdata) {
$aptsyaratdata = (array)$aptsyaratdata;
$aptsyaratdata['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptunitroomsyarat[] = $aptsyaratdata;
}
foreach($aptdatabap as $key => $data){
$data = (array)$data;
$data['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptdatabap[] = $data;
}
$newid_aptimportdata++;
}
if ($lotno !== false) {
$insert_data[$tablename][$lotno] = $ndata;
} else {
$insert_data[$tablename][] = $ndata;
}
}
}
}
$real_insert_data = array();
if (isset($insert_data['aptimportdata'])) {
$_aptimportdata = $insert_data['aptimportdata'];
$real_insert_data['aptimportdata'] = array_values($_aptimportdata);
$real_insert_data['mimportlog'] = array_values($_aptimportdata);
foreach($insert_data as $tablename => $datas) {
if ($tablename !== 'aptimportdata' && $tablename !== 'aptunitroom') {
$real_insert_data[$tablename] = array();
foreach($datas as $key => $data) {
if ((!isset($data['idaptunitroom']) || intval($data['idaptunitroom']) === 0) || $_aptimportdata[$data['lotno']]) {
$data['idaptunitroom'] = $_aptimportdata[$data['lotno']]['noid'];
}
$real_insert_data[$tablename][$key] = $data;
}
}
}
} else {
$real_insert_data = $insert_data;
}
if (!empty($insert_data_aptunitroom)) {
$real_insert_data['aptunitroom'] = $insert_data_aptunitroom;
$real_insert_data['aptimportdataaddress'] = $insert_data_aptimportdataaddress;
}
if (!empty($insert_data_aptunitroomsyarat)) {
$real_insert_data['aptunitroomsyarat'] = $insert_data_aptunitroomsyarat;
$real_insert_data['aptunitroomdatabap'] = $insert_data_aptdatabap;
}
$gagal = array();
$dbase = new Sereware\Query($appimport->idconnection);
// var_dump(json_encode($real_insert_data));
// exit();
if (!empty($real_insert_data)) {
foreach($real_insert_data as $tablename => $data) {
try {
$db = $dbase->table($tablename);
$db->insert($data);
}catch(Exception $e){
$gagal['insert'][$tablename] = $e->getMessage();
}
}
}
if (!empty($update_data)) {
foreach($update_data as $tablename => $datas) {
foreach($datas as $noid => $data) {
try {
$db = $dbase->table($tablename);
$db->where('noid','=',$noid);
$db->update($data);
}catch(Exception $e){
$gagal['update'][$tablename] = $e->getMessage();
}
}
}
}
ob_start();
echo !count($gagal);
ob_flush();
}
#}}}
}
i'm still using localhost, and sublime text.
the "altaddress" and "homeaddress" are not inside the code, because it's a columns in the table. you can only find a table name on the code.
my question is how can i make the "altaddress" data from aptimportdata table go to aptimportdataaddress table, i dont't want the altaddress go to aptimportdata table, i just want the data get to aptimportdataaddress.

Codeigniter custom search function issue

Hello I am writing an php application and currently I'm stuck at a method that retrives flights from the database and applies diffrent filters to it. There are no problems when I initially load the page without any filters applied, all records from DB are loaded as expected. Then again everything as expected when I use "Departure Airport" or "Arrival Airport" filters along with "Bookable Only" filter.
It is whole of another story when you try to use "Bookable Only" filter on its own, it doesn't load any records from database. That's the same with "Aircraft" filter, doesn't work on its own and with "Bookable Only" filter but works when combined with both or either one of Airport filters + "Bookable Only" filter
Schedules_model.php
public function getFilteredSchedule($available, $departureICAO, $arrivalICAO, $specificAircraftId)
{
$this->db->select('*');
if($departureICAO != FALSE) {
$this->db->where('departureICAO', $departureICAO);
}
if($arrivalICAO != FALSE) {
$this->db->where('arrivalICAO', $arrivalICAO);
}
if($specificAircraftId != FALSE) {
$this->db->where('aircraftId', $specificAircraftId);
}
$schedules = $this->db->where('active', 1)
->order_by('id', 'asc')
->get('schedules')
->result_array();
$schedulesAvailable = array();
if($available === TRUE) {
echo 'work';
foreach($schedules as $key => $schedule) {
if($this->RebuildVA->mustBeAtDepartureAirport()) {
if($this->Aircrafts->isAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
if(!$this->RebuildVA->allowMultipleAircraftBookings()) {
if(!$this->Aircrafts->isBooked($schedule['aircraftId'])) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
if(!$this->RebuildVA->allowMultiplePilotBookings()) {
if(!$this->Pilots->hasBookedFlight($this->session->userdata('pilotId'))) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
}
} else {
$schedulesAvailable = $schedules;
}
return $schedulesAvailable;
}
schedules.php
public function search()
{
$this->data['pageTitle'] = 'Schedule Search';
$this->data['pageDisplayedTitle'] = 'Schedule Search';
$available = (bool) $this->input->post('available');
$this->data['schedules'] = $this->Schedules->getFilteredSchedule($available, $this->input->post('departureICAO'), $this->input->post('arrivalICAO'), $this->input->post('aircraftId'));
$airportsList = $this->Airports->getAllAirports(TRUE, TRUE); // Get set of all active airports
$aircraftsList = $this->Aircrafts->getAllAircrafts(TRUE, TRUE); // Get set of all active airports
// Prepare form inputs
$this->data['departureICAO'] = array(
'name' => 'departureICAO',
'id' => 'departureICAO',
'selected' => $this->input->post('departureICAO'),
'options' => $airportsList,
);
$this->data['arrivalICAO'] = array(
'name' => 'arrivalICAO',
'id' => 'arrivalICAO',
'selected' => $this->input->post('arrivalICAO'),
'options' => $airportsList,
);
$this->data['aircraftId'] = array(
'name' => 'aircraftId',
'id' => 'aircraftId',
'selected' => $this->input->post('aircraftId'),
'options' => $aircraftsList,
);
$this->data['available'] = array(
'name' => 'available',
'id' => 'available',
'checked' => set_checkbox('available', $this->input->post('available'), FALSE),
'value' => TRUE,
);
$this->load->view('schedules/scheduleSearch', $this->data);
}
I tried debugging everything and following the process step by step as well as trial and error method but none give expected effects. Any ideas?
By trial and error method I have found some kind of a work around that some how does the job. If anyone has any suggestions regarding it or how I could improve it, please feel free, as I am looking for performance in the app.
The required changes were in the Model:
public function getFilteredSchedule($available, $departureICAO, $arrivalICAO, $specificAircraftId)
{
$this->db->select('*');
if($departureICAO != FALSE) {
$this->db->where('departureICAO', $departureICAO);
}
if($arrivalICAO != FALSE) {
$this->db->where('arrivalICAO', $arrivalICAO);
}
if($specificAircraftId != FALSE) {
$this->db->where('aircraftId', $specificAircraftId);
}
$schedules = $this->db->where('active', 1)
->order_by('id', 'asc')
->get('schedules')
->result_array();
$schedulesAvailable = array();
// Check if any of the filters is required
if(!$this->RebuildVA->mustBeAtDepartureAirport() && $this->RebuildVA->allowMultipleAircraftBookings() && $this->RebuildVA->allowMultiplePilotBookings()) {
$schedulesAvailable = $schedules;
// Check if only bookable flights has been checked
} elseif($available === TRUE) {
foreach($schedules as $key => $schedule) {
// Allow multiple schedule bookings
// Check if the aircraft must be at departure airport
if($this->RebuildVA->mustBeAtDepartureAirport()) {
if($this->Aircrafts->isAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
// Check if use of other aircraft of same type is allowed
if($this->RebuildVA->allowOtherAircraftUse()) {
if($this->Aircrafts->aircraftTypeAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
unset($schedulesAvailable[$key]);
continue;
}
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
// Check if there is a limit of only one booking at time per aircraft
if(!$this->RebuildVA->allowMultipleAircraftBookings()) {
if(!$this->Aircrafts->isBooked($schedule['aircraftId'])) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
// Check if there is a limit of only one booking at time per pilot
if(!$this->RebuildVA->allowMultiplePilotBookings()) {
if(!$this->Pilots->hasBookedFlight($this->session->userdata('pilotId'))) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
}
} else {
$schedulesAvailable = $schedules;
}
return $schedulesAvailable;
}

Splitting Order is not working in magento

This code is not completely splitting my order. Still subtotal and grand total of bill is not split up. This code is splitting order's product fine. Is there any other code that is working well with this. I want to split order on the bases of supplier. The products from one supplier should be in one order and the other one's should be in other. Please suggest me some useful links.
Below is my code. This is an observer of order save.
<?php
class Custom_SplitOrderObserver_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage {
/**
* Create order based on checkout type. Create customer if necessary.
*
* #return Mage_Checkout_Model_Type_Onepage
*/
public function saveOrder() {
$this->validate();
$isNewCustomer = false;
switch ($this->getCheckoutMethod()) {
case self::METHOD_GUEST:
$this->_prepareGuestQuote();
break;
case self::METHOD_REGISTER:
$this->_prepareNewCustomerQuote();
$isNewCustomer = true;
break;
default:
$this->_prepareCustomerQuote();
break;
}
$cart = $this->getQuote();
$key = 0;
foreach ($cart->getAllItems() as $item) {
$key = $key + 1;
$temparray[$key]['product_id'] = $item->getProduct()->getId();
$temparray[$key]['qty'] = $item->getQty();
$cart->removeItem($item->getId());
$cart->setSubtotal(0);
$cart->setBaseSubtotal(0);
$cart->setSubtotalWithDiscount(0);
$cart->setBaseSubtotalWithDiscount(0);
$cart->setGrandTotal(0);
$cart->setBaseGrandTotal(0);
$cart->setTotalsCollectedFlag(false);
$cart->collectTotals();
}
$cart->save();
foreach ($temparray as $key => $item) {
$customer_id = Mage::getSingleton('customer/session')->getId();
$store_id = Mage::app()->getStore()->getId();
$customerObj = Mage::getModel('customer/customer')->load($customer_id);
$quoteObj = $cart;
$storeObj = $quoteObj->getStore()->load($store_id);
$quoteObj->setStore($storeObj);
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->load($item['product_id']);
$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
$quoteItem->setBasePrice($productObj->getFinalPrice());
$quoteItem->setPriceInclTax($productObj->getFinalPrice());
$quoteItem->setData('original_price', $productObj->getPrice());
$quoteItem->setData('price', $productObj->getPrice());
$quoteItem->setRowTotal($productObj->getFinalPrice());
$quoteItem->setQuote($quoteObj);
$quoteItem->setQty($item['qty']);
$quoteItem->setStoreId($store_id);
$quoteObj->addItem($quoteItem);
$quoteObj->setBaseSubtotal($productObj->getFinalPrice());
$quoteObj->setSubtotal($productObj->getFinalPrice());
$quoteObj->setBaseGrandTotal($productObj->getFinalPrice());
$quoteObj->setGrandTotal($productObj->getFinalPrice());
$quoteObj->setStoreId($store_id);
$quoteObj->collectTotals();
$quoteObj->save();
$this->_quote = $quoteObj;
$service = Mage::getModel('sales/service_quote', $quoteObj);
$service->submitAll();
if ($isNewCustomer) {
try {
$this->_involveNewCustomer();
} catch (Exception $e) {
Mage::logException($e);
}
}
$this->_checkoutSession->setLastQuoteId($quoteObj->getId())
->setLastSuccessQuoteId($quoteObj->getId())
->clearHelperData();
$order = $service->getOrder();
if ($order) {
Mage::dispatchEvent('checkout_type_onepage_save_order_after', array('order' => $order, 'quote' => $quoteObj));
$quoteObj->removeAllItems();
$quoteObj->setTotalsCollectedFlag(false);
$quoteObj->collectTotals();
}
/**
* a flag to set that there will be redirect to third party after confirmation
* eg: paypal standard ipn
*/
$redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
/**
* we only want to send to customer about new order when there is no redirect to third party
*/
if (!$redirectUrl && $order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e) {
Mage::logException($e);
}
}
// add order information to the session
$this->_checkoutSession->setLastOrderId($order->getId())
->setRedirectUrl($redirectUrl)
->setLastRealOrderId($order->getIncrementId());
// as well a billing agreement can be created
$agreement = $order->getPayment()->getBillingAgreement();
if ($agreement) {
$this->_checkoutSession->setLastBillingAgreementId($agreement->getId());
}
}
// add recurring profiles information to the session
$profiles = $service->getRecurringPaymentProfiles();
if ($profiles) {
$ids = array();
foreach ($profiles as $profile) {
$ids[] = $profile->getId();
}
$this->_checkoutSession->setLastRecurringProfileIds($ids);
// TODO: send recurring profile emails
}
Mage::dispatchEvent(
'checkout_submit_all_after', array('order' => $order, 'quote' => $this->getQuote(), 'recurring_profiles' => $profiles)
);
return $this;
}
}

How do I write code without a foreach loop?

How do I write this code without a foreach loop? I want to fetch the data from the database, but the key and value are stored in the database.
<?php
$options = get_payment_mode_options();
foreach ($options as $key => $value)
{
echo isset($form_data["personal_info"]) && $form_data["personal_info"]->payment_mode == $key ? $value : "";
}
?>
get_payment_mode_options() is function in helper,
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
Check this,
$options = get_payment_mode_options();
$paymentmode = isset($form_data["personal_info"]) ? $form_data["personal_info"]->payment_mode : '';
echo $options[$paymentmode];
helper function
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
<?php
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
// make a new function
function get_your_result($your_key)
{
if (!$your_key) {
return "";
}
$options = get_payment_mode_options();
if(!array_key_exists($your_key,$options)){
return "";
}
return $options[$your_key];
}
// dummy for test
$form_data["personal_info"] = new stdClass();
$form_data["personal_info"]->payment_mode = "o";
$k = $form_data["personal_info"]->payment_mode;
// ~dummy for test
// echo result
echo "----".PHP_EOL;
echo get_your_result($k).PHP_EOL;
echo "----".PHP_EOL;

Categories