示例#1
0
 public function balance($marketId, $presenterId, $userId)
 {
     $result = $this->query("Select sum(amount) as balance\r\n\t\t\t\tfrom " . $this->useTable . " as ProductCredit\r\n\t\t\t\twhere user_id = " . (int) $userId . "\r\n\t\t\t\tand product_credit_status_type_id in(" . self::STATUS_AUTHORIZED . "," . self::STATUS_SETTLED . ")\r\n\t\t\t\tand market_id = " . (int) $marketId, false);
     $balance = Money::fromString($result[0][0]['balance']);
     syslog(LOG_DEBUG, "Balance\tLedger {$marketId} {$presenterId}\t{$userId}\t{$balance}");
     return $balance;
 }
 /**
  * Get Totals for order with previous/current month totals
  * @param $Model
  * @return array
  */
 public function partyOrderTotals($Model)
 {
     /**
      * Fields
      */
     if ($Model->hostess_market_id == Market::MARKET_UNITED_KINGDOM) {
         $fields = array('sum(Order.market_commissionable) as total, sum(Order.point_total) as points');
     } else {
         $fields = array('sum(Order.presenter_commissionable) as total, sum(Order.point_total) as points');
     }
     /**
      * Order status conditions
      */
     $status = array(Order::STATUS_ENTERED, Order::STATUS_PRINTED, Order::STATUS_SHIPPED, Order::STATUS_PROCESSING);
     /**
      * Order Total points
      */
     $total = $Model->Order->find('first', array('fields' => $fields, 'conditions' => array('Order.party_id' => $Model->id, "Order.order_status_id" => $status)));
     /**
      * Order Double points
      */
     $prev_total = $Model->Order->find('first', array('fields' => $fields, 'conditions' => array('Order.party_id' => $Model->id, 'MONTH(Order.date_completed)' => 2, "Order.order_status_id" => $status)));
     $points = (int) $total['0']['points'];
     $double_points = (int) $prev_total['0']['points'];
     /**
      * Returns array with previous month and current month points
      */
     return array("total" => Money::fromString($total['0']['total']), "points" => $points, "double_points" => $double_points, "regular_points" => $points - $double_points);
 }
 public function main()
 {
     $db = ConnectionManager::getDataSource('default');
     $result = $db->query("Select date_sub(now(), interval 2 second) as timestamp");
     $twoSecondsAgo = $result[0][0]["timestamp"];
     $since = $this->SystemSetting->getSystemSetting("commission_load", "0000-00-00");
     $newPresenters = $this->Presenter->findChanges($twoSecondsAgo, $since);
     foreach ($newPresenters as $presenter) {
         $eligibleRaceToStart = $presenter['Presenter']['default_locale'] == 'es_US';
         if ($eligibleRaceToStart) {
             $result = $this->AdminUserAudit->query("Select count(*) as changes\r\n                    from admin_user_audits\r\n                    Where reference_id = " . (int) $presenter['Presenter']['id'] . " and reference_name = 'presenters.default_locale' and notes = 'Admin3 sponsor default locale change' ");
             if ($result[0][0]['changes'] == 0) {
                 $eligibleRaceToStart = true;
             } else {
                 $eligibleRaceToStart = false;
             }
         }
         //getTypeId requires presenter_sequence_id
         $presenterRank = $this->PresenterType->getRecognizedStatus($presenter['Presenter']['id']);
         if ($presenterRank['id'] >= 8) {
             //To get on the Wall of Influence in USD, earn 83333.33 in one month. Alter for other markets
             $goalForWall = $this->Market->getPayPegRate($presenter['Presenter']['market_id']) * 83333.33;
             $wallInfluence = $this->RoyaltiesEarned->isWallInfluence($presenter['Presenter']['id'], $goalForWall);
         } else {
             $wallInfluence = false;
         }
         $result = CommissionAPI::write("presenter/" . $presenter['Presenter']['id'], array("parentId" => $presenter['Presenter']['id'] == 1 ? 0 : $presenter['Presenter']['sponsor_id'], "date" => date("c", strtotime($presenter['Presenter']['consent_to_agreements'])), "name" => $presenter['User']['first_name'] . " " . $presenter['User']['last_name'], "presenter_id" => $presenter['Presenter']['presenter_sequence_id'], "image" => $presenter['User']['largeimage'], "terminated_date" => $presenter['Presenter']['terminated_date'], "timestamp" => date("c", strtotime($presenter['Presenter']['_auditdate'])), "cat1" => $eligibleRaceToStart ? $presenter['Presenter']['default_locale'] : '', "wallInfluence" => $wallInfluence));
     }
     $newOrders = $this->Order->findChanges($twoSecondsAgo, $since);
     foreach ($newOrders as $order) {
         $presenterId = $order['Order']['presenter_id'];
         if ($presenterId == 0) {
             continue;
         }
         $status = "rejected";
         //if(in_array($order['Order']['order_status_id'], array(3,4,5,8))) { MIKEFIX
         if ($this->Order->isCommissionable($order['Order']['order_status_id'])) {
             $status = "accepted";
         }
         $result = CommissionAPI::write("order/" . $order['Order']['id'], array("parentId" => $presenterId, "state" => $status, "date" => date("c", strtotime($order['Order']['date_completed'])), "retail" => Money::fromString($order['Order']['commissionable_total'])->intVal(), "wholesale" => Money::fromString($order['Order']['commissionable_total'])->times(0.75)->intVal(), "timestamp" => date("c", strtotime($order['Order']['_auditdate']))));
     }
     $this->SystemSetting->saveSetting("commission_load", $twoSecondsAgo);
     print "Done";
 }
 public function faststart()
 {
     ini_set("memory_limit", "4000M");
     $charm = new Charm();
     $this->out('Starting to run fast start accomplishment script.');
     if (empty($this->args[0])) {
         $startTime = strtotime(date("Y-m-d 00:00:00", strtotime("Yesterday")));
     } else {
         $startTime = strtotime(date("Y-m-d 00:00:00", strtotime($this->args[0])));
     }
     $endTime = strtotime(date("Y-m-d 00:00:00"));
     while ($startTime < $endTime) {
         $date = date("Y-m-d", $startTime);
         $this->out($date);
         //CHECK FAST START
         //Gotta get any presenter who signed up in last 90 days, that has 3 signups and 2000 in PRS (commissionable total)
         $presenters = $this->Presenter->listActivePresentersSince($date);
         foreach ($presenters as $presenter) {
             $this->Presenter->id = $presenter['Presenter']['id'];
             $this->User->id = $presenter['User']['id'];
             if (!$this->User->achievedFastStart()) {
                 if ($this->Presenter->signupsByDate($date) >= 3 && $this->Presenter->prsByDate($date) >= 2000) {
                     $this->out('Presenter: ' . $presenter['Presenter']['presenter_sequence_id'], 1, Shell::VERBOSE);
                     $this->Accomplishment->fastStart($presenter, date("Y-m-d 23:59:59", $startTime - 1));
                     // market touch point
                     $trait = $this->TraitCountry->getTrait($presenter['Presenter']['market_id'], 'fast_start_reward');
                     $credit_amount = !empty($trait) ? $trait : $this->TraitCountry->getTrait(1, 'fast_start_reward');
                     $this->ProductCredit->credit(ProductCredit::METHOD_SYSTEM, ProductCredit::TYPE_FASTSTART, $presenter['Presenter']['market_id'], $presenter['Presenter']['id'], $presenter['Presenter']['user_id'], Money::fromString($credit_amount), "PresenterAccomplishmentsShell:FastStart", date('Y-m-d H:i:s'));
                     $this->out('YCash added: ' . $credit_amount, 1, Shell::VERBOSE);
                     $this->hr();
                 }
             }
         }
         $startTime = strtotime("tomorrow", $startTime);
     }
     $this->out('Finished running fast start accomplishment script.');
 }
示例#5
0
 /**
  * @covers \SebastianBergmann\Money\Money::fromString
  * @uses   \SebastianBergmann\Money\Money::__construct
  * @uses   \SebastianBergmann\Money\Money::handleCurrencyArgument
  * @uses   \SebastianBergmann\Money\Currency
  */
 public function testObjectCanBeConstructedFromStringValue2()
 {
     $this->assertEquals(new Money(1234, new Currency('EUR')), Money::fromString('12.34', 'EUR'));
 }
 /**
  * Give Presenter Sla yCash
  *
  * @param $order_id
  * @param $market_id
  * @param $user_id
  * @param $presenter
  * @param $credit_amount
  * @return mixed
  */
 private function slayCash($order_id, $market_id, $user_id, $presenter, $credit_amount)
 {
     $type_id = ProductCredit::TYPE_SLAYCASH;
     $existing = $this->ProductCredit->checkExists($type_id, $user_id, $order_id);
     if (!$existing) {
         /**
          * Award yCash
          */
         $this->ProductCredit->credit(ProductCredit::METHOD_SYSTEM, $type_id, $market_id, $presenter['Presenter']['id'], $user_id, Money::fromString($credit_amount), "Late Order Shipping", $order_id);
         $market_cash = Market::numberCurrency($market_id, $credit_amount);
         /**
          * Send notifying email
          */
         $this->slayCashEmail($order_id, $market_cash, $user_id, $presenter);
         return true;
     } else {
         // Exists
         return false;
     }
 }
示例#7
0
 public function testCreateOrderLineItemsAccident()
 {
     $this->expectException("Exception", "Somehow we were about to order the wrong qty");
     $result = $this->Item->createOrderLineItems(1, 2, Money::fromString(99), Money::fromString(99), 1, Money::fromFloat(99), Money::fromString(99), Money::fromFloat(0), Money::fromString(3.2), 0, date("Y-m-d H:i:s"), array("US-1012-00" => array("US-1011-00" => array("skus" => array("US-1011-00" => 1)))));
 }
