function updateCustomer($id) { if (is_null($id)) { Functions::setResponse(400); } $data = Functions::getJSONData(); try { $c = new Customer($id); $oldnick = $c->get('nickname'); $oldemail = $c->get('email'); $passwordUpdate = Functions::get('updatePassword'); foreach ($c->getFields() as $field) { $value = Functions::elt($data, $field['name']); if (is_null($value)) { Functions::setResponse(400); } if ($field['name'] != 'password' || !is_null($passwordUpdate)) { $c->set($field['name'], $value); } } $c->set('id', $id); if (!is_null($passwordUpdate)) { $c->set('password', Functions::hash($c->get('password'))); } if (!testUniqueness($c->get('nickname'), $c->get('email'), $oldnick, $oldemail)) { Functions::setResponse(409); } $c->save(); return true; } catch (RuntimeException $e) { Functions::setResponse(404); } }
public function action_edit_customer() { $customer_id = $this->request->param('options'); $customer_model = new Customer($customer_id); xml::to_XML(array('customer' => $customer_model->get()), $this->xml_content, NULL, 'id'); if (count($_POST)) { $post = new Validation($_POST); $post->filter('trim'); if ($post->validate()) { $customer_model->set($post->as_array()); $this->add_message('Customer "' . $post->get('name') . '" updated'); } } $this->set_formdata($customer_model->get()); }
/** * (non-PHPdoc) * @see DetailsPageAbstract::saveItem() */ public function saveItem($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $task = null; if (isset($param->CallbackParameter->id) && !($task = Task::get(trim($param->CallbackParameter->id))) instanceof Task) { throw new Exception('Invalid Task passed in!'); } if (!isset($param->CallbackParameter->instructions) || ($instructions = trim($param->CallbackParameter->instructions)) === '') { throw new Exception('Instructions are required!'); } if (!isset($param->CallbackParameter->customerId) || !($customer = Customer::get(trim($param->CallbackParameter->customerId))) instanceof Customer) { throw new Exception('Invalid Customer Passed in!'); } $tech = isset($param->CallbackParameter->techId) ? UserAccount::get(trim($param->CallbackParameter->techId)) : null; $order = isset($param->CallbackParameter->orderId) ? Order::get(trim($param->CallbackParameter->orderId)) : null; $dueDate = new UDate(trim($param->CallbackParameter->dueDate)); $status = isset($param->CallbackParameter->statusId) ? TaskStatus::get(trim($param->CallbackParameter->statusId)) : null; if (!$task instanceof Task) { $task = Task::create($customer, $dueDate, $instructions, $tech, $order); } else { $task->setCustomer($customer)->setDueDate($dueDate)->setInstructions($instructions)->setTechnician($tech)->setFromEntityId($order instanceof Order ? $order->getId() : '')->setFromEntityName($order instanceof Order ? get_class($order) : '')->setStatus($status)->save(); } // $results['url'] = '/task/' . $task->getId() . '.html?' . $_SERVER['QUERY_STRING']; $results['item'] = $task->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
public function get($customerId = null, $carId = null) { $sql = "SELECT * FROM {$this->tableName} WHERE 1=1"; if (!empty($customerId)) { $sql .= " AND `owner` = " . $this->db->escape($customerId); } if (!empty($carId)) { $sql .= " AND `id` = " . $this->db->escape($carId); } $result = array(); $service = new Service(); if (!empty($carId)) { $result = $this->db->fetchOne($sql); $customer = new Customer(false); $owner = $customer->get($result['owner']); if (!empty($owner)) { $result['owner'] = $owner; } $result['services'] = $service->getForCar($carId); } else { $result = $this->db->fetchAll($sql); $customer = new Customer(false); foreach ($result as $index => $car) { $owner = $customer->get($car['owner']); if (!empty($owner)) { $result[$index]['owner'] = $owner; } $result[$index]['services'] = $service->getForCar($car['id']); } } new Respond($result); }
/** * Display a listing of the resource. * GET /customers * * @return Response */ public function index() { // $relations = ['contactInfo', 'secretary', 'representatives']; // Can't paginate and eager load at same time $countrow = Customer::get()->count(); $customers = Customer::paginate($countrow); return View::make('customers.index', compact('customers')); }
/** * Getting The end javascript * * @return string */ protected function _getEndJs() { $js = parent::_getEndJs(); if (isset($_REQUEST['poid']) && ($po = PurchaseOrder::get(trim($_REQUEST['poid']))) instanceof PurchaseOrder) { $js .= "pageJs.loadPO( " . json_encode($po->getJson(array(), false, true)) . " );"; } $customer = isset($_REQUEST['customerid']) && ($customer = Customer::get(trim($_REQUEST['customerid']))) instanceof Customer ? $customer->getJson() : null; return $js; }
public static function checkRights($page, $action, $token) { loadClass('status'); loadClass('token'); loadClass('action'); loadClass('right'); loadClass('customer'); if (is_null($action)) { Functions::setResponse(400); } $pagename = str_replace('.php', '', basename($page)); $actionName = $pagename . '-' . $action; $whereClause = 'name=:name'; $params = array(array('id' => ':name', 'value' => $actionName)); $result = Action::search($whereClause, $params); if (!count($result)) { echo 'Please update actions and rights!'; Functions::setResponse(500); } $action = $result[0]; define('LOGGED_OUT_STATUS', 'standard'); $loggedOut = false; if (is_null($token) || strtolower($token) == 'none') { $loggedOut = true; } else { $whereClause = 'value=:value'; $params = array(array('id' => ':value', 'value' => $token)); $result = Token::search($whereClause, $params); if (!count($result)) { Functions::setResponse(498); } else { $token = $result[0]; $customer = new Customer($token->get('customerId')); $status = new Status($customer->get('statusId')); } } if ($loggedOut) { $whereClause = 'name=:name'; $params = array(array('id' => ':name', 'value' => LOGGED_OUT_STATUS)); $result = Status::search($whereClause, $params); if (!count($result)) { Functions::setResponse(500); } $status = $result[0]; } $whereClause = 'action_id=:action_id AND status_id=:status_id'; $params = array(array('id' => ':action_id', 'value' => $action->get('id')), array('id' => ':status_id', 'value' => $status->get('id'))); $result = Right::search($whereClause, $params); if (!count($result)) { Functions::setResponse(401); } if ($result[0]->get('right') == 'deny') { Functions::setResponse(401); } }
/** * Add a bill * * @param int $customer_id * @param num $due_date (UNIX timestamp) * @param str $contact - Their reference * @param arr $items - array( array( 'artnr' => '239D', 'spec' => 'What to bill for', 'price' => 700, 'qty' => 2, 'delivery_date' => '2011-01-01' ), etc ) * @param str $comment - Optional */ public static function new_bill($customer_id, $due_date, $contact, $items, $comment = '', $template = 'default', $mail_body = '') { $pdo = Kohana_pdo::instance(); if (self::$prepared_insert == NULL) { self::$prepared_insert = $pdo->prepare('INSERT INTO bills (due_date,customer_id,customer_name,customer_orgnr,customer_contact,customer_tel,customer_email,customer_street,customer_zip,customer_city,comment,contact,template,mail_body) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)'); self::$prepared_item_insert = $pdo->prepare('INSERT INTO bills_items (item_id,bill_id,artnr,spec,qty,price,delivery_date) VALUES(?,?,?,?,?,?,?)'); } $customer_model = new Customer($customer_id); self::$prepared_insert->execute(array(date('Y-m-d', $due_date), intval($customer_id), $customer_model->get('name'), $customer_model->get('orgnr'), $customer_model->get('contact'), $customer_model->get('tel'), $customer_model->get('email'), $customer_model->get('street'), $customer_model->get('zip'), $customer_model->get('city'), $comment, $contact, $template, $mail_body)); $bill_id = $pdo->lastInsertId(); foreach ($items as $nr => $item) { self::$prepared_item_insert->execute(array($nr + 1, $bill_id, $item['artnr'], $item['spec'], $item['qty'], $item['price'], date('Y-m-d', time()))); } return $bill_id; }
public function verify(SS_HTTPRequest $request) { $token = $request->param('Token'); /** @var CryptofierImplementation $crypto */ $crypto = Injector::inst()->get('CryptofierService'); if ($email = $crypto->decrypt_friendly($token)) { /** @var Customer $member */ if ($member = Customer::get()->filter('Email', $email)->first()) { $member->{ProfiledMemberExtension::VerificationDateName} = date('Y-m-d H:i:s'); $member->write(); ProfiledMemberForm::set_form_message(ProfiledMemberForm::get_form_message('VerificationOK'), 'Your account has been activated', CrackerjackForm::Good); return $this()->redirect(CrackerjackModule::get_config_setting(null, 'post_verify_url')); } } ProfiledMemberForm::set_form_message('VerificationFail', 'bad'); return $this()->redirectBack(); }
/** * (non-PHPdoc) * @see BPCPageAbstract::_preGetEndJs() */ protected function _preGetEndJs() { parent::_preGetEndJs(); $order = $tech = $customer = null; if (isset($_REQUEST['customerId']) && !($customer = Customer::get(trim($_REQUEST['customerId']))) instanceof Customer) { die('Invalid Customer provided!'); } if (isset($_REQUEST['orderId']) && !($order = Order::get(trim($_REQUEST['orderId']))) instanceof Order) { die('Invalid Order provided!'); } if (isset($_REQUEST['techId']) && !($tech = UserAccount::get(trim($_REQUEST['techId']))) instanceof UserAccount) { die('Invalid Technician provided!'); } $statusIds = array(); if (isset($_REQUEST['statusIds']) && ($statusIds = trim($_REQUEST['statusIds'])) !== '') { $statusIds = array_map(create_function('$a', 'return intval(trim($a));'), explode(',', $statusIds)); } $allstatuses = isset($_REQUEST['allstatuses']) && intval(trim($_REQUEST['allstatuses'])) === 1; $preSetData = array('statuses' => array(), 'order' => $order instanceof Order ? $order->getJson() : array(), 'technician' => $tech instanceof UserAccount ? $tech->getJson() : array(), 'customer' => $customer instanceof Customer ? $customer->getJson() : array(), 'meId' => Core::getUser()->getId(), 'noDueDateStatusIds' => array()); $statuses = array(); foreach (TaskStatus::getAll() as $status) { $statuses[] = $statusJson = $status->getJson(); if (($noDueDateChecking = in_array(intval($status->getId()), TaskStatus::getClosedStatusIds())) === true) { $preSetData['noDueDateStatusIds'][] = $status->getId(); } if (count($statusIds) > 0) { if (in_array(intval($status->getId()), $statusIds)) { $preSetData['statuses'][] = $statusJson; } } else { if ($allstatuses === false && !$noDueDateChecking) { $preSetData['statuses'][] = $statusJson; } } } if (count($statusIds) > 0 && count($preSetData['statuses']) === 0) { die('Invalide Task Status provided.'); } $js = "pageJs"; $js .= ".setOpenInFancyBox(" . (isset($_REQUEST['blanklayout']) && intval(trim($_REQUEST['blanklayout'])) === 1 && (isset($_REQUEST['nosearch']) && intval($_REQUEST['nosearch']) === 1) ? 'false' : 'true') . ")"; $js .= ".setStatuses(" . json_encode($statuses) . ")"; $js .= ".setPreSetData(" . json_encode($preSetData) . ")"; $js .= ";"; return $js; }
/** * getCMSFields * Construct the FieldList used in the CMS. To provide a * smarter UI we don't use the scaffolding provided by * parent::getCMSFields. * * @return FieldList */ public function getCMSFields() { Requirements::css('torindul-silverstripe-shop/css/LeftAndMain.css'); $customer = $this->Customer(); $fields = FieldList::create(Tabset::create("Root", Tabset::create("Order", Tab::create("CustomerDetails", HeaderField::create("Customer Selection"), CompositeField::create(DropdownField::create("CustomerID", $this->exists() ? "Customer" : "Select a Customer", Customer::get()->sort(array('Surname' => 'ASC', 'FirstName' => 'ASC'))->map())->setEmptyString("(Select a Customer)")->setRightTitle($this->exists() ? "To change the customer against this order select the new customer above (when editing from the\n\t\t\t\t\t\t\t\t'Store Orders' screen) and click save." : "Which customer is this order for?")), $this->exists() ? HeaderField::create("Customer Details") : null, $this->exists() ? CompositeField::create(ReadonlyField::create("Customer.FirstName", "First Name", $customer->FirstName), ReadonlyField::create("Customer.Surname", "Surname", $customer->Surname), ReadonlyField::create("Customer.CompanyName", "Company", $customer->CompanyName), ReadonlyField::create("Customer.Landline", "Landline Number", $customer->LandlineNumber), ReadonlyField::create("Customer.Mobile", "Mobile Number", $customer->MobileNumber)) : ""), Tab::create("OrderDetails", HeaderField::create("Order Details"), CompositeField::create(DropdownField::create("Status", "Order Status", Order_Statuses::get()->map()), DropdownField::create("BillingAddressID", "Billing Address", DataObject::get("Customer_AddressBook", "(`CustomerID`=" . $this->Customer()->ID . ")")->map())->setRightTitle("Customers' billing address.")->setEmptyString("(Select one)"), DropdownField::create("ShippingAddressID", "Shipping Address", DataObject::get("Customer_AddressBook", "(`CustomerID`=" . $this->Customer()->ID . ")")->map())->setRightTitle("Customers' shipping address.")->setEmptyString("(Select one)")), HeaderField::create("Order Items (Basket)"), CompositeField::create($items = GridField::create("OrderItems", "", $this->Order_Items(), GridFieldConfig_RecordEditor::create()), ReadonlyField::create("SubTotal", "Basket Total (" . Product::getDefaultCurrency() . ")", $this->calculateSubTotal())), HeaderField::create("Shipping"), CompositeField::create(FieldGroup::create(DropdownField::create("Courier", "Courier", $this->getCouriers($this->ID))->setRightTitle("Which courier is being used for this order?")->setEmptyString("(Select one)"), Textfield::create("TrackingNo", "Tracking Number (Optional)")->setRightTitle("If the shipment has a tracking number, enter it here.")), ReadonlyField::create("Shipping", "Shipping Total (" . Product::getDefaultCurrency() . ")", $this->calculateShippingTotal())), HeaderField::create("Order Totals"), CompositeField::create(FieldGroup::create("Tax (" . Product::getDefaultCurrency() . ")", ReadonlyField::create("ProductTaxInclusive", "Product Tax (Inclusive)", $this->calculateProductTax(1))->setRightTitle("Basket total is inclusive of this tax."), ReadonlyField::create("ProductTaxExclusive", "Product Tax (Exclusive)", $this->calculateProductTax(2))->setRightTitle("Basket total is exclusive of this tax."), ReadonlyField::create("ShippingTax", "Shipping Tax", $this->calculateShippingTax($this->calculateShippingTotal()))->setRightTitle(StoreSettings::get_settings()->TaxSettings_ShippingInclusiveExclusive == 1 ? "Shipping price is inclusive of this tax." : "Shipping price is exclusive of this tax.")), FieldGroup::create("Final Totals (" . Product::getDefaultCurrency() . ")", ReadonlyField::create("Total", "Final Total", $this->calculateOrderTotal()), ReadonlyField::create("TotalPayments", "Total Payments", $this->calculatePaymentTotal()), ReadonlyField::create("OutstandingBalance", "Outstanding Balance", $this->calculateRemainingBalance()))), HeaderField::create("Payments"), CompositeField::create($items = GridField::create("OrderPayments", "", $this->Order_Payment(), GridFieldConfig_RecordEditor::create()))), Tab::create("OrderComments", HeaderField::create("Order Comments"), CompositeField::create(ReadonlyField::create("CustomerComments", "Customer Comments")->setRightTitle("These are the comments of this customer."), TextareaField::create("AdminComments", "Admin Comments")->setRightTitle("Only store admins can see these comments"))), Tab::create("OrderEmails", HeaderField::create("Order Emails"), CompositeField::create($items = GridField::create("Order_Emails", "", $this->Order_Emails(), GridFieldConfig_RecordViewer::create())))))); //If record doesn't exist yet, hide certain tabs. !$this->exists() ? $fields->RemoveFieldsFromTab("Root.Order", array("OrderDetails", "OrderComments", "OrderEmails")) : null; /* * If record exists, and order is unpaid show warning message to prevent shipment of unpaid orders. * Otherwise show a success message. */ if ($this->exists() && $this->calculateRemainingBalance() > 0) { $alert = new LiteralField("OrderPayment_LiteralField", "<div class=\"literal-field field\">\n\t\t\t\t\t<div class=\"message error\">\n\t\t\t\t\t\t<strong>ORDER REMAINS UNPAID</strong> - This order has an outstanding balance of " . Product::getDefaultCurrency() . $this->calculateRemainingBalance() . ". If the customer has paid then the\n\t\t\t\t\t\t payment gateway may not have provided a payment status yet.\n\t\t\t\t\t</div>\n\t\t\t\t</div>"); $fields->addFieldToTab("Root.Order", $alert, "Status"); } elseif ($this->exists() && $this->calculateRemainingBalance() == 0) { $alert = new LiteralField("OrderPayment_LiteralField", "<div class=\"literal-field field\">\n\t\t\t\t\t<div class=\"message good\">\n\t\t\t\t\t\t<strong>BALANCE PAID</strong> - This balance of this order has been paid. You may now prepare and \n\t\t\t\t\t\tdispatch the order items below.\n\t\t\t\t\t</div> \n\t\t\t\t</div>"); $fields->addFieldToTab("Root.Order", $alert, "Status"); } return $fields; }
function list_by_parent($id, $customer_id) { $cartdetails = new Cartdetail(); $cartdetails->order_by('id', 'desc'); $cartdetails->where('cart_id', $id); $cartdetails->get(); $customers = new Customer($customer_id); $customers->order_by('id', 'asc'); $customers->where('id', $customer_id); $customers->get(); $dis['base_url'] = base_url(); $dis['view'] = "cartdetail/listbyparent"; $dis['menu_active'] = 'Giỏ hàng'; $dis['title'] = "Chi tiết giỏ hàng"; $dis['title_customer'] = "Thông tin khách hàng"; $dis['cartdetails'] = $cartdetails; $dis['customers'] = $customers; $dis['nav_menu'] = array(array("type" => "back", "text" => "Back", "link" => "{$this->admin_url}carts/list_all/", "onclick" => "")); $this->viewadmin($dis); }
/** * (non-PHPdoc) * @see BPCPageAbstract::_preGetEndJs() */ protected function _preGetEndJs() { // parent::_preGetEndJs(); $order = $task = $customer = null; if (isset($_REQUEST['customerId']) && !($customer = Customer::get(trim($_REQUEST['customerId']))) instanceof Customer) { die('Invalid Customer provided!'); } if (isset($_REQUEST['taskId']) && !($task = Task::get(trim($_REQUEST['taskId']))) instanceof Task) { die('Invalid Order provided!'); } if (isset($_REQUEST['orderId']) && !($order = Order::get(trim($_REQUEST['orderId']))) instanceof Order) { die('Invalid Order provided!'); } $preSetData = array('task' => $task instanceof Task ? $task->getJson() : array(), 'order' => $order instanceof Order ? $order->getJson() : array(), 'customer' => $customer instanceof Customer ? $customer->getJson() : array()); $js = "pageJs"; $js .= ".setOpenInFancyBox(" . (isset($_REQUEST['blanklayout']) && intval(trim($_REQUEST['blanklayout'])) === 1 && (isset($_REQUEST['nosearch']) && intval($_REQUEST['nosearch']) === 1) ? 'false' : 'true') . ")"; $js .= ".setPreSetData(" . json_encode($preSetData) . ")"; $js .= ";"; return $js; }
/** * Customers list * @route GET customers all * @param type $token */ public function all_get($token) { $token_entry = new Token(); $token_entry->get_by_valid_token($token)->get(); if ($token_entry->exists()) { $customers = new Customer(); $customers->order_by('customer_name', 'ASC'); $customers->get(); $response = array(); foreach ($customers as $customer) { $p = new stdClass(); $p->id = $customer->id; $p->customer_name = $customer->customer_name; array_push($response, $p); } $this->response($response); } else { $response = new stdClass(); $response->status = false; $response->error = 'Token not found or session expired'; $this->response($response); } }
function fix($bill_id) { $products = $this->getByBillId($bill_id); $product = new Product(); $price = new Price(); $tax = new Tax(); $bill = new Bill(); $tmp = $bill->get($bill_id); $bill_data = $tmp[0]; $customer = new Customer(); $tmp = $customer->get($bill_data[1]); $customer_data = $tmp[0]; for ($i = 0; $i < count($products); $i++) { $tmp = $this->getByBillIdAndProductId($bill_id, $products[$i][2]); $bill_product_data = $tmp[0]; $tmp = $product->get($products[$i][2]); $product_data = $tmp[0]; $tmp = $price->getPrice($customer_data[11], $product_data[0]); $price_data = $tmp[0]; $tmp = $tax->get($product_data[4]); $tax_data = $tmp[0]; $this->update($bill_product_data[0], array($bill_product_data[1], $bill_product_data[2], $bill_product_data[3], $bill_product_data[4], $bill_product_data[5], $price_data[3], $tax_data[2])); } }
<?php require_once "util.php"; require_once "NTK/NTK.php"; require_once "DataBase/Customer.php"; require_once "DataBase/Tour.php"; $customer = new Customer(); $tour = new Tour(); if (var_post("print", "") == "print") { $search = ""; $tour_data = ""; if (!var_post("tour_all", "")) { $search = " tour_id='" . var_post("tour", "") . "' "; $tour_data = $tour->get(var_post("tour", ''), array()); } $customer_data = $customer->get('', array(), $search); include "Druckvorlagen/zeilen.php"; include "Druckvorlagen/customer_list.php"; } else { $toolbar_box = new NTKVBox("toolbar_box", 0, 0, False); $main_box = new NTKTable("main_box", 3, 2, False); $main_box->setStyle("background-color: #dfe7f3;"); $main_box->add(new NTKLabel("", "alle Touren"), 0, 0); $main_box->add(new NTKCheckbox("tour_all", 1, False), 0, 1); $main_box->add(new NTKLabel("", "aus Tour"), 1, 0); $main_box->add(new NTKComboBox("tour", $tour->get("")), 1, 1); $main_box->add(new NTKButton("submit", "Druckvorschau", "document.forms['print'].submit();"), 2, 1); $form = new NTKForm("print", "stat_customer_list.php", $main_box); $form->addAttribute("print", "print"); $toolbar_box->add($form, 0, 0); echo getHead();
require_once "util.php"; require_once "DataBase/Bill.php"; require_once "DataBase/Assistant.php"; require_once "DataBase/Customer.php"; require_once "DataBase/Product.php"; require_once "DataBase/Bill_Product.php"; require_once "DataBase/Price.php"; require_once "DataBase/Priceset.php"; require_once "DataBase/Tax.php"; $bill_id = var_get_post("bill_id", ""); $bill = new Bill(); $tmp = $bill->get($bill_id); $bill_data = $tmp[0]; $customer = new Customer(); $tmp = $customer->get($bill_data[1]); $customer_data = $tmp[0]; $assistant = new Assistant(); $tmp = $assistant->get($bill_data[4]); $assistant_data = $tmp[0]; $priceset = new Priceset(); $tmp = $priceset->get($customer_data[11]); $priceset_data = $tmp[0]; $bill_product = new Bill_Product(); $bill_product_data = $bill_product->getByBillId($bill_id); $product = new Product(); $price = new Price(); $tax = new Tax(); include "Druckvorlagen/zeilen.php"; include "Druckvorlagen/rechnung.php"; ?>
<?php include "session_check.php"; include "header.php"; include "menu.php"; require_once "util.php"; require_once "DataBase/Product.php"; require_once "DataBase/Customer.php"; require_once "DataBase/Price.php"; require_once "DataBase/Priceset.php"; /* TODO: check if valid $priceset_id and what if no $customer_data found? */ $customer = new Customer(); $customer_data = $customer->get($_SESSION["username"]); $priceset_id = 0; if (count($customer_data) > 0) { $priceset_id = $customer_data[0][11]; } $priceset = new Priceset(); $product = new Product(); $price = new Price(); $tmp_priceset = $priceset->get($priceset_id); $netto = 0; if (count($tmp_priceset) > 0) { $netto = $tmp_priceset[0][2]; } ?> <div width="100%" align="center"> <?php // prepare search/filter params
require_once "DataBase/Customer.php"; // sync Customer database $customer = new Customer(); $customer_net = new Customer_Net(); $new_customer_count = 0; $del_customer_count = 0; // fetch all remote customers $remote_customers = $customer_net->get('', array('customer_id')); foreach ($remote_customers as $tmp) { if ($customer->exists($tmp[0]) == false) { $customer_net->delete($tmp[0]); $del_customer_count++; } } $remote_customers = $customer_net->get('', array('customer_id')); $local_customers = $customer->get('', array('customer_id')); foreach ($local_customers as $tmp) { $found = false; foreach ($remote_customers as $remote_tmp) { if ($remote_tmp[0] == $tmp[0]) { $found = true; break; } } $tmp_data = $customer->get($tmp[0], array("password", "prename", "postname", "street", "streetnumber", "plz", "city", "telephone", "telefax", "email", "pricelist_id", "tour_id", "rabatt", "details", "bank_name", "bank_account", "blz")); if (!$found) { $customer_net->create($tmp[0], $tmp_data[0]); $new_customer_count++; } else { $customer_net->update($tmp[0], $tmp_data[0]); }
<?php require_once "util.php"; require_once "NTK/NTK.php"; require_once "DataBase/Customer.php"; ?> <html> <head> <title> Index </title> <?php echo getHead(); $search = var_get("search", ""); if (strlen($search) >= 3) { $customer = new Customer(); $main_box = new NTKVBox("main_box", 0, 0, False); $list_view = new NTKListView("list_view", array('Kundennummer', 'Vorname', 'Nachname'), "parent.frames['main'].document." . var_get("form", "") . "." . var_get("entry", "") . ".value = '%0%';parent.frames['main'].document." . var_get("form", "") . "." . var_get("next", "") . ".focus();"); $list_view->addLines($customer->get('', array('customer_id', 'prename', 'postname'), "customer_id LIKE '%{$search}%' OR prename LIKE'%{$search}%' OR postname LIKE '%{$search}%'")); $main_box->add($list_view, -1, -1, "background-color: #dfe7f3; vertical-align: top;"); echo $main_box->getHtml(); } ?> </body> </html>
function createBill() { $bill = new Bill(); $customer = new Customer(); $tour = new Tour(); $bill_product = new Bill_Product(); $customer_data = $customer->get($this->customer_id); if (count($customer_data) == 0) { echo "<div class=\"error\">Fehler in Session, bitte neu anmelden</div><br>\n"; return -1; } $tour_data = $tour->getByAssistant($customer_data[0][12]); $bill_id = $bill->create("", array($this->customer_id, $customer_data[0][12], "", $tour_data[0][2], -2, time())); $list = $this->getItems(); for ($i = 0; $i < count($list); $i++) { if ($list[$i][2] > 0) { $bill_product->create(array($bill_id, $list[$i][0], $list[$i][2], $list[$i][5], "", 0, 0, time())); } } return 0; }
require_once "DataBase/Bill_Product_Import.php"; require_once "DataBase/Customer.php"; require_once "DataBase/Tour.php"; // import new bills $bill = new Bill(); $bill_product = new Bill_Product(); $bill_import = new Bill_Import(); $bill_product_import = new Bill_Product_Import(); $customer = new Customer(); $tour = new Tour(); if ($bill_import->import("mysql_import/bill.csv") == 0 && $bill_product_import->import("mysql_import/bill_product.csv") == 0) { /* import bills from bill_import and products from bill_product_import */ $bills = $bill_import->get(); for ($i = 0; $i < count($bills); $i++) { if (!$bill->hasTimestamp($bills[$i][6])) { $customer_data = $customer->get($bills[$i][1]); if (count($customer_data) == 0) { echo "Fehler: websync.php import bills from bill_import no customer data"; continue; } $tour_data = $tour->get($customer_data[0][12]); $date = getdate(time()); $new_bill_id = $bill->create("", array($bills[$i][1], $customer_data[0][12], $date['year'] . "-" . $date['mon'] . "-" . $date['mday'], $tour_data[0][2], -2, $bills[$i][6])); $bill_products = $bill_product_import->getByBillId($bills[$i][0]); for ($j = 0; $j < count($bill_products); $j++) { $bill_product->create(array($new_bill_id, $bill_products[$j][2], $bill_products[$j][3], $bill_products[$j][4], 0, 0, 0)); } } } $main_box->add($spacer, True, True, "background-color: #dfe7f3;"); $main_box->add(new NTKLabel("", "Fertig"), False, False, "font-style: bold; background-color: #dfe7f3;");
require_once "DataBase/Product.php"; require_once "DataBase/Customer.php"; require_once "DataBase/Price.php"; require_once "DataBase/Tax.php"; $db_action = var_get_post("db_action", ""); $bill = new Bill(); $tour = new Tour(); $assistant = new Assistant(); $bill_product = new Bill_Product(); $product = new Product(); $customer = new Customer(); $price = new Price(); $tax = new Tax(); switch ($db_action) { case "new": $customer_data = $customer->get(var_post("customer_id", "")); if (count($customer_data) > 0) { $tour_data = $tour->getByAssistant($customer_data[0][12]); if (count($tour_data) > 0) { $bill_id = $bill->create(var_post("bill_id", ""), array(var_post("customer_id", ""), $customer_data[0][12], var_post("date", ""), $tour_data[0][2], -1, 0)); } else { $bill_id = $bill->create(var_post("bill_id", ""), array(var_post("customer_id", ""), $customer_data[0][12], var_post("date", ""), 1, -1, 0)); } } else { $bill_id = $bill->create(var_post("bill_id", ""), array(var_post("customer_id", ""), '', var_post("date", ""), var_post("assistant_id", "1"), -1, 0)); } $action = "edit"; break; case "edit": $bill->update(var_post("bill_id", ""), array(var_post("customer_id", ""), var_post("tour_id", ""), var_post("date", ""), var_post("assistant_id", ""), var_post("bill_number", ""))); if ($fp_tour_id != "") {
<a href="javascript: history.back();">Zurück</a> <div width="100%" align="center"> <table border="0" width="80%" class="product_details"> <?php require_once "DataBase/Product.php"; require_once "DataBase/Customer.php"; require_once "DataBase/Price.php"; require_once "DataBase/Priceset.php"; $product = new Product(); $customer = new Customer(); $price = new Price(); $priceset = new Priceset(); $customer_data = $customer->get($_SESSION['username']); $priceset_id = 0; if (count($customer_data) > 0) { $priceset_id = $customer_data[0][11]; } $tmp_priceset = $priceset->get($priceset_id); $netto = 0; if (count($tmp_priceset) > 0) { $netto = $tmp_priceset[0][2]; } // prepare search/filter params $product_id = var_get_post("product_id", ""); $list = $product->get($product_id); // $count = $product->getCountByFilter($search_product, $search_category); for ($i = 0; $i < count($list); $i++) { $tmp_price = $price->getPrice($priceset_id, $list[$i][0]);
/** * saveOrder * * @param unknown $sender * @param unknown $param * * @throws Exception * */ public function saveOrder($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $customer = Customer::get(trim($param->CallbackParameter->customer->id)); if (!$customer instanceof Customer) { throw new Exception('Invalid Customer passed in!'); } if (!isset($param->CallbackParameter->type) || ($type = trim($param->CallbackParameter->type)) === '' || !in_array($type, Order::getAllTypes())) { throw new Exception('Invalid type passed in!'); } $order = null; if (isset($param->CallbackParameter->orderId) && ($orderId = trim($param->CallbackParameter->orderId)) !== '') { if (!($order = Order::get($orderId)) instanceof Order) { throw new Exception('Invalid Order to edit!'); } } $orderCloneFrom = null; if (isset($param->CallbackParameter->orderCloneFromId) && ($orderCloneFromId = trim($param->CallbackParameter->orderCloneFromId)) !== '') { if (!($orderCloneFrom = Order::get($orderCloneFromId)) instanceof Order) { throw new Exception('Invalid Order to clone from!'); } } $shipped = isset($param->CallbackParameter->shipped) && intval($param->CallbackParameter->shipped) === 1; $poNo = isset($param->CallbackParameter->poNo) && trim($param->CallbackParameter->poNo) !== '' ? trim($param->CallbackParameter->poNo) : ''; if (isset($param->CallbackParameter->shippingAddr)) { $shippAddress = $order instanceof Order ? $order->getShippingAddr() : null; $shippAddress = Address::create($param->CallbackParameter->shippingAddr->street, $param->CallbackParameter->shippingAddr->city, $param->CallbackParameter->shippingAddr->region, $param->CallbackParameter->shippingAddr->country, $param->CallbackParameter->shippingAddr->postCode, $param->CallbackParameter->shippingAddr->contactName, $param->CallbackParameter->shippingAddr->contactNo, $param->CallbackParameter->shippingAddr->companyName, $shippAddress); } else { $shippAddress = $customer->getShippingAddress(); } $printItAfterSave = false; if (isset($param->CallbackParameter->printIt)) { $printItAfterSave = intval($param->CallbackParameter->printIt) === 1 ? true : false; } if (!$order instanceof Order) { $order = Order::create($customer, $type, null, '', OrderStatus::get(OrderStatus::ID_NEW), new UDate(), false, $shippAddress, $customer->getBillingAddress(), false, $poNo, $orderCloneFrom); } else { $order->setType($type)->setPONo($poNo)->save(); } $totalPaymentDue = 0; if (trim($param->CallbackParameter->paymentMethodId)) { $paymentMethod = PaymentMethod::get(trim($param->CallbackParameter->paymentMethodId)); if (!$paymentMethod instanceof PaymentMethod) { throw new Exception('Invalid PaymentMethod passed in!'); } $totalPaidAmount = trim($param->CallbackParameter->totalPaidAmount); $order->addPayment($paymentMethod, $totalPaidAmount); $order = Order::get($order->getId()); $order->addInfo(OrderInfoType::ID_MAGE_ORDER_PAYMENT_METHOD, $paymentMethod->getName(), true); if ($shipped === true) { $order->setType(Order::TYPE_INVOICE); } } else { $paymentMethod = ''; $totalPaidAmount = 0; } foreach ($param->CallbackParameter->items as $item) { $product = Product::get(trim($item->product->id)); if (!$product instanceof Product) { throw new Exception('Invalid Product passed in!'); } if (isset($item->active) && intval($item->active) === 1 && intval($product->getActive()) !== 1 && $type === Order::TYPE_INVOICE) { throw new Exception('Product(SKU:' . $product->getSku() . ') is DEACTIVATED, please change it to be proper product before converting it to a ' . $type . '!'); } $unitPrice = trim($item->unitPrice); $qtyOrdered = trim($item->qtyOrdered); $totalPrice = trim($item->totalPrice); $itemDescription = trim($item->itemDescription); if (intval($item->active) === 1) { $totalPaymentDue += $totalPrice; if ($orderCloneFrom instanceof Order || !($orderItem = OrderItem::get($item->id)) instanceof OrderItem) { $orderItem = OrderItem::create($order, $product, $unitPrice, $qtyOrdered, $totalPrice, 0, null, $itemDescription); } else { $orderItem->setActive(intval($item->active))->setProduct($product)->setUnitPrice($unitPrice)->setQtyOrdered($qtyOrdered)->setTotalPrice($totalPrice)->setItemDescription($itemDescription)->save(); $existingSellingItems = SellingItem::getAllByCriteria('orderItemId = ?', array($orderItem->getId())); foreach ($existingSellingItems as $sellingItem) { //DELETING ALL SERIAL NUMBER BEFORE ADDING $sellingItem->setActive(false)->save(); } } $orderItem = OrderItem::get($orderItem->getId())->reCalMarginFromProduct()->resetCostNMarginFromKits()->save(); } else { if ($orderCloneFrom instanceof Order) { continue; } elseif (($orderItem = OrderItem::get($item->id)) instanceof OrderItem) { $orderItem->setActive(false)->save(); } } if (isset($item->serials) && count($item->serials) > 0) { foreach ($item->serials as $serialNo) { $orderItem->addSellingItem($serialNo)->save(); } } if ($shipped === true) { $orderItem->setIsPicked(true)->save(); } } if (isset($param->CallbackParameter->courierId)) { $totalShippingCost = 0; $courier = null; if (is_numeric($courierId = trim($param->CallbackParameter->courierId))) { $courier = Courier::get($courierId); if (!$courier instanceof Courier) { throw new Exception('Invalid Courier passed in!'); } $order->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD, $courier->getName(), true); } else { $order->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD, $courierId, true); } if (isset($param->CallbackParameter->totalShippingCost)) { $totalShippingCost = StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->totalShippingCost)); $order->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST, StringUtilsAbstract::getCurrency($totalShippingCost), true); } if ($shipped === true) { if (!$courier instanceof Courier) { $courier = Courier::get(Courier::ID_LOCAL_PICKUP); } Shippment::create($shippAddress, $courier, '', new UDate(), $order, ''); } } else { $courier = ''; $totalShippingCost = 0; } $totalPaymentDue += $totalShippingCost; $comments = isset($param->CallbackParameter->comments) ? trim($param->CallbackParameter->comments) : ''; $order = $order->addComment($comments, Comments::TYPE_SALES)->setTotalPaid($totalPaidAmount); if ($shipped === true) { $order->setStatus(OrderStatus::get(OrderStatus::ID_SHIPPED)); } $order->setTotalAmount($totalPaymentDue)->save(); if (isset($param->CallbackParameter->newMemo) && ($newMemo = trim($param->CallbackParameter->newMemo)) !== '') { $order->addComment($newMemo, Comments::TYPE_MEMO); } $results['item'] = $order->getJson(); if ($printItAfterSave === true) { $results['printURL'] = '/print/order/' . $order->getId() . '.html?pdf=1'; } $results['redirectURL'] = '/order/' . $order->getId() . '.html' . (trim($_SERVER['QUERY_STRING']) === '' ? '' : '?' . $_SERVER['QUERY_STRING']); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * saveOrder * * @param unknown $sender * @param unknown $param * * @throws Exception * */ public function saveOrder($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $customer = Customer::get(trim($param->CallbackParameter->customer->id)); if (!$customer instanceof Customer) { throw new Exception('Invalid Customer passed in!'); } if (!isset($param->CallbackParameter->status) || ($status = trim($param->CallbackParameter->status)) === '' || !in_array($status, RMA::getAllStatuses())) { throw new Exception('Invalid Status passed in!'); } if (isset($param->CallbackParameter->RMA) && !($RMA = RMA::get(trim($param->CallbackParameter->RMA->id))) instanceof RMA) { throw new Exception('Invalid RMA To passed in!'); } $RMA = isset($param->CallbackParameter->RMA) && ($RMA = RMA::get(trim($param->CallbackParameter->RMA->id))->setDescription(trim($param->CallbackParameter->description))) instanceof RMA ? $RMA : RMA::create($customer, trim($param->CallbackParameter->description)); if (isset($param->CallbackParameter->order) && ($order = Order::get(trim($param->CallbackParameter->order->id))) instanceof Order) { $RMA->setOrder($order); } if (isset($param->CallbackParameter->shippingAddr)) { $shippAddress = Address::create($param->CallbackParameter->shippingAddr->street, $param->CallbackParameter->shippingAddr->city, $param->CallbackParameter->shippingAddr->region, $param->CallbackParameter->shippingAddr->country, $param->CallbackParameter->shippingAddr->postCode, $param->CallbackParameter->shippingAddr->contactName, $param->CallbackParameter->shippingAddr->contactNo, $param->CallbackParameter->shippingAddr->companyName); $customer->setShippingAddress($shippAddress); } $printItAfterSave = false; if (isset($param->CallbackParameter->printIt)) { $printItAfterSave = intval($param->CallbackParameter->printIt) === 1 ? true : false; } if (isset($param->CallbackParameter->comments)) { $comments = trim($param->CallbackParameter->comments); $RMA->addComment($comments, Comments::TYPE_SALES); } $totalPaymentDue = 0; foreach ($param->CallbackParameter->items as $item) { $product = Product::get(trim($item->product->id)); if (!$product instanceof Product) { throw new Exception('Invalid Product passed in!'); } $unitPrice = trim($item->unitPrice); $qtyOrdered = trim($item->qtyOrdered); $totalPrice = trim($item->totalPrice); $itemDescription = trim($item->itemDescription); $active = trim($item->valid); $totalPaymentDue += $totalPrice; if (is_numeric($item->RMAItemId) && !RMAItem::get(trim($item->RMAItemId)) instanceof RMAItem) { throw new Exception('Invalid RMA Item passed in'); } $RMAItem = is_numeric($item->RMAItemId) ? RMAItem::get(trim($item->RMAItemId))->setActive($active)->setProduct($product)->setQty($qtyOrdered)->setItemDescription($itemDescription) : RMAItem::create($RMA, $product, $qtyOrdered, $itemDescription); if (isset($item->orderItemId) && ($orderItem = OrderItem::get(trim($item->orderItemId))) instanceof OrderItem) { $RMAItem->setOrderItem($orderItem)->setUnitCost($orderItem->getUnitCost()); } if (isset($item->RMAItemId) && ($RMAItem = RMAItem::get(trim($item->RMAItemId))) instanceof RMAItem && $product->getUnitCost() != 0) { $RMAItem->setUnitCost($RMAItem->getUnitCost())->save(); } else { $RMAItem->setUnitCost($product->getUnitCost())->save(); } $RMAItem->save(); } $RMA->setTotalValue($totalPaymentDue)->setStatus($status)->save(); $results['item'] = $RMA->getJson(); // if($printItAfterSave === true) // $results['printURL'] = '/print/rma/' . $RMA->getId() . '.html?pdf=1'; Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); // $errors[] = $ex->getMessage(); $errors[] = $ex->getTraceAsString(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
<?php require 'JsonDB.php'; require 'Customer.php'; $cliente = Customer::get('444', new JsonDB('db.txt')); $cliente->name = 'Maria José'; $cliente->save();
/** * saveOrder * * @param unknown $sender * @param unknown $param * * @throws Exception * */ public function saveOrder($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $customer = Customer::get(trim($param->CallbackParameter->customer->id)); if (!$customer instanceof Customer) { throw new Exception('Invalid Customer passed in!'); } if (!isset($param->CallbackParameter->applyTo) || ($applyTo = trim($param->CallbackParameter->applyTo)) === '' || !in_array($applyTo, CreditNote::getApplyToTypes())) { throw new Exception('Invalid Apply To passed in!'); } if (isset($param->CallbackParameter->creditNoteId) && ($creditNote = CreditNote::get(trim($param->CallbackParameter->creditNoteId))) instanceof CreditNote) { $creditNote = $creditNote; } else { if (isset($param->CallbackParameter->orderId) && ($order = Order::get(trim($param->CallbackParameter->orderId))) instanceof Order) { $creditNote = CreditNote::createFromOrder($order, $customer, trim($param->CallbackParameter->description)); } else { $creditNote = CreditNote::create($customer, trim($param->CallbackParameter->description)); } } $creditNote->setShippingValue(isset($param->CallbackParameter->totalShippingCost) ? StringUtilsAbstract::getValueFromCurrency($param->CallbackParameter->totalShippingCost) : 0); if (isset($param->CallbackParameter->shippingAddr)) { $shippAddress = Address::create($param->CallbackParameter->shippingAddr->street, $param->CallbackParameter->shippingAddr->city, $param->CallbackParameter->shippingAddr->region, $param->CallbackParameter->shippingAddr->country, $param->CallbackParameter->shippingAddr->postCode, $param->CallbackParameter->shippingAddr->contactName, $param->CallbackParameter->shippingAddr->contactNo); $customer->setShippingAddress($shippAddress); } $printItAfterSave = false; if (isset($param->CallbackParameter->printIt)) { $printItAfterSave = intval($param->CallbackParameter->printIt) === 1 ? true : false; } if (isset($param->CallbackParameter->comments)) { $comments = trim($param->CallbackParameter->comments); $creditNote->addComment($comments, Comments::TYPE_SALES); } $totalPaymentDue = $creditNote->getShippingValue(); $hasShipped = $creditNote->getOrder() instanceof Order && Shippment::countByCriteria('orderId = ?', array($creditNote->getOrder()->getId())) > 0; $creditNoteItemsMap = array(); foreach ($param->CallbackParameter->items as $item) { if (!($product = Product::get(trim($item->product->id))) instanceof Product) { throw new Exception('Invalid Product passed in!'); } $unitPrice = StringUtilsAbstract::getValueFromCurrency(trim($item->unitPrice)); $qtyOrdered = trim($item->qtyOrdered); $totalPrice = StringUtilsAbstract::getValueFromCurrency(trim($item->totalPrice)); $itemDescription = trim($item->itemDescription); $active = trim($item->valid); $totalPaymentDue += $totalPrice; if (is_numeric($item->creditNoteItemId) && !CreditNoteItem::get(trim($item->creditNoteItemId)) instanceof CreditNoteItem) { throw new Exception('Invalid Credit Note Item passed in'); } $unitCost = $product->getUnitCost(); $orderItem = null; if (isset($item->orderItemId) && ($orderItem = OrderItem::get(trim($item->orderItemId))) instanceof OrderItem) { $unitCost = $orderItem->getUnitCost(); } $creditNoteItem = is_numeric($item->creditNoteItemId) ? CreditNoteItem::get(trim($item->creditNoteItemId))->setActive($active)->setProduct($product)->setQty($qtyOrdered)->setUnitPrice($unitPrice)->setItemDescription($itemDescription)->setUnitCost($unitCost)->setTotalPrice($totalPrice)->save() : ($orderItem instanceof OrderItem ? CreditNoteItem::createFromOrderItem($creditNote, $orderItem, $qtyOrdered, $unitPrice, $itemDescription, $unitCost, $totalPrice) : CreditNoteItem::create($creditNote, $product, $qtyOrdered, $unitPrice, $itemDescription, $unitCost, $totalPrice)); if (intval($creditNoteItem->getActive()) === 1) { if (!isset($creditNoteItemsMap[$product->getId()])) { $creditNoteItemsMap[$product->getId()] = 0; } $creditNoteItemsMap[$product->getId()] += $qtyOrdered; } //if we are not creating from a order, or there are shippments for this order then if (!$creditNote->getOrder() instanceof Order || $hasShipped === true) { switch (trim($item->stockData)) { case 'StockOnHand': $product->returnedIntoSOH($qtyOrdered, $creditNoteItem->getUnitCost(), '', $creditNoteItem); break; case 'StockOnRMA': $product->returnedIntoRMA($qtyOrdered, $creditNoteItem->getUnitCost(), '', $creditNoteItem); break; default: throw new Exception('System Error: NO where to transfer the stock: ' . trim($item->stockData) . ' for product(SKU=' . $product->getSku() . ').'); } } else { //revert all the shipped stock foreach (OrderItem::getAllByCriteria('ord_item.orderId = ? and ord_item.isShipped = 1', array($creditNote->getOrder()->getId())) as $orderItem) { $orderItem->setIsShipped(false)->save(); } //revert all the picked stock foreach (OrderItem::getAllByCriteria('ord_item.orderId = ? and ord_item.isPicked = 1', array($creditNote->getOrder()->getId())) as $orderItem) { $orderItem->setIsPicked(false)->save(); } } } if (($paymentMethod = PaymentMethod::get(trim($param->CallbackParameter->paymentMethodId))) instanceof PaymentMethod) { $creditNote->setTotalPaid($totalPaidAmount = $param->CallbackParameter->totalPaidAmount)->addPayment($paymentMethod, $totalPaidAmount); } $creditNote->setTotalValue($totalPaymentDue)->setApplyTo($applyTo)->save(); //if need to check half credited orders if ($creditNote->getOrder() instanceof Order && $hasShipped === false) { $orderItemMap = array(); foreach ($order->getOrderItems() as $orderItem) { $productId = $orderItem->getProduct()->getId(); if (!isset($orderItemMap[$productId])) { $orderItemMap[$productId] = 0; } $orderItemMap[$productId] += $orderItem->getQtyOrdered(); } //figure out the difference foreach ($creditNoteItemsMap as $productId => $qty) { if (isset($orderItemMap[$productId])) { if ($orderItemMap[$productId] <= $qty) { //credited more than orderred unset($orderItemMap[$productId]); } else { //credited less then ordered $orderItemMap[$productId] = $orderItemMap[$productId] - $qty; } } } $orderItemMap = array_filter($orderItemMap); if (count($orderItemMap) > 0) { //there are difference $creditNote->creditFullOrder(); $newOrder = Order::create($creditNote->getOrder()->getCustomer(), $creditNote->getOrder()->getType() === 'INVOICE' ? Order::TYPE_ORDER : $creditNote->getOrder()->getType(), null, 'Spliting order because of partial credit note(CreditNoteNo:.' . $creditNote->getCreditNoteNo() . ') created', null, $creditNote->getOrder()->getOrderDate(), false, $creditNote->getOrder()->getShippingAddr(), $creditNote->getOrder()->getBillingAddr(), $creditNote->getOrder()->getPassPaymentCheck(), $creditNote->getOrder()->getPONo(), $creditNote->getOrder())->addComment('Created because of partial credit from '); $totalAmount = 0; foreach ($orderItemMap as $productId => $qty) { $orderItems = OrderItem::getAllByCriteria('productId = ? and orderId = ?', array($productId, $creditNote->getOrder()->getId()), true, 1, 1); if (count($orderItems) > 0) { $totalAmount += $orderItems[0]->getUnitPrice() * $qty; } $newOrder->addItem($orderItems[0]->getProduct(), $orderItems[0]->getUnitPrice(), $qty, $orderItems[0]->getTotalPrice(), $orderItems[0]->getMageOrderId(), $orderItems[0]->getEta(), $orderItems[0]->getItemDescription()); } if (count($shippingMethods = $creditNote->getOrder()->getInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD)) > 0) { $newOrder->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD, $shippingMethods[0], true); } if (count($shippingCost = $creditNote->getOrder()->getInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST)) > 0) { $newOrder->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST, $shippingCost[0], true); $totalAmount += StringUtilsAbstract::getValueFromCurrency($shippingCost[0]); } $results['newOrder'] = $newOrder->setTotalAmount($totalAmount)->save()->getJson(); $creditNote->getOrder()->setStatus(OrderStatus::get(OrderStatus::ID_CANCELLED))->save()->addComment('This ' . $creditNote->getOrder()->getType() . ' is CANCELED, because of partial credit (CreditNoteNo:<a href="/creditnote/' . $creditNote->getId() . '.html" target="_BLANK">' . $creditNote->getCreditNoteNo() . '</a>) is created and a new ' . $newOrder->getType() . ' (<a href="/orderdetails/' . $newOrder->getId() . '.html?blanklayout=1">' . $newOrder->getOrderNo() . '</a>) is created for the diference.', Comments::TYPE_MEMO); } else { $creditNote->getOrder()->setStatus(OrderStatus::get(OrderStatus::ID_CANCELLED))->save()->addComment('This ' . $creditNote->getOrder()->getType() . ' is CANCELED, because of full credit (CreditNoteNo:<a href="/creditnote/' . $creditNote->getId() . '.html" target="_BLANK">' . $creditNote->getCreditNoteNo() . '</a>) is created.', Comments::TYPE_MEMO); } } $results['item'] = $creditNote->getJson(); $results['redirectURL'] = '/creditnote/' . $creditNote->getId() . '.html?' . $_SERVER['QUERY_STRING']; if ($printItAfterSave === true) { $results['printURL'] = '/print/creditnote/' . $creditNote->getId() . '.html?pdf=1'; } Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage() . '<pre>' . $ex->getTraceAsString() . '</pre>'; } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
public function process($data, $form) { $this->extend('onBeforeProcess', $data); //Check payment type try { $paymentMethod = Convert::raw2sql($data['PaymentMethod']); $paymentProcessor = PaymentFactory::factory($paymentMethod); } catch (Exception $e) { Debug::friendlyError(403, _t('CheckoutPage.NOT_VALID_METHOD', "Sorry, that is not a valid payment method."), _t('CheckoutPage.TRY_AGAIN', "Please go back and try again.")); return; } //Save or create a new customer/member $member = Customer::currentUser() ? Customer::currentUser() : singleton('Customer'); if (!$member->exists()) { $existingCustomer = Customer::get()->filter('Email', $data['Email']); if ($existingCustomer && $existingCustomer->exists()) { $form->sessionMessage(_t('CheckoutPage.MEMBER_ALREADY_EXISTS', 'Sorry, a member already exists with that email address. If this is your email address, please log in first before placing your order.'), 'bad'); $this->controller->redirectBack(); return false; } $member = Customer::create(); $form->saveInto($member); $member->write(); $member->addToGroupByCode('customers'); $member->logIn(); } //Save the order $order = Cart::get_current_order(); $items = $order->Items(); $form->saveInto($order); $order->MemberID = $member->ID; $order->Status = Order::STATUS_PENDING; $order->OrderedOn = SS_Datetime::now()->getValue(); $order->write(); //Saving an update on the order if ($notes = $data['Notes']) { $update = new Order_Update(); $update->Note = $notes; $update->Visible = true; $update->OrderID = $order->ID; $update->MemberID = $member->ID; $update->write(); } //Add modifiers to order $order->updateModifications($data)->write(); Session::clear('Cart.OrderID'); $order->onBeforePayment(); try { $shopConfig = ShopConfig::current_shop_config(); $precision = $shopConfig->BaseCurrencyPrecision; $paymentData = array('Amount' => number_format($order->Total()->getAmount(), $precision, '.', ''), 'Currency' => $order->Total()->getCurrency(), 'Reference' => $order->ID); $paymentProcessor->payment->OrderID = $order->ID; $paymentProcessor->payment->PaidByID = $member->ID; $paymentProcessor->setRedirectURL($order->Link()); $paymentProcessor->capture($paymentData); } catch (Exception $e) { //This is where we catch gateway validation or gateway unreachable errors $result = $paymentProcessor->gateway->getValidationResult(); $payment = $paymentProcessor->payment; //TODO: Need to get errors and save for display on order page SS_Log::log(new Exception(print_r($result->message(), true)), SS_Log::NOTICE); SS_Log::log(new Exception(print_r($e->getMessage(), true)), SS_Log::NOTICE); $this->controller->redirect($order->Link()); } }
/** * (non-PHPdoc) * @see DetailsPageAbstract::saveItem() */ public function saveItem($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $name = trim($param->CallbackParameter->name); $id = !is_numeric($param->CallbackParameter->id) ? '' : trim($param->CallbackParameter->id); $active = !is_numeric($param->CallbackParameter->id) ? '' : trim($param->CallbackParameter->active); $email = trim($param->CallbackParameter->email); $contactNo = trim($param->CallbackParameter->contactNo); $billingCompanyName = trim($param->CallbackParameter->billingCompanyName); $billingName = trim($param->CallbackParameter->billingName); $billingContactNo = trim($param->CallbackParameter->billingContactNo); $billingStreet = trim($param->CallbackParameter->billingStreet); $billingCity = trim($param->CallbackParameter->billingCity); $billingState = trim($param->CallbackParameter->billingState); $billingCountry = trim($param->CallbackParameter->billingCountry); $billingPostcode = trim($param->CallbackParameter->billingPosecode); $shippingCompanyName = trim($param->CallbackParameter->shippingCompanyName); $shippingName = trim($param->CallbackParameter->shippingName); $shippingContactNo = trim($param->CallbackParameter->shippingContactNo); $shippingStreet = trim($param->CallbackParameter->shippingStreet); $shippingCity = trim($param->CallbackParameter->shippingCity); $shippingState = trim($param->CallbackParameter->shippingState); $shippingCountry = trim($param->CallbackParameter->shippingCountry); $shippingPosecode = trim($param->CallbackParameter->shippingPosecode); if (is_numeric($param->CallbackParameter->id)) { $customer = Customer::get(trim($param->CallbackParameter->id)); if (!$customer instanceof Customer) { throw new Exception('Invalid Customer passed in!'); } $customer->setName($name)->setEmail($email)->setContactNo($contactNo)->setActive($active); $billingAddress = $customer->getBillingAddress(); if ($billingAddress instanceof Address) { $billingAddress->setStreet($billingStreet)->setCity($billingCity)->setRegion($billingState)->setCountry($billingCountry)->setPostCode($billingPostcode)->setContactName($billingName)->setContactNo($billingContactNo)->setCompanyName($billingCompanyName)->save(); } else { if (trim($billingStreet) !== '' || trim($billingCity) !== '' || trim($billingState) !== '' || trim($billingCountry) !== '' || trim($billingPostcode) !== '' || trim($billingName) !== '' || trim($billingContactNo) !== '' || trim($billingCompanyName) !== '') { $customer->setBillingAddress(Address::create($billingStreet, $billingCity, $billingState, $billingCountry, $billingPostcode, $billingName, $billingContactNo, $billingCompanyName)); } } $shippingAddress = $customer->getShippingAddress(); if ($shippingAddress instanceof Address && $billingAddress instanceof Address && $shippingAddress->getId() !== $billingAddress->getId()) { $shippingAddress->setStreet($shippingStreet)->setCity($shippingCity)->setRegion($shippingState)->setCountry($shippingCountry)->setPostCode($shippingPosecode)->setContactName($shippingName)->setContactNo($shippingContactNo)->setCompanyName($shippingCompanyName)->save(); } else { if (trim($shippingStreet) !== '' || trim($shippingCity) !== '' || trim($shippingState) !== '' || trim($shippingCountry) !== '' || trim($shippingPosecode) !== '' || trim($shippingName) !== '' || trim($shippingContactNo) !== '' || trim($shippingCompanyName) !== '') { $customer->setShippingAddress(Address::create($shippingStreet, $shippingCity, $shippingState, $shippingCountry, $shippingPosecode, $shippingName, $shippingContactNo, $shippingCompanyName)); } } $customer->save(); } else { if (trim($billingStreet) === '' && trim($billingCity) === '' && trim($billingState) === '' && trim($billingCountry) === '' && trim($billingPostcode) === '' && trim($billingName) === '' && trim($billingContactNo) === '' && trim($billingCompanyName) === '') { $billingAdressFull = null; } else { $billingAdressFull = Address::create($billingStreet, $billingCity, $billingState, $billingCountry, $billingPostcode, $billingName, $billingContactNo, $billingCompanyName); } if (trim($shippingStreet) === '' && trim($shippingCity) === '' && trim($shippingState) === '' && trim($shippingCountry) === '' && trim($shippingPosecode) === '' && trim($shippingName) === '' && trim($shippingContactNo) === '' && trim($shippingCompanyName) === '') { $shippingAdressFull = null; } else { $shippingAdressFull = Address::create($shippingStreet, $shippingCity, $shippingState, $shippingCountry, $shippingPosecode, $shippingName, $shippingContactNo, $shippingCompanyName); } $customer = Customer::create($name, $contactNo, $email, $billingAdressFull, false, '', $shippingAdressFull); if (!$customer instanceof Customer) { throw new Exception('Error creating customer!'); } } $results['url'] = '/customer/' . $customer->getId() . '.html'; $results['item'] = $customer->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage() . $ex->getTraceAsString(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }