/** * Execute Queue Commissions * * @return bool */ public function execute() { /** * Limit is command line argument */ $limit = !empty($this->args[0]) ? $this->args[0] : null; /** * Get Commissions */ $commissions = $this->RoyaltiesEarned->listRetailCommissions(RoyaltiesEarned::STATUS_UNPAID, $limit, true); $this->out('=> Retrieved: ' . count($commissions) . ' commissions.'); /** * Queued Commissions */ $queued = []; /** * Send commissions into commission_queue */ foreach ($commissions as $commission) { if (empty($commission['id']) || empty($commission['presenter_id'])) { continue; } $sqs = new Sqs(Sqs::queueUrl('commission_queue')); $sqs->sendJSON(['id' => $commission['id'], 'name' => 'RoyaltiesEarned', 'delay_seconds' => $this->delay_seconds, 'payload' => $commission, 'timeout' => 30.0, 'created' => date("Y-m-d H:i:s")], $this->delay_seconds); $queued[] = $commission['id']; $this->RoyaltiesEarned->clear(); $this->RoyaltiesEarned->id = $commission['id']; $this->RoyaltiesEarned->saveField("royalty_status_id", RoyaltiesEarned::STATUS_QUEUED); $this->out('=> Queued commission RoyaltiesEarned id: ' . $commission['id']); } $this->out('=> Queued: ' . count($queued) . ' commissions.'); return true; }
/** * Queue For Snap * * @param OrderShipment $Model * @param null $delay * @param null $priority * @param null $id * @param array $payload * @return bool */ public function queueForSnap(OrderShipment $Model, $delay = null, $priority = null, $id = null, $payload = []) { if (empty($id)) { $id = $Model->id; } if ($delay != null) { $this->delay_seconds = $delay; } if (Sqs::useQueue()) { $sqs = new Sqs(Sqs::queueUrl('snap_queue')); $sqs->sendJSON(['id' => $id, 'name' => 'Shipment', 'delay_seconds' => $this->delay_seconds, 'payload' => $payload, 'timeout' => 30.0, 'created' => date("Y-m-d H:i:s")], $this->delay_seconds, $priority); } return true; }
/** * Execute close shipment * * @return bool * @throws CloseShipmentException */ public function execute() { parent::execute(); $shipment_id = $this->message_id; $stage = $this->message_data['payload']->stage; $snap_shipment_id = $this->message_data['payload']->snap_shipment_id; $snap_instance = $this->message_data['payload']->snap_instance; $date_created = $this->message_data['payload']->date_created; if (empty($date_created) || empty($snap_instance) || empty($stage)) { $this->out('=> Error: Message from sqs is malformed.'); return false; } $order_shipment = $this->getDbShipment($shipment_id); if (!$order_shipment) { $this->out("=> Error: No Order shipment record found.", 1, Shell::VERBOSE); return false; } // lookup the order and store the tracking number $snap_shipment = $this->getShipment("shipments/{$snap_shipment_id}", $snap_instance); if (!$snap_shipment) { return true; } $order_id = $snap_shipment->CustomerRef; $this->Order->id = $order_id; $this->out("=> Processing Shipment Stage: {$stage}"); /** * Handle shipment stages */ switch ($stage) { case SnapConfig::SNAP_CANCELLED: $this->cancelShipment($shipment_id); break; case SnapConfig::SNAP_SHIPPED: $this->closeShipment($shipment_id, $snap_shipment, $date_created); /** * Send message for Net Suite Item fulfillment */ if (Sqs::useQueue()) { $sqs = new Sqs(Sqs::queueUrl('ns_item_fulfillment_queue')); $sqs->sendJSON(['id' => $shipment_id, 'name' => 'Shipment', 'delay_seconds' => 1, 'timeout' => 30.0, 'created' => date("Y-m-d H:i:s")]); } break; default: throw new CloseShipmentException("Stage {$stage} not found for closing shipment {$shipment_id}"); } return true; }
/** * Sends an email to the queue to make sure email sends don't hold up http requests on the site. * @param $emailData * @param $templateName * @param $to * @param $subjectBlockName * @param $tag * @param $locale * @param null $emailOptions * @return bool|\Guzzle\Service\Resource\Model|string * @throws Exception */ public static function queueEmail($emailData, $templateName, $to, $subjectBlockName, $tag, $locale, $emailOptions = null) { $to = trim($to); if (Sqs::useQueue()) { $data = ['to' => $to, 'locale' => $locale, 'template' => $templateName, 'tag' => $tag, 'subject' => $subjectBlockName, 'email_data' => $emailData, 'email_options' => $emailOptions]; if (!defined('EMAIL_QUEUE_DB') || !defined('EMAIL_QUEUE_SQS')) { CakeLog::error("Email Queue Table name or SQS Url not found."); return false; } $ddb = new Ddb(EMAIL_QUEUE_DB); $sqs = new Sqs(EMAIL_QUEUE_SQS); // save to DDB $details_id = $ddb->guid(); $result = $ddb->saveData($details_id, $data); // send to SQS $sqs->send($details_id); return $result; } else { $result = YouniqueEmail::sendEmail($emailData, $templateName, $to, $subjectBlockName, $tag, $locale, false, $emailOptions); return $result; } }
/** * Queue an order in purchase queue * * @param Order $Model * @param $id * @param null $priority * @return bool */ public function queueOrder(Order $Model, $id, $priority = null) { if (empty($id)) { $id = $Model->id; } /** * Queue Order in SQS for post purchase modifications */ if (Sqs::useQueue()) { $sqs = new Sqs(Sqs::queueUrl('order_events')); $sqs->sendJSON(['id' => $id, 'name' => 'Order', 'delay_seconds' => $this->delay_seconds, 'timeout' => 30.0, 'created' => date("Y-m-d H:i:s")], $this->delay_seconds, $priority); } else { /** * Process queue tasks manually (For Local DEVELOPMENT) */ $this->OrderShipmentMethod = ClassRegistry::init('OrderShipmentMethod'); $this->OrderShipmentMethod->setOrderShipmentMethod($id); $Model->addLipstickCard(); $Model->addBackOrderCard(); $Model->addFreeItems(); $Model->orderReady(); } return true; }
/** * Submits the selected orders to the Amazon Queue */ public function fboEnqueueOrders() { if (!self::AppSession(CHECK, 'fboOptions')) { $this->appException('fbo', 'API options not found.'); } else { if (!self::AppSession(CHECK, 'fboSelected')) { $this->appException('fbo', 'Selected orders not found.'); } else { // array to track queued order_id's for audit log $ids = array(); // define the return array $queued = array('orders' => [], 'sqs_results' => [], 'items_used' => 0); // check our ability to use the sqs queue if (!Sqs::useQueue()) { return $this->appException('fbo', 'Unable to use SQS Queue.'); } // attempt to create the sqs object try { $sqs = new Sqs(Sqs::queueUrl('back_order_allocation_queue')); } catch (Exception $e) { return $this->appException('fbo', 'Unable to create SQS object: ' . $e->getMessage()); } // default sqs queue values $delay = 1; $priority = 1; //1=High 10=Low // send each order into the queue $orders = self::AppSession(READ, 'fboSelected'); $options = self::AppSession(READ, 'fboOptions'); foreach ($orders as $key => $order) { $order_id = (int) $order['Order']['id']; $order_item_id = (int) $order['OrderItem']['id']; $item_quantity = (int) $order['OrderItem']['quantity']; $message_data = ['id' => $order_item_id, 'name' => 'OrderItem', 'delay_seconds' => $delay, 'payload' => new stdClass(), 'timeout' => 30.0, 'created' => date("Y-m-d H:i:s")]; if (!empty($options['bo_class']) && $options['bo_class'] == 'true') { $message_data['payload']->shipment_class = 'BO'; } try { /** * According to the documentation found at: * http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html#API_SendMessage_Examples * it's possible that the reponse could contain Errors, although the documentation at: * http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.Sqs.SqsClient.html#_sendMessage * seems to indicate that sendMessage(), which is used by sendJSON, does not have an error response. */ $response = $sqs->sendJSON($message_data, $delay, $priority); $ResponseMetadata = $response->get('ResponseMetadata'); $result = ['MessageId' => $response->get('MessageId'), 'MD5OfMessageAttributes' => $response->get('MD5OfMessageAttributes'), 'MD5OfMessageBody' => $response->get('MD5OfMessageBody'), 'RequestId' => $ResponseMetadata['RequestId']]; // Add the sqs response to the order $order['SqsResult'] = $result; // add this updated $order to the return array array_push($queued['orders'], $order); // update the items_used value in the return array $queued['items_used'] += $item_quantity; // push the order_id to the $ids array for use in the audit log array_push($ids, $order_id); } catch (Exception $e) { $result = ['Error' => $e->getMessage()]; } // Add the sqs response to the sqs_results array $sqsResult = ['OrderId' => $order_id, 'OrderItemId' => $order_item_id, 'ItemQuantity' => $item_quantity]; array_push($queued['sqs_results'], array_merge($sqsResult, $result)); } // create the audit log entry try { $this->AdminUserAudit->save(array('admin_user_id' => $options['audit']['admin_user_id'], 'reference_name' => 'order_items.item_id', 'reference_id' => $options['item_id'], 'old_value' => json_encode(array('request' => array('sku' => $options['item_sku'], 'wh' => $options['warehouse_id'], 'qty' => $options['fulfill_qty'], 'dates' => $options['lib_params']['date']))), 'new_value' => json_encode(array('result' => array('num_orders_queued' => count($queued['orders']), 'num_items_used' => $queued['items_used'], 'orders' => $ids))), 'notes' => 'Backorders send to fulfilment queue')); } catch (Exception $e) { CakeLog::error("Error: Cannot create AdminUserAudit record - " . $e->getMessage() . "\nFile: " . $e->getFile() . "\nLine: " . $e->getLine()); } // Delete the session vars $this->fboCleanup(); // Create the response $this->appRespond(true, $queued); } } }
/** * Failure sqs url * * Failure queue full path url * * @return string */ protected function failureSqsUrl() { return Sqs::queueUrl($this->sqs_fail_name); }
/** * Execute Process Snap Notifications * @return bool * @throws SnapConfigError * @throws SnapNotificationsException */ public function execute() { /** * Initialize arguments */ $mod_value = $this->args[0]; $snap_instance = $this->args[1]; $max_notifications = !empty($this->args[2]) ? $this->args[2] : 100; if (empty($snap_instance)) { throw new SnapNotificationsException('You must provide a Snap instance.'); } $this->out("Processing Snap Notifications:", 1, Shell::VERBOSE); $this->out("Mod value: {$mod_value}", 1, Shell::VERBOSE); $this->out("Snap instance: {$snap_instance}", 1, Shell::VERBOSE); $this->out("Qty: {$max_notifications} ", 1, Shell::VERBOSE); $notification_endpoint = 'snapoutbound?$top=' . $max_notifications; if (is_numeric($mod_value)) { $notification_endpoint .= '&$filter=endswith(XDoc,\'' . $mod_value . '\')'; } $notifications = $this->getNotifications($notification_endpoint, $snap_instance); if (!$notifications) { $this->out('No notifications to process.'); return true; } $total_records = count($notifications); $this->out("Notifications: {$total_records}", 1, Shell::VERBOSE); $stage = null; $count = 0; foreach ($notifications as $notification) { $count++; $left = $total_records - $count; $this->hr(); $this->out('Left: ' . $left); $shipment_id = NULL; $clear_notification_endpoint = "snapoutbound" . "/" . $notification->XDoc; $snap_shipment_id = ''; $shipment_id = ''; $transfer_order = false; $shipment = explode(' ', $notification->Key); foreach ($shipment as $value) { $parts = explode('=', $value); foreach ($parts as $part) { if ($part == "Shipment") { /** * Check for transfer order */ if (strpos($parts[1], 'TO') !== false) { $transfer_order = true; } $snap_shipment_id = str_replace("\"", "", $parts[1]); $shipment_id = (int) str_replace("\"", "", $parts[1]); } elseif ($part == "Stage") { $stage = (int) str_replace("\"", "", $parts[1]); } } } /** * Skip transfer orders */ if ($transfer_order == true) { continue; } /** * Skip on no shipment id */ if (!$shipment_id || !is_numeric($shipment_id)) { $this->out("Not a valid shipment ID", 1, Shell::VERBOSE); continue; } $this->out("Sending notification to queue for shipment id: {$shipment_id}", 1, Shell::VERBOSE); $message_data = ['id' => $shipment_id, 'name' => 'Shipment', 'delay_seconds' => $this->delay_seconds, 'payload' => ['stage' => $stage, 'snap_shipment_id' => $snap_shipment_id, 'snap_instance' => $snap_instance, 'date_created' => $notification->DateCreated], 'timeout' => 30.0, 'created' => date("Y-m-d H:i:s")]; if (Sqs::useQueue()) { $sqs = new Sqs(Sqs::queueUrl('snap_notifications_queue')); $sqs->sendJSON($message_data, $this->delay_seconds); } $this->out("Clearing notification for: " . $notification->XDoc, 1, Shell::VERBOSE); if (!$this->clearNotification($clear_notification_endpoint, $snap_instance, $notification)) { continue; } $this->out("Total notifications left: " . $left, 1, Shell::VERBOSE); } return true; }
/** * Send Tracking Email from net suite DataFlow 5 * * @see DataFlowFiveTask * @param $shipment_id * @return bool|\Guzzle\Service\Resource\Model */ public function sendCustomerTrackingEmail($shipment_id) { $this->OrderShipment = ClassRegistry::init('OrderShipment'); $record = $this->OrderShipment->find('first', ['contain' => ['OrderShipment', 'Order'], 'conditions' => ['OrderShipment.id' => $shipment_id]]); if ($record['OrderShipment']['tracking_number'] && $record['OrderShipment']['carrier']) { $tracking_url = $this->OrderShipment->getTrackingLink($record['OrderShipment']['tracking_number'], $record['OrderShipment']['carrier']); } else { $tracking_url = ''; } //to try to avoid sending too many emails, check the order status. if ($record['Order']['order_status_id'] == Order::STATUS_SHIPPED) { return false; } $charm_order = false; if ((string) $record['Order']['order_type_id'] == '8') { $charm_order = true; } $customer_name = $record['OrderShipment']['first_name'] . " " . $record['OrderShipment']['last_name']; if (!$charm_order) { $email_data = ["name" => $customer_name, "order_id" => $record['OrderShipment']['order_id'], "tracking_number" => $record['OrderShipment']['tracking_number'], "tracking_url" => $tracking_url, "country_id" => $record['OrderShipment']['country_id']]; $customers_user_id = $record['Order']['user_id']; $this->User = ClassRegistry::init('User'); $userLocale = $this->User->userLocale($customers_user_id); $locale = $userLocale['User']['locale'] ? $userLocale['User']['locale'] : "en_US"; $data = ['to' => $record['OrderShipment']['email_address'], 'locale' => $locale, 'template' => 'en_us_tracking_numbers', 'tag' => 'purchase-page', 'subject' => 'email order tracking', 'email_data' => $email_data]; if (!defined('EMAIL_QUEUE_DB') || !defined('EMAIL_QUEUE_SQS')) { CakeLog::error("Email Queue Table name or SQS Url not found."); return false; } $ddb = new Ddb(EMAIL_QUEUE_DB); $sqs = new Sqs(EMAIL_QUEUE_SQS); // save to DDB $details_id = $ddb->guid(); $result = $ddb->saveData($details_id, $data); // send to SQS $sqs->send($details_id); return $result; } return false; }
/** * $args[0] = shipment_id //30108475 */ public function test_snap_send() { $id = $this->args[0]; $this->out("Creating test Snap SQS message Shipment_id# {$id}"); $delay = 1; $priority = 1; //1=High 10=Low if ($this->args[1] == '_fail_sqs') { $sqs = new Sqs(Sqs::queueUrl('snap_queue_fail')); } else { $sqs = new Sqs(Sqs::queueUrl('snap_queue')); } $sqs->sendJSON(['id' => $id, 'name' => 'Shipment', 'delay_seconds' => $delay, 'payload' => ['hostname' => trim(gethostname())], 'timeout' => 30.0, 'created' => date("Y-m-d H:i:s")], $delay, $priority); $this->out("Sent SQS Message id: {$id}"); }
/** * @param Order $Model * @param null $id * @param null $delay * @return bool */ public function queueForNetSuite(Order $Model, $id = null, $delay = null) { if (empty($id)) { $id = $Model->id; } if ($delay != null) { $this->delay_seconds = $delay; } if (Sqs::useQueue() && !$Model->noQueueFlagged($id)) { /** * Queue For NetSuite */ if ($Model->isExpedited()) { $sqs_queue = 'ns_expedited_order'; $delay = $this->expedited_delay; } else { $sqs_queue = 'ns_export_orders_queue'; $delay = $this->delay_seconds; } $sqs = new Sqs(Sqs::queueUrl($sqs_queue)); $sqs->sendJSON(['id' => $id, 'name' => 'Order', 'delay_seconds' => $delay, 'timeout' => 30.0, 'created' => date("Y-m-d H:i:s")], $delay); } return true; }