示例#8
0
 public function orderCleanup()
 {
     $this->ItemPrice = ClassRegistry::init('ItemPrice');
     $this->OrderItem = ClassRegistry::init('OrderItem');
     $this->OrderShipment = ClassRegistry::init('OrderShipment');
     $this->OrderShipmentItem = ClassRegistry::init('OrderShipmentItem');
     $this->ProductCredit = ClassRegistry::init('ProductCredit');
     $this->Snap = ClassRegistry::init('Snap');
     $this->UserNote = ClassRegistry::init('UserNote');
     $this->Order->useDbConfig = "replicated";
     $sql = "\r\nSELECT\r\n    *\r\nFROM\r\n    orders o\r\n    join order_customers oc on oc.order_id = o.id\r\n    join order_items oi on oi.order_customer_id = oc.id\r\n        and (oi.order_item_hold_code_id = 0 or oi.order_item_hold_code_id is null)\r\n    inner join order_shipments os on os.id = oi.order_shipment_id\r\n    left join addresses a on a.id = oc.address_id and address_type_id = 0\r\n    left join emails e on e.id = oc.email_id and email_type_id = 0\r\n    left join phones p on p.id = oc.phone_id and phone_type_id = 0\r\nWHERE\r\n    o.order_status_id = 3\r\n        AND o.secondary_order_status_id = 9\r\n        AND o.date_completed < DATE_SUB(NOW(), INTERVAL 12 HOUR)\r\n        group by os.id\r\n        ;\r\n            ";
     $time = microtime(true);
     $orders = $this->Order->query($sql);
     $run_time = microtime(true) - $time;
     $this->out('Time to get query data: ' . $run_time, SHELL::VERBOSE);
     $total_orders = count($orders);
     $count = 0;
     $check_count = 0;
     $this->out("Total Orders: " . $total_orders);
     $this->Order->useDbConfig = "default";
     $results = ['unshippable' => 0, 'missing_order_shipment_package' => 0, 'added_tracking' => 0, 'no_tracking' => 0, 'snap_cancelled' => 0, 'in_snap' => 0, 'order_not_in_ns' => 0, 'shipment_not_in_ns' => 0, 'shipment_in_ns' => 0, 'added_to_snap' => 0, 'added_to_snap_error' => 0, 'closed_in_ns' => 0, 'inv_skip' => 0, 'has_replacement' => 0];
     $unshippable_items = ["US-7014-00", "US-7114-00", "US-70015-00", "US-70015-02", "US-70015-01", "US-70015-03", "US-70016-01", "US-70016-02"];
     $date = new DateTime();
     $today = $date->format("Y-m-d");
     foreach ($orders as $shipment) {
         $this->Order->getDataSource()->reconnect();
         $this->OrderItem->getDataSource()->reconnect();
         $this->OrderShipment->getDataSource()->reconnect();
         $this->ItemPrice->getDataSource()->reconnect();
         $this->hr();
         $count++;
         $left = $total_orders - $count;
         $this->out("Orders left: " . $left);
         $order_details = $this->Order->loadPaymentDetails($shipment['o']['id']);
         $items = $order_details['OrderCustomer']['OrderItem'];
         $shipment_id = $shipment['os']['id'];
         $market_id = $shipment['o']['order_market_id'];
         $order_id = $shipment['o']['id'];
         $this->out("Order id: <success>" . $order_id . "</success>");
         $this->out("Shipment id: <success>" . $shipment_id . "</success>");
         $this->Order->clear();
         $this->Order->id = $order_id;
         $this->OrderShipment->clear();
         $this->OrderShipment->id = $shipment_id;
         $this->UserNote->clear();
         // check if it has a replacement against it
         $replacement_sql = "\r\n                select * from dynamic_column_data where attribute_value = {$order_id} and dynamic_column_id = 1\r\n                ";
         $replacements = $this->OrderShipment->query($replacement_sql);
         if (count($replacements) > 0) {
             //                  $this->OrderShipment->saveField("order_shipment_status_id", OrderShipment::TYPE_HAS_REPLACEMENT);
             $this->out("Has replacement");
             $cancelled = FALSE;
             foreach ($replacements as $replacement) {
                 $replacement_order_id = $replacement['dynamic_column_data']['table_key'];
                 $replacement_order_model = new Order($replacement_order_id);
                 $replacement_order = $replacement_order_model->loadDisplayDetails();
                 if (count($order_details['OrderCustomer']['OrderItem']) == count($replacement_order['OrderCustomer']['OrderItem'])) {
                     $this->Order->updateOrderStatus($order_id, Order::STATUS_SHIPPED);
                     $this->OrderShipment->saveField("order_shipment_status_id", OrderShipmentStatus::CANCELLED);
                     $this->UserNote->save(['user_id' => 1, 'note' => "Shipment cancelled due to replacement {$today}", 'reference_type' => 'order', 'reference_id' => $order_id, 'user_note_status' => 'normal', 'admin_user_id' => 584]);
                     $this->out("Note added");
                     $cancelled = TRUE;
                 }
             }
             if ($cancelled) {
                 continue;
             }
             $results['has_replacement']++;
         }
         // check if it's a shippable shipment
         $has_shippable_item = FALSE;
         foreach ($items as $item) {
             if (!in_array($item['Item']['sku'], $unshippable_items)) {
                 $has_shippable_item = TRUE;
                 break;
             }
         }
         if ($has_shippable_item === FALSE) {
             $this->Order->saveField("order_status_id", OrderStatus::STATUS_SHIPPED);
             $this->OrderShipment->saveField("order_shipment_status_id", OrderShipmentStatus::UN_SHIPPABLE);
             $this->out("Unshippable");
             $results['unshippable']++;
             continue;
         }
         //check for refund
         $amt = 0;
         $pmt_count = 0;
         $has_refund = FALSE;
         foreach ($order_details['OrderPayment'] as $payment) {
             if ($payment['order_payment_type_id'] == OrderPayment::TYPE_REFUND) {
                 $has_refund = TRUE;
             }
             $pmt_count++;
             $amt += $payment['amount'];
         }
         if ($amt == 0 && $pmt_count > 1 && $has_refund) {
             $this->Order->updateOrderStatus($order_id, Order::STATUS_REFUNDED);
             $this->OrderShipment->saveField("order_shipment_status_id", OrderShipmentStatus::CANCELLED);
             $this->UserNote->save(['user_id' => 1, 'note' => "Shipment cancelled due to refund {$today}", 'reference_type' => 'order', 'reference_id' => $order_id, 'user_note_status' => 'normal', 'admin_user_id' => 584]);
             $this->out("Note added");
         }
         // check snap for completed data
         try {
             $wh_id = (int) WarehouseUtil::idByMarket($market_id);
             $snap_shipment = SnapFulfilAPI::call("shipments/{$shipment_id}", NULL, FALSE, $wh_id);
             $this->Order->updateOrderStatus($order_id, Order::STATUS_PROCESSING);
             $this->Order->updateSecondaryStatus($order_id, Order::SECONDARY_NETSUITE_SENT);
             if ($snap_shipment->Stage == '39' || $snap_shipment->Stage == '90') {
                 if ($snap_shipment->CarrierTrackingNumber && $snap_shipment->ShippingMethod) {
                     $tracking_url = $this->OrderShipment->getTrackingLink($snap_shipment->CarrierTrackingNumber, $snap_shipment->ShippingMethod);
                     $this->OrderShipment->saveField('order_shipment_status_id', NULL);
                     $this->OrderShipment->saveField('date_shipped', $snap_shipment->DateClosed);
                     $this->OrderShipment->saveField('tracking_number', $snap_shipment->CarrierTrackingNumber);
                     $this->OrderShipment->saveField('carrier', $snap_shipment->ShippingMethod);
                     $this->out("Order Shipment updated");
                     $this->Order->updateOrderStatus($order_id, Order::STATUS_SHIPPED);
                     $this->Order->updateSecondaryStatus($order_id, NULL);
                     $email_data = array("name" => $snap_shipment->CustomerName, "order_id" => $snap_shipment->CustomerRef, "tracking_number" => $snap_shipment->CarrierTrackingNumber, "tracking_url" => $tracking_url, "country_id" => $snap_shipment->ShipAddress[0]->Country);
                     $this->User = ClassRegistry::init('User');
                     $userLocale = $this->User->userLocale($shipment['o']['user_id']);
                     $usable_userLocale = empty($userLocale['User']['locale']) ? 'en_US' : $userLocale['User']['locale'];
                     YouniqueEmail::queueEmail($email_data, 'en_us_tracking_numbers', $shipment['e']['email_address'], 'email order tracking', 'purchase-page', $usable_userLocale);
                     $this->out("Tracking email sent: " . $snap_shipment->CarrierTrackingNumber);
                     $results['added_tracking']++;
                     continue;
                 } else {
                     // shipment is in snap but not yet fulfilled
                     $results['no_tracking']++;
                     $this->out("In Snap but No tracking number");
                     $this->OrderShipment->saveField("order_shipment_status_id", OrderShipmentStatus::PROCESSING);
                 }
             } elseif ($snap_shipment->Stage == '91') {
                 $results['snap_cancelled']++;
                 $this->out("Shipment cancelled in snap ");
                 //                      $this->OrderShipment->saveField("order_shipment_status_id", OrderShipmentStatus::CANCELLED);
             } else {
                 $results['in_snap']++;
                 $this->OrderShipment->saveField("order_shipment_status_id", OrderShipmentStatus::PROCESSING);
                 $this->out("Found in Snap but it's not fulfilled. Stage: " . $snap_shipment->Stage);
             }
         } catch (Exception $e) {
             $this->out("Not in Snap.");
             try {
                 $sql = "\r\nSELECT\r\n    *\r\nFROM\r\n    order_shipments os\r\n        JOIN\r\n    orders o ON o.id = os.order_id\r\n        JOIN\r\n    order_customers oc ON oc.order_id = o.id\r\n        JOIN\r\n    order_items oi ON oi.order_customer_id = oc.id\r\n         JOIN\r\n    addresses a ON a.id = oc.address_id AND a.address_type_id = 0\r\n       JOIN\r\n    items i ON i.id = oi.item_id\r\n        LEFT JOIN\r\n    states s ON s.id = a.state_id\r\n        LEFT JOIN\r\n    countries c ON c.id = a.country_id\r\nWHERE\r\n    os.id = {$shipment_id};\r\n                                ";
                 $order_items = $this->Order->query($sql);
                 $results['shipment_not_in_ns']++;
                 //                      $this->out("Shipment <error>NOT</error> in NetSuite: " . $shipment_id);
                 // check for cancel
                 $items = [];
                 // loop through all items and prepare the shipment
                 $first_sku = "";
                 $prekit_items = [];
                 foreach ($order_items as $key => $order_item) {
                     if (in_array($order_item['i']['sku'], $this->Snap->prekit)) {
                         $prekit_items[] = $order_item['oi']['id'];
                     }
                 }
                 foreach ($order_items as $order_item) {
                     if ($first_sku == '') {
                         $first_sku = $order_item['i']['sku'];
                     }
                     $status = $order_item['oi']['order_item_hold_code_id'];
                     if ($status != OrderItemHoldCode::NONE && $status != NULL) {
                         $this->out("<warning>Item not shippable: {$order_item['oi']['id']}</warning>");
                     } else {
                         $price = $order_item['oi']['price'] * $order_item['osi']['qty'];
                         if ($price <= 1) {
                             $item_id = $order_item['i']['id'];
                             $order_date = $order_details['Order']['date_completed'];
                             $item_price = $this->ItemPrice->getPrice($item_id, $market_id, $order_date);
                             $price = $item_price;
                         }
                         $price = $price > 0 ? $price : 1;
                         $sku = $order_item['i']['sku'];
                         $parent_id = $order_item['oi']['parent_id'];
                         // prekit
                         if (in_array($parent_id, $prekit_items)) {
                             continue;
                         }
                         // noscan
                         if (in_array($sku, $this->Snap->noscan)) {
                             continue;
                         }
                         // remap
                         if (array_key_exists($sku, $this->Snap->remapSkus)) {
                             $sku = $this->Snap->remapSkus[$sku];
                         }
                         if ($order_item['oi']['quantity'] < 1) {
                             continue;
                         }
                         $items[] = ["ShipmentId" => $shipment_id, "SKUId" => $sku, "UnitOfMeasure" => "EA", "QtyOrdered" => $order_item['oi']['quantity'], "Stage" => "00", "Price" => $price];
                     }
                 }
                 if (empty($items)) {
                     $this->out("<warning>No items</warning>");
                     continue;
                 }
                 switch ($shipment['o']['order_market_id']) {
                     case Market::MARKET_USA:
                         $shippingMethod = 'ALL';
                         break;
                     case Market::MARKET_MEXICO:
                         $shippingMethod = 'EF02';
                         break;
                     default:
                         $shippingMethod = 'INTL';
                         break;
                 }
                 $date = date('c', strtotime($shipment['o']['date_completed']));
                 $param = ['Order' => $order_details];
                 $shipment_class = $this->Order->findShipmentClass($param);
                 $result = ["ShipmentId" => $shipment_id, "ShippingMethod" => $shippingMethod, "CarrierId" => "RATELINX", "DateDueOut" => $date, "Stage" => "00", "CustomerId" => $shipment['o']['user_id'], "CustomerName" => $this->_scrub($shipment['oc']['first_name']) . " " . $this->_scrub($shipment['oc']['last_name']), "CustomerRef" => $order_id, "OrderClass" => $shipment_class, "Status" => "00", "PriorityDespatch" => "02", "Region" => $first_sku, "ShipAddress" => [["Table" => "SHH", "ShipmentId" => $shipment_id, "AddressId" => "ADD1", "Name" => $this->_scrub($shipment['oc']['first_name']) . " " . $this->_scrub($shipment['oc']['last_name']), "Line1" => $this->_scrub($shipment['a']['address1']), "Line2" => $this->_scrub($shipment['a']['address2']), "Line3" => $this->_scrub($shipment['a']['address3']), "City" => $this->_scrub($shipment['a']['city']), "State" => $order_items[0]['s']['abbrev'], "Postcode" => $shipment['a']['postal_code'], "Country" => $order_items[0]['c']['country_code']]], "ShipContacts" => [["Phone" => empty($shipment['p']['phone']) ? "N/A" : $this->_scrub($shipment['p']['phone']), "ShipmentId" => $shipment_id, "LineId" => 0]], "ShipmentLines" => $items];
                 if ($check_count <= 5) {
                     $continue = $this->in("Continue to send shipment to Snap?", ['y', 'n'], 'y');
                     if ($continue == 'n') {
                         continue;
                     }
                     $check_count++;
                 }
                 try {
                     $response = SnapFulfilAPI::call("shipments", $result, FALSE, $wh_id);
                     $results['added_to_snap']++;
                     $this->out("<info>Shipment added to Snap</info>");
                     $this->Order->updateOrderStatus($order_id, Order::STATUS_PROCESSING);
                     $this->Order->updateSecondaryStatus($order_id, Order::SECONDARY_NETSUITE_SENT);
                     $this->OrderShipment->saveField("order_shipment_status_id", OrderShipmentStatus::PROCESSING);
                     // refund item value in ycash
                     $ycash_amt = 10;
                     $this->ProductCredit->credit(ProductCredit::METHOD_SYSTEM, ProductCredit::TYPE_CONCESSION, $shipment['o']['order_market_id'], $shipment['o']['presenter_id'], $shipment['o']['user_id'], Money::fromString($ycash_amt), "shipping concession:missing orders {$today}", date('Y-m-d H:i:s'));
                     $this->out("Ycash paid: " . $ycash_amt);
                     $this->UserNote->save(['user_id' => 1, 'note' => "Missing order added to Snap. Ycash added {$ycash_amt} ", 'reference_type' => 'order', 'reference_id' => $order_id, 'user_note_status' => 'normal', 'admin_user_id' => 584]);
                     $this->out("Note aded");
                 } catch (Exception $d) {
                     $this->out("<error>Snap fail: {$d->getMessage()}</error>");
                     $this->OrderShipment->saveField("order_shipment_status_id", OrderShipmentStatus::WMS_ERROR);
                     $results['added_to_snap_error']++;
                 }
                 //                      }
             } catch (Exception $e) {
                 $this->out("<error>Netsuite fail: {$e->getMessage()}</error>", 1, Shell::VERBOSE);
             }
         }
     }
     $this->out("Done");
 }
 /**
  * Execute Promotion Awards for 2016 rules
  *
  * @return bool
  */
 public function execute()
 {
     $promotion_id = 3;
     $winners = $this->PresenterPromotionPoints->find('all', ['fields' => ['presenter_id', 'SUM(value) as point_total'], 'conditions' => ['promotion_id' => $promotion_id], 'group' => "presenter_id having SUM(value) >= 10000", 'order' => "SUM(value) desc"]);
     foreach ($winners as $presenter) {
         $this->hr();
         $awards = [];
         $presenter_id = $presenter['PresenterPromotionPoints']['presenter_id'];
         $points = $presenter[0]['point_total'];
         $this->Presenter->clear();
         $this->Presenter->id = $presenter_id;
         $awarded = $this->PresenterPromotionAward->find('all', ['conditions' => ['promotion_id' => $promotion_id, 'presenter_id' => $presenter_id]]);
         foreach ($awarded as $award) {
             $awards[] = $award['PresenterPromotionAward']['award'];
         }
         unset($award);
         $presenter = $this->Presenter->loadBasicDetails();
         $presenter_market_id = $presenter['Presenter']['market_id'];
         $presenter_user_id = $presenter['Presenter']['user_id'];
         $presenter_display = $presenter['User']['first_name'] . " " . $presenter['User']['last_name'] . " " . $presenter['Presenter']['presenter_sequence_id'];
         $date = new DateTime();
         $date_display = $date->format('Y-m');
         $this->out("<info>Presenter {$presenter_display} ({$presenter_id}) - Points: {$points}</info>");
         // get trunk
         if (!in_array('level3', $awards)) {
             if ($points >= 20000) {
                 $level_name = "Level3";
                 $level = "level3";
                 $this->out("-- Adding award for {$level_name}");
                 $sku = "US-61006-01";
                 $order_type = Order::TYPE_PRODUCT;
                 $ship_to = ["first_name" => $presenter['User']['first_name'], "last_name" => $presenter['User']['last_name'], "address1" => $presenter['User']['ShippingAddress']['address1'], "address2" => $presenter['User']['ShippingAddress']['address2'], "address3" => $presenter['User']['ShippingAddress']['address3'], "city" => $presenter['User']['ShippingAddress']['city'], "state_id" => $presenter['User']['ShippingAddress']['state_id'], "postal_code" => $presenter['User']['ShippingAddress']['postal_code'], "country_id" => $presenter['User']['ShippingAddress']['country_id'], "email_address" => $presenter['email']['email']];
                 $qty = 1;
                 $items = [['qty' => $qty, 'sku' => $sku]];
                 $this->Order->clear();
                 $this->Order->createOrder(0, $presenter_id, $presenter['Presenter']['user_id'], 0, $items, $ship_to, $order_type, NULL, [], TRUE, TRUE, FALSE, WarehouseUtil::idByMarket($presenter['Presenter']['market_id']));
                 $this->Order->finalize(array('success' => TRUE, 'payments' => []));
                 $new_order_id = $this->Order->id;
                 $this->out("Trunk Order Id: " . $new_order_id);
                 $new_order_id = $this->Order->id;
                 // Set Shipment Method
                 $this->Order->queueOrder();
                 $this->PresenterPromotionAward->create(['presenter_id' => $presenter_id, 'award' => $level, 'promotion_id' => $promotion_id]);
                 $this->PresenterPromotionAward->save();
                 $this->UserNote->clear();
                 $this->UserNote->save(['user_id' => $presenter_user_id, 'note' => "Trunk order placed for Incentive Trip {$level_name} Award", 'reference_type' => '', 'reference_id' => '', 'user_note_status' => 'normal', 'admin_user_id' => 584]);
                 $this->out("Added trunk order({$new_order_id}) for Incentive Trip {$level_name} Award");
             }
         } else {
             $this->out("<warning>Already got award for Level3</warning>");
         }
         // get 75$ ycash
         if (!in_array('level2', $awards)) {
             if ($points >= 15000) {
                 $level_name = "Level2";
                 $level = "level2";
                 $this->out("-- Adding award for {$level_name}");
                 $ycash = [1 => 75, 2 => 82.5, 3 => 86.25, 4 => 104.25, 5 => 48.75, 6 => 975, 7 => 63.75, 8 => 63.75, 9 => 63.75];
                 $amount = $ycash[$presenter_market_id];
                 $this->ProductCredit->credit(ProductCredit::METHOD_SYSTEM, ProductCredit::TYPE_CONCESSION, $presenter_market_id, $presenter_id, $presenter_user_id, Money::fromString($ycash[$presenter_market_id]), "Incentive Trip {$level_name} Award {$date_display}", 0);
                 $this->out("{$level_name} Ycash paid: {$amount} to Presenter: {$presenter_display}");
                 $this->PresenterPromotionAward->create(['presenter_id' => $presenter_id, 'award' => $level, 'promotion_id' => $promotion_id]);
                 $this->PresenterPromotionAward->save();
                 //add user note
                 $this->UserNote->clear();
                 $this->UserNote->save(['user_id' => $presenter_user_id, 'note' => "Ycash ({$amount}) added for Incentive Trip {$level_name} Award", 'reference_type' => '', 'reference_id' => '', 'user_note_status' => 'normal', 'admin_user_id' => 584]);
             }
         } else {
             $this->out("<warning>Already got award for Level2</warning>");
         }
         // get 25$ ycash
         if (!in_array('level1', $awards)) {
             if ($points >= 10000) {
                 $level_name = "Level1";
                 $level = "level1";
                 $this->out("-- Adding award for {$level_name}");
                 $ycash = [1 => 25, 2 => 27.5, 3 => 28.75, 4 => 34.75, 5 => 16.25, 6 => 325, 7 => 21.25, 8 => 21.25, 9 => 21.25];
                 $amount = $ycash[$presenter_market_id];
                 $this->ProductCredit->credit(ProductCredit::METHOD_SYSTEM, ProductCredit::TYPE_CONCESSION, $presenter_market_id, $presenter_id, $presenter_user_id, Money::fromString($ycash[$presenter_market_id]), "Incentive Trip {$level_name} Award {$date_display}", 0);
                 $this->out("{$level_name} Ycash paid: {$amount} to Presenter: {$presenter_display}");
                 $this->PresenterPromotionAward->create(['presenter_id' => $presenter_id, 'award' => $level, 'promotion_id' => $promotion_id]);
                 $this->PresenterPromotionAward->save();
                 //add user note
                 $this->UserNote->clear();
                 $this->UserNote->save(['user_id' => $presenter_user_id, 'note' => "Ycash ({$amount}) added for Incentive Trip {$level_name} Award", 'reference_type' => '', 'reference_id' => '', 'user_note_status' => 'normal', 'admin_user_id' => 584]);
             }
         } else {
             $this->out("<warning>Already got award for Level1</warning>");
         }
     }
 }
示例#10
0
 /**
  * Gets a list of customers for a presenter that have ordered in a specific month
  *
  * @param $date YYYY-mm-dd HH:ii:ss format
  * @return array
  */
 public function listUsers($date)
 {
     $users = $this->Order->find("all", array("contain" => array("User" => array("fields" => array("first_name", "last_name", "facebook_id", "largeimage", "count(Order.id) as ordercount", "sum(Order.grand_total) as grandtotal", "max(Order.date_completed) as last_order_date"), "Email" => array("fields" => array("email")))), "conditions" => array("Order.presenter_id" => $this->id, "Order.order_status_id >=" => Order::STATUS_ENTERED, "Order.date_completed >= " => date('Y-m-01 00:00:00', strtotime($date)), "Order.date_completed <= " => date('Y-m-t 23:59:59', strtotime($date))), "group" => "Order.user_id"));
     $finalUsers = array();
     foreach ($users as $user) {
         $finalUsers[] = array("id" => $user['User']['id'], "first_name" => $user['User']['first_name'], "last_name" => $user['User']['last_name'], "name" => $user['User']['first_name'] . " " . $user['User']['last_name'], "facebook_id" => $user['User']['facebook_id'], "largeimage" => $user['User']['largeimage'], "email" => !empty($user['User']['Email']) ? $user['User']['Email']['email'] : '', "ordercount" => $user[0]['ordercount'], "grandtotal" => Money::fromString($user[0]['grandtotal']), "last_order_date" => $user[0]['last_order_date']);
     }
     return $finalUsers;
 }
示例#11
0
 public function finalize($partyId = null)
 {
     if (!empty($partyId)) {
         $this->id = $partyId;
     }
     //Going to close down the party, you don't have to go home,
     $this->User = new User();
     $this->Country = new Country();
     $fields = $this->read(array("presenter_id", 'hostess_id', 'finalized_date', 'start_time', 'party_status_id'));
     $hostess = $this->User->find('first', array('conditions' => array('User.id' => $fields['Party']['hostess_id']), 'contain' => array('Address')));
     $party_info = $this->find('first', array('fields' => array('Party.hostess_market_id'), 'conditions' => array('Party.id' => $this->id)));
     $this->Presenter->id = $fields['Party']['presenter_id'];
     if (!empty($party_info['Party']['hostess_market_id'])) {
         $this->hostess_market_id = $party_info['Party']['hostess_market_id'];
     } else {
         if (!empty($hostess) && (!is_null($hostess['Address']['country_id']) && $hostess['Address']['country_id'] > 0)) {
             $this->hostess_market_id = $this->Country->getMarketFromCountryId($hostess['Address']['country_id']);
         } else {
             $this->hostess_market_id = $this->Presenter->field("market_id");
         }
     }
     $rewards = $this->calculateRewards();
     if (!empty($rewards)) {
         if ($fields['Party']['finalized_date'] != '0000-00-00 00:00:00' && $fields['Party']['finalized_date'] != '') {
             return false;
         }
         if ($fields['Party']['party_status_id'] < 1) {
             return false;
         }
         $party = array("id" => $this->id, "party_status_id" => 3, "party_total" => (string) $rewards['Order Total'], "earned_coupons" => (string) $rewards['Half-Price Items'], "earned_free_product_credit" => (string) $rewards['Free Product Credits'], "finalized_date" => date('Y-m-d H:i:s'));
         $result = $this->save(array("Party" => $party), false);
         if (!empty($rewards['Free Product Credits']) && !empty($fields['Party']['hostess_id'])) {
             $this->ProductCredit->credit(ProductCredit::METHOD_SYSTEM, ProductCredit::TYPE_PARTYCREDIT, $this->hostess_market_id, $fields['Party']['presenter_id'], $fields['Party']['hostess_id'], Money::fromString($rewards['Free Product Credits']), "Party.php finalize", $this->id);
         }
         if (!empty($rewards['Half-Price Items']) && !empty($fields['Party']['hostess_id'])) {
             for ($i = 0; $i < (int) $rewards['Half-Price Items']; $i++) {
                 $this->CouponPresenterUser->assignCoupon($fields['Party']['presenter_id'], Coupon::HALFOFF, $fields['Party']['hostess_id'], $this->id);
             }
         }
         //Kudos Start
         if (YOUNIQUE_TESTSERVER == true) {
             $kudos_start_date = new DateTime('July 1, 2014 midnight');
         } else {
             $kudos_start_date = new DateTime('January 1, 2015 midnight');
         }
         $kudos_end_date = new DateTime('February 1, 2015 midnight');
         $party_start_date = new DateTime($fields['Party']['start_time']);
         if ($party_start_date >= $kudos_start_date && $party_start_date <= $kudos_end_date && !empty($fields['Party']['hostess_id'])) {
             if (!empty($rewards["Points Total"]) && $rewards["Points Total"] >= 5000) {
                 $this->CouponPresenterUser->forceAssignCoupon($fields['Party']['presenter_id'], Coupon::KUDOS, $fields['Party']['hostess_id'], $this->id);
             }
             if (!empty($rewards["Points Total"]) && $rewards["Points Total"] >= 10000) {
                 $this->CouponPresenterUser->forceAssignCoupon($fields['Party']['presenter_id'], Coupon::KUDOS, $fields['Party']['hostess_id'], $this->id);
                 $this->CouponPresenterUser->forceAssignCoupon($fields['Party']['presenter_id'], Coupon::KUDOS, $fields['Party']['hostess_id'], $this->id);
             }
         }
         //$kudosData = $this->Kudos->getPartyData($fields);
         //Kudos End
         return true;
     }
     return true;
 }
示例#12
0
 public function create_negative_invoice($orderId, $last_quote_date = null, $refundOrder = false, $order_items = null)
 {
     //for cancel returned or refunded items
     $itemModel = ClassRegistry::init('Item');
     if ($refundOrder && !is_null($order_items)) {
         $cancelled_order_items = $order_items;
     } else {
         $order_items = $this->OrderCustomer->OrderItem->find('all', array('fields' => array('Items.id', 'Items.sku', 'Items.name', 'OrderItem.price', 'OrderItem.quantity', 'OrderItem.tax_amount', 'OrderItem.extended_price', 'OrderItem.discount'), 'joins' => array(array('table' => 'order_customers', 'alias' => 'OrderCustomer', 'type' => 'INNER', 'conditions' => array('OrderItem.order_customer_id=OrderCustomer.id')), array('table' => 'items', 'alias' => 'Items', 'type' => 'INNER', 'conditions' => array('OrderItem.item_id=Items.id'))), 'conditions' => array('OrderCustomer.order_id' => $orderId)));
         $cancelled_order_items = array();
         foreach ($order_items as $order_item) {
             $cancelled_order_items[] = array('sku' => $order_item['Items']['sku'], 'name' => $order_item['Items']['name'], 'price' => "-" . $order_item['OrderItem']['price'], 'qty' => $order_item['OrderItem']['quantity'], 'subtotal' => "-" . $order_item['OrderItem']['extended_price'], 'originalSubtotal' => "-" . ($order_item['OrderItem']['discount'] + $order_item['OrderItem']['extended_price']), 'display_name' => $order_item['Items']['name'], 'tax_type' => $itemModel->getTaxTypeName($order_item['Items']['id']), 'tax_amount' => "-" . $order_item['OrderItem']['tax_amount']);
         }
     }
     $order_info = $this->find('first', array('contain' => ['OrderCustomer' => ['Address']], 'fields' => array('Order.id', 'Order.date_started', 'Order.order_market_id', 'Order.user_id'), 'joins' => array(array('table' => 'order_shipments', 'alias' => 'OrderShipments', 'type' => 'INNER', 'conditions' => array('OrderShipments.order_id=Order.id'))), 'conditions' => array('Order.id' => $orderId)));
     $market_info = $this->findOrderMarketInfo($order_info['Order']['order_market_id']);
     if ($order_info['Order']['order_market_id'] == MARKET::MARKET_CANADA) {
         $shippingtotal = Money::fromString($order_info['Order']['shippingtotal']);
         $subtotal = Money::fromString($order_info['Order']['subtotal']);
         $shipping = $this->getShippingTotal($shippingtotal, $subtotal);
         $market_info['shipping'] = $shipping;
     }
     $address = array('postal_code' => strtoupper($order_info['OrderCustomer']['Address']['postal_code']), 'city' => $order_info['OrderShipments']['city'], 'state' => $this->OrderShipment->State->find('all', array('fields' => array('State.name'), 'conditions' => array('State.id' => $order_info['OrderCustomer']['Address']['state_id']))));
     $user = $this->getOrderUserData($order_info['Order']['user_id']);
     $is_presenter = !is_null($user['Presenters']['id']) ? true : false;
     $order_date = new DateTime($order_info['Order']['date_started']);
     $tax_api = new TaxAPI();
     $tax_result = $tax_api->get_tax($address, $market_info, $cancelled_order_items, $refundOrder ? 'distribute' : 'cancel', $is_presenter, $user, $orderId, is_null($last_quote_date) ? $order_date->format('Y-m-d') : $last_quote_date);
     if (!isset($tax_result->taxAmount) && $tax_result->success === false) {
         $this->apiLog("order.id", $orderId, "Order->create_negative_invoice", "Vertex API", $tax_result->sent, $tax_result->received, "Vertex Response Logging", 1);
     }
 }
 /**
  * Shopping cart Purchase 
  *
  * Validates order details, creates order, processes payment
  * and queues for emails and post order process.
  * 
  */
 public function purchase()
 {
     if ($this->request->data['market_id'] == 7 || $this->request->data['market_id'] == 8 || $this->request->data['market_id'] == 9) {
         $this->request->data['state'] = null;
     }
     $this->Presenter->id = $this->data['sponsor_id'];
     if ($this->Session->check('activate_link')) {
         $this->Session->delete('activate_link');
     }
     if ($this->Session->check("user_id")) {
         $userId = $this->Session->read("user_id");
     } else {
         if (!empty($this->request->data['email'])) {
             $data = $this->User->find('first', array('conditions' => array("User.email" => $this->request->data['email']), 'order' => array('User.id DESC')));
             $userId = $data['User']['id'];
         } else {
             $userId = null;
         }
     }
     $presenter = $this->Presenter->loadBasicDetails();
     if (!empty($presenter)) {
         $promoterId = 0;
         $presenterId = $presenter['Presenter']['id'];
         if (isset($this->request->data['personal_consumption']) && $this->request->data['personal_consumption']) {
             $recargo_exempt = true;
         } else {
             $recargo_exempt = Configure::read("market_id") == Market::MARKET_SPAIN ? $this->checkRecargoTaxStatus($this->request->data, $presenter['Presenter']['user_id'], $userId) : true;
         }
     } else {
         $promoterId = 0;
         $presenterId = 0;
         $recargo_exempt = true;
     }
     $validation_errors = array();
     $vertex_success = $this->data['vertex_success'];
     if ($this->data['processor'] == OrderPaymentProcessor::PROCESSOR_CYBERSOURCE) {
         if (!strlen($this->data['billingCardholderFirstName']) || !strlen($this->data['billingCardholderLastName'])) {
             $validation_errors['cardHolder'] = array(DruniqueAPIUtil::content('name required', $this->DruniqueAPI->page_data));
         }
         $credit_card_number = $this->data['cardNum'];
         if (!strlen($this->data['cardNum'])) {
             $validation_errors['cardNum'] = array(DruniqueAPIUtil::content('credit card required', $this->DruniqueAPI->page_data));
         } else {
             $credit_card_number = preg_replace('/\\D/', '', $credit_card_number);
             if (!preg_match('/\\d{13,16}/', $credit_card_number) || !$this->luhn_check($credit_card_number)) {
                 $validation_errors['cardNum'] = array(DruniqueAPIUtil::content('credit card invalid', $this->DruniqueAPI->page_data));
             }
         }
         $credit_card_code = preg_replace('/\\D/', '', $this->data['cardCode']);
         if (!strlen($credit_card_code) || strlen($credit_card_code) < 3 || strlen($credit_card_code) > 4) {
             $validation_errors['cardCode'] = array(DruniqueAPIUtil::content('card code invalid', $this->DruniqueAPI->page_data));
         }
         if (!strlen($this->data['cardExpMonth']) || !strlen($this->data['cardExpYear'])) {
             $validation_errors['cardExpYear'] = array(DruniqueAPIUtil::content('expiration date required', $this->DruniqueAPI->page_data));
         }
         switch ($this->data['sameAsShipping']) {
             case "on":
                 if (!strlen($this->data['postal_code'])) {
                     $validation_errors['postal_code'] = array(DruniqueAPIUtil::content('billing postal code required', $this->DruniqueAPI->page_data));
                 }
                 break;
             default:
                 //check for not empty
                 if (!strlen($this->data['billingState']) && $this->data['billing_market_id'] != Market::MARKET_UNITED_KINGDOM) {
                     $validation_errors['billingState'] = array(DruniqueAPIUtil::content('billing state required', $this->DruniqueAPI->page_data));
                 }
                 if (!strlen($this->data['billingZip'])) {
                     $validation_errors['billingZip'] = array(DruniqueAPIUtil::content('billing postal code required', $this->DruniqueAPI->page_data));
                 }
                 if (!strlen($this->data['billingEmail'])) {
                     $validation_errors['billingEmail'] = array(DruniqueAPIUtil::content('billing email required', $this->DruniqueAPI->page_data));
                 }
                 if (!strlen($this->data['billingAddress1'])) {
                     $validation_errors['billingAddress1'] = array(DruniqueAPIUtil::content('billing address required', $this->DruniqueAPI->page_data));
                 }
                 $this->Email->set('email', $this->data['billingEmail']);
                 if (!$this->Email->validates(array('fieldList' => array('email')))) {
                     $validation_errors['billingEmail'] = array(DruniqueAPIUtil::content('valid billing email address', $this->DruniqueAPI->page_data));
                 }
                 break;
         }
         if (!empty($this->request->data['cardExpMonth'])) {
             $this->request->data['cardExp'] = $this->request->data['cardExpMonth'] . "/" . $this->request->data['cardExpYear'];
         }
         if (!empty($validation_errors)) {
             $this->sendError(500, $validation_errors);
             return;
         }
     }
     if (empty($presenterId)) {
         $this->sendError(500, array("process_error" => array(DruniqueAPIUtil::content('presenter for purchase', $this->DruniqueAPI->page_data))));
         return;
     }
     /**
      * Return error when cart is empty
      */
     if (empty($this->request->data['items'])) {
         $this->sendError(500, ['process_error' => [DruniqueAPIUtil::content('no items in cart', $this->DruniqueAPI->page_data)]]);
         return;
     }
     $itemIds = $this->request->data['items'];
     $party = $this->Party->partyFromId($this->data['party_id'], $presenterId, true);
     if (!empty($party)) {
         $partyId = $party['Party']['id'];
     } else {
         $partyId = 0;
     }
     /**
      * @var Money
      */
     $productCredits = null;
     if (!empty($this->request->data['productcredits'])) {
         $productCredits = Money::fromPennies((int) $this->request->data['productcredits']);
     }
     $commission_total = null;
     //determine if user is a presenter
     $is_presenter = $this->Presenter->presenterFromUserId($userId);
     if (!empty($is_presenter)) {
         $commission_total = $this->request->data['commissionable_total'];
     }
     $country = $this->Country->getByMarketId(Configure::read("market_id"));
     if (!empty($this->request->data['state'])) {
         $state_id = (int) $this->Address->State->search($this->request->data['state']);
     } else {
         $state_id = null;
     }
     $first_last = array();
     if (empty($this->request->data['first_name'])) {
         $first_last['first_name'][0] = array(DruniqueAPIUtil::content('valid First Name', $this->DruniqueAPI->page_data));
     }
     if (Configure::read("market_id") != Market::MARKET_MEXICO) {
         if (empty($this->request->data['last_name'])) {
             $first_last['last_name'][0] = array(DruniqueAPIUtil::content('valid Last Name', $this->DruniqueAPI->page_data));
         }
     }
     @($address = array("first_name" => $this->request->data['first_name'], "last_name" => $this->request->data['last_name'], "address1" => $this->request->data['address1'], "address2" => $this->request->data['address2'], "address3" => $this->request->data['address3'], "city" => $this->request->data['city'], "state_id" => $state_id, "state" => $this->request->data['state'], "country_id" => $country['Country']['id'], "postal_code" => strtoupper($this->request->data['postal_code']), "phone" => $this->request->data['phone']));
     $email = ['email' => trim($this->request->data['email'])];
     $hasDailySpecial = false;
     $hasConventionTicket = false;
     $this->Address->set($address);
     $this->Email->set($email);
     /**
      * Currently us market does not require phone number
      */
     if (Configure::read("market_id") != Market::MARKET_USA) {
         $this->Phone->set(['phone' => $this->request->data['phone']]);
         $phone_validation = true;
         //$this->Phone->validates();
     } else {
         $phone_validation = true;
     }
     if (!$this->Address->validates() || !$this->Email->validates() || !$phone_validation || !empty($first_last)) {
         $address_error = $this->Address->validationErrors;
         foreach ($address_error as $key => $error_details) {
             if ($key == 'first_name') {
                 $address_error[$key][0] = DruniqueAPIUtil::content('valid First Name', $this->DruniqueAPI->page_data);
             } elseif ($key == 'last_name') {
                 $address_error[$key][0] = DruniqueAPIUtil::content('valid Last Name', $this->DruniqueAPI->page_data);
             } elseif ($key == 'address1') {
                 $address_error[$key][0] = DruniqueAPIUtil::content('valid Address', $this->DruniqueAPI->page_data);
             } elseif ($key == 'city') {
                 $address_error[$key][0] = DruniqueAPIUtil::content('valid City', $this->DruniqueAPI->page_data);
             } elseif ($key == 'country_id') {
                 $address_error[$key][0] = DruniqueAPIUtil::content('Check your Country', $this->DruniqueAPI->page_data);
             } elseif ($key == 'postal_code') {
                 $address_error[$key][0] = DruniqueAPIUtil::content('valid Postal Code', $this->DruniqueAPI->page_data);
             } elseif ($key == 'state_id') {
                 $address_error[$key][0] = DruniqueAPIUtil::content('Check your State', $this->DruniqueAPI->page_data);
             }
         }
         if (!$this->Email->validates()) {
             $email_validation_errors = $this->Email->validationErrors;
             foreach ($email_validation_errors as $key => $error_details) {
                 if ($key == 'email_address') {
                     $email_validation_errors[$key][0] = DruniqueAPIUtil::content('valid email address', $this->DruniqueAPI->page_data);
                 }
             }
         }
         if (Configure::read("market_id") != Market::MARKET_USA) {
             $phone_error = $this->Phone->validationErrors;
             foreach ($phone_error as $key => $error_details) {
                 if ($key == 'phone') {
                     $phone_error[$key][0] = DruniqueAPIUtil::content('valid phone number', $this->DruniqueAPI->page_data);
                 }
             }
         } else {
             $phone_error = [];
         }
         $this->sendError(500, array_merge($address_error, $email_validation_errors, $phone_error, $first_last));
         return;
     } else {
         $address['email_address'] = $email['email'];
         foreach ($itemIds as &$item) {
             if (strpos($item['sku'], "US-3001-") === 0) {
                 $hasDailySpecial = true;
             }
             if (empty($item['coupons'])) {
                 continue;
             }
             $couponIds = $item['coupons'];
             unset($item['coupons']);
             $coupons = $this->User->CouponPresenterUser->availableCouponsById($presenterId, $userId, $couponIds);
             foreach ($coupons as $coupon) {
                 $item['coupons'][$coupon['id']] = array("discount_percentage" => $coupon['discount_percentage'], "discount_flat" => $coupon['discount_flat'], "name" => $coupon['name']);
             }
         }
         $toUseCoupons = array();
         foreach ($this->User->CouponPresenterUser->availableCouponsById($presenterId, $userId, $this->ShoppingCartItem->getCoupons()) as $coupon) {
             $toUseCoupons[$coupon['id']] = $coupon;
         }
         $hasdonation = $this->data['hasdonation'] == 'true' ? TRUE : FALSE;
         /**
          * Warehouse selection logic
          */
         $whm_id = $this->Country->getMarketFromCountryId($address['country_id']);
         if (!empty($address['state_id'])) {
             $warehouse = $this->Address->State->warehouse($address['state_id']);
         }
         if (empty($warehouse)) {
             $warehouse = (int) WarehouseUtil::idByMarket($whm_id);
         }
         /**
          * Catch Order Validation error
          */
         try {
             $this->Order->recargo_exempt = $recargo_exempt;
             $prices = $this->Order->createOrder($promoterId, $presenterId, $userId, $partyId, $itemIds, $address, Order::TYPE_PRODUCT, $productCredits, $toUseCoupons, FALSE, $is_presenter, $hasdonation, $warehouse);
         } catch (OrderValidationException $e) {
             $this->sendError(500, [DruniqueAPIUtil::content($e->getMessage(), $this->DruniqueAPI->page_data)]);
             return;
         }
         if ($prices !== false) {
             foreach ($prices['total']['usedCoupons'] as $couponId => $details) {
                 $this->User->CouponPresenterUser->id = $couponId;
                 $this->User->CouponPresenterUser->save(array("date_redeemed" => date('Y-m-d H:i:s'), "redemption_reference_id" => $details['reference_id'], "redemption_amount" => (string) $details['amount']));
             }
             $order = $this->Order->loadDisplayDetails();
             if ($vertex_success == 'false') {
                 $this->ApiAudit = ClassRegistry::init('ApiAudit');
                 $api_data = ['reference_name' => get_class(), 'reference_id' => 0, 'source' => __FILE__ . ' ' . __LINE__, 'destination' => 'vertex', 'sent' => json_encode($order), 'received' => 'vertex error', 'notes' => 'Vertex fail'];
                 $this->ApiAudit->clear();
                 $this->ApiAudit->create($api_data);
                 $this->ApiAudit->save();
             }
             $shipped_by_dates = $this->Order->estimatedShippingDates(date('Y-m-d H:i:s'));
             $ship_type = null;
             $expedited_date = null;
             switch ($this->data['ship_type']) {
                 case 'twoday':
                     $ship_type = 'twoday';
                     $expedited_date = $shipped_by_dates['TwoDay'];
                     break;
                 case 'ground':
                     $ship_type = 'ground';
                     $expedited_date = $shipped_by_dates['Ground'];
                     break;
                 default:
             }
             //I now need to fund this order...Possibly from multiple payment sources.
             $payments = array();
             /** @noinspection PhpUndefinedMethodInspection */
             if ($prices["total"]['productcredits']->isGreaterThanZero()) {
                 $payments[] = array("type" => "ledger", "presenter_id" => $presenterId, "user_id" => $userId, "amount" => $prices["total"]['productcredits']);
             }
             if ($this->data['hasdonation'] == 'true') {
                 $charge = $prices['total']['charge_w_donation'];
                 $donation = $prices['total']['donation'];
             } else {
                 $charge = $prices['total']['charge'];
                 $donation = 0.0;
             }
             $ip = array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
             /**
              * Prepare Payments
              */
             if (!empty($this->request->data['bankcode'])) {
                 $payments[] = $this->Payment->preparePayments(['request' => $this->request, 'session' => $this->Session->id(), 'country' => $country, 'address' => $address, 'amount' => $charge, 'party' => $partyId, 'order' => $order, 'ip' => $ip, 'bankcode' => $this->request->data['bankcode']]);
             } else {
                 $payments[] = $this->Payment->preparePayments(['request' => $this->request, 'session' => $this->Session->id(), 'country' => $country, 'address' => $address, 'amount' => $charge, 'party' => $partyId, 'order' => $order, 'ip' => $ip]);
             }
             /**
              * Process Payment
              */
             $paymentResult = $this->Payment->processOrderPayments($order['Order']['id'], $payments);
             /**
              * Finalize Order
              */
             $this->Order->finalize($paymentResult, $donation);
             /**
              * Payment Failed
              */
             if ($paymentResult['success'] !== true) {
                 foreach ($prices['total']['usedCoupons'] as $couponId => $details) {
                     $this->User->CouponPresenterUser->id = $couponId;
                     $this->User->CouponPresenterUser->save(["date_redeemed" => null, "redemption_reference_id" => null, "redemption_amount" => null]);
                 }
                 /**
                  * Cancel Payments
                  */
                 foreach ($payments as $payment) {
                     $this->Payment->cancel($payment['processor'], $order['Order']['order_market_id'], $order['Order']['id']);
                 }
                 $this->sendError(500, ['process_error' => [$paymentResult['error']]]);
                 return;
             } else {
                 if ($hasDailySpecial) {
                     $this->ShoppingCartItem->usedDailySpecial();
                 }
                 // Back Order Start
                 foreach ($order['OrderCustomer'] as $customerKey => $customer) {
                     foreach ($customer['OrderItem'] as $itemKey => $item) {
                         if (!empty($item['backorder_start'])) {
                             $order['OrderCustomer'][$customerKey]['BackOrderItem'][] = $item;
                         }
                     }
                 }
                 // Back Order End
                 $ycash = $productCredits ? number_format((int) $this->request->data['productcredits'] / 100, 2, '.', ',') : null;
                 $credit_card_payments = null;
                 $paypal = null;
                 if (empty($order['Party']['Hostess']) && !empty($order['Party']['ContactBook'])) {
                     $hostess = $order['Party']['ContactBook']['first_name'] . " " . $order['Party']['ContactBook']['last_name'];
                 } else {
                     $hostess = $order['Party']['Hostess']['first_name'] . " " . $order['Party']['Hostess']['last_name'];
                 }
                 $royalty_earned = $this->RoyaltiesEarned->getOrderCommission($order['Order']['id']);
                 $orderDetails = array("order" => $order, "ship_type" => $ship_type, "expedited_date" => $expedited_date, "presenter" => $presenter, "user_id" => $order['User']['id'], "sponsor" => $presenter['User']['first_name'] . " " . $presenter['User']['last_name'], "royalty_earned" => $royalty_earned, "name" => $address['first_name'] . " " . $address['last_name'], "current_locale" => $this->Session->read('Config.language'), "payments" => array("ycash" => $ycash, "creditcard" => $credit_card_payments, "paypal" => $paypal, "commission" => $commission_total, "hasdonation" => $this->data['hasdonation'], "orderwdonation" => $prices['total']['charge_w_donation'], "donation" => $prices['total']['donation'], "taxTypes" => $order['Order']['order_market_id'] == Market::MARKET_CANADA ? $prices['total']['taxes_by_type'] : array(), "recargo" => $order['Order']['order_market_id'] == Market::MARKET_SPAIN ? $prices['total']['recargo_tax']->display : '0.00'), "hasConventionTicket" => $hasConventionTicket, "hostess" => $hostess);
                 $user = $this->Session->read('user');
                 $tolkien = "";
                 if (isset($user['guest_checkout']) && $user['guest_checkout'] == TRUE) {
                     $tolkien = $this->User->setResetToken($user['id'], $user['primary_email']);
                     $orderDetails['tolkien'] = $tolkien;
                     $orderDetails['site_url'] = $presenter['PresenterSite']['site_url'];
                 }
                 if ($order['Order']['order_market_id'] == Market::MARKET_CANADA) {
                     $canda_tax_breakout = json_encode($prices['total']['taxes_by_type']);
                     $this->Order->setDynamicData($order['Order']['id'], 'canada_tax', $canda_tax_breakout);
                 }
                 if ($order['Order']['order_market_id'] == Market::MARKET_FRANCE) {
                     //grab what the customer paid with
                     $orderDetails['paid_with'] = $paymentResult['payments']['0']['paid_with'];
                 }
                 if ($this->request->data['processor'] == OrderPaymentProcessor::PROCESSOR_WORLDPAY_OXXO) {
                     $orderDetails['pending_payment'] = true;
                 }
                 //cakelog::debug('$orderDetails = '.var_export($orderDetails,true));
                 /**
                  * Customer Email
                  */
                 YouniqueEmail::queueEmail($orderDetails, 'en_us_order', $address['email_address'], 'Younique Order Confirmation', 'purchase-page', $orderDetails['current_locale']);
                 /**
                  * Sponsor Email
                  */
                 YouniqueEmail::queueEmail($orderDetails, 'en_us_sponsor_order', $presenter['User']['Email']['email'], 'Younique Order Confirmation', 'purchase-page', $presenter['User']['user_default_locale']);
                 /**
                  * Queue for after purchase order modifications
                  */
                 if (!$this->Order->noQueueFlagged($order['Order']['id'])) {
                     $this->Order->queueOrder($order['Order']['id']);
                 }
                 if ($order['Order']['order_market_id'] == Market::MARKET_CANADA) {
                     $canda_tax_breakout = json_encode($prices['total']['taxes_by_type']);
                     $this->Order->setDynamicData($order['Order']['id'], 'canada_tax', $canda_tax_breakout);
                 }
                 //get the items in the order
                 $order_items = array();
                 foreach ($order['OrderCustomer']['OrderItem'] as $oi) {
                     $order_items[] = array('sku' => $oi['Item']['sku'], 'name' => $oi['Item']['name'], 'price' => $oi['price'], 'qty' => $oi['quantity'], 'subtotal' => $oi['extended_price'], 'originalSubtotal' => $oi['discount'] + $oi['extended_price'], 'display_name' => $oi['Item']['ItemContent']['display_name'], 'tax_type' => $this->Item->getTaxTypeName($oi['Item']['id']));
                 }
                 $shipping = Money::fromString($order['Order']['shippingtotal']);
                 // Send Invoice to Vertex for tax purposes
                 $this->Order->create_invoice($address, $order['Order']['order_market_id'], $order_items, $order['Order']['id'], $userId, $this->Session->check('last_quote_date') ? $this->Session->read('last_quote_date') : date(Y - m - d), $shipping);
                 $this->Session->write('order.id', $this->Order->id);
                 $this->Session->write('order.user_id', $order['Order']['user_id']);
                 $countPayment = count($paymentResult['payments']);
                 $redirect = false;
                 for ($i = 0; $i < $countPayment; $i++) {
                     if (!empty($paymentResult['payments'][$i]['redirect'])) {
                         $redirect = true;
                         $redirect_value = $paymentResult['payments'][$i]['transaction_id'];
                     }
                 }
                 if ($redirect == true) {
                     $this->ShoppingCartItem->clear();
                     $this->sendSuccess(['redirect' => $redirect_value]);
                 } else {
                     $this->sendSuccess(["id" => $this->Order->id, 'subtotal' => $order['Order']['subtotal'], 'tax' => $order['Order']['taxtotal'], 'shipping' => $order['Order']['shippingtotal'], 'city' => $this->request->data['city'], 'state' => $this->request->data['state'], 'country' => 'USA', 'items' => $order_items, 'access_token' => $tolkien]);
                 }
             }
         } else {
             $this->sendError(500, array("process_error" => array(DruniqueAPIUtil::content('cannot create order', $this->DruniqueAPI->page_data))));
         }
     }
 }