function updateShipmentFeed($post_id)
 {
     $feed_type = '_POST_FLAT_FILE_FULFILLMENT_DATA_';
     $order_id = get_post_meta($post_id, '_wpla_amazon_order_id', true);
     $om = new WPLA_OrdersModel();
     $order = $om->getOrderByOrderID($order_id);
     $account = new WPLA_AmazonAccount($order->account_id);
     // echo "<pre>";print_r($account);echo"</pre>";die();
     WPLA()->logger->info('updateShipmentFeed() ' . $feed_type . ' - order id: ' . $order_id);
     WPLA()->logger->info('updateShipmentFeed() - post id: ' . $post_id . ' - account id: ' . $account->id);
     // create pending feed if it doesn't exist
     if (!($this->id = self::getPendingFeedId($feed_type, null, $account->id))) {
         # build feed data
         WPLA()->logger->info('building shipment data feed...');
         $csv = WPLA_FeedDataBuilder::buildShippingFeedData($post_id, $order_id, $account->id, true);
         if (!$csv) {
             WPLA()->logger->warn('no feed data - not creating feed');
             return;
         }
         // add new feed
         $this->FeedType = $feed_type;
         $this->status = 'pending';
         $this->account_id = $account->id;
         $this->date_created = date('Y-m-d H:i:s');
         $this->data = $csv;
         $this->add();
         WPLA()->logger->info('added NEW feed - id ' . $this->id);
     } else {
         WPLA()->logger->info('found existing feed ' . $this->id);
         $existing_feed = new WPLA_AmazonFeed($this->id);
         # append feed data
         WPLA()->logger->info('updating shipment data feed...');
         $csv = WPLA_FeedDataBuilder::buildShippingFeedData($post_id, $order_id, $account->id, false);
         $this->data = $existing_feed->data . $csv;
     }
     // update feed
     $this->line_count = sizeof($csv);
     $this->FeedProcessingStatus = 'pending';
     $this->date_created = date('Y-m-d H:i:s');
     $this->update();
     WPLA()->logger->info('feed was built and updated - ' . $this->id);
 }
 public function action_update_orders()
 {
     WPLA()->logger->info("do_action: wpla_update_orders");
     $accounts = WPLA_AmazonAccount::getAll();
     foreach ($accounts as $account) {
         $api = new WPLA_AmazonAPI($account->id);
         // get date of last order
         $om = new WPLA_OrdersModel();
         $lastdate = $om->getDateOfLastOrder($account->id);
         WPLA()->logger->info('getDateOfLastOrder() returned: ' . $lastdate);
         $days = isset($_REQUEST['days']) && $_REQUEST['days'] ? $_REQUEST['days'] : false;
         if (!$lastdate && !$days) {
             $days = 1;
         }
         // get orders
         $orders = $api->getOrders($lastdate, $days);
         // echo "<pre>";print_r($orders);echo"</pre>";#die();
         if (is_array($orders)) {
             // run the import
             $importer = new WPLA_OrdersImporter();
             $success = $importer->importOrders($orders, $account);
             $msg = sprintf(__('%s order(s) were processed for account %s.', 'wpla'), sizeof($orders), $account->title);
             if ($importer->updated_count > 0) {
                 $msg .= "\n" . 'Updated orders: ' . $importer->updated_count;
             }
             if ($importer->imported_count > 0) {
                 $msg .= "\n" . 'Created orders: ' . $importer->imported_count;
             }
             WPLA()->logger->info($msg);
             $this->showMessage(nl2br($msg), 0, 1);
         } elseif ($orders->Error->Message) {
             $msg = sprintf(__('There was a problem downloading orders for account %s.', 'wpla'), $account->title) . ' - Error: ' . $orders->Error->Message;
             WPLA()->logger->error($msg);
             $this->showMessage(nl2br($msg), 1, 1);
         } else {
             $msg = sprintf(__('There was a problem downloading orders for account %s.', 'wpla'), $account->title);
             WPLA()->logger->error($msg);
             $this->showMessage(nl2br($msg), 1, 1);
         }
     }
     $this->message = '';
 }
 public function showOrderDetails($id)
 {
     // init model
     $ordersModel = new WPLA_OrdersModel();
     // get amazon_order record
     $amazon_order = $ordersModel->getItem($id);
     // get WooCommerce order
     $wc_order_notes = $amazon_order['post_id'] ? $this->get_order_notes($amazon_order['post_id']) : false;
     $aData = array('amazon_order' => $amazon_order, 'wc_order_notes' => $wc_order_notes);
     $this->display('order_details', $aData);
 }
 /** ************************************************************************
  * REQUIRED! This is where you prepare your data for display. This method will
  * usually be used to query the database, sort and filter the data, and generally
  * get it ready to be displayed. At a minimum, we should set $this->items and
  * $this->set_pagination_args(), although the following properties and methods
  * are frequently interacted with here...
  * 
  * @uses $this->_column_headers
  * @uses $this->items
  * @uses $this->get_columns()
  * @uses $this->get_sortable_columns()
  * @uses $this->get_pagenum()
  * @uses $this->set_pagination_args()
  **************************************************************************/
 function prepare_items()
 {
     // process bulk actions
     $this->process_bulk_action();
     // get pagination state
     $current_page = $this->get_pagenum();
     $per_page = $this->get_items_per_page('orders_per_page', 20);
     // define columns
     $this->_column_headers = $this->get_column_info();
     // fetch profiles from model
     $ordersModel = new WPLA_OrdersModel();
     $this->items = $ordersModel->getPageItems($current_page, $per_page);
     $total_items = $ordersModel->total_items;
     // register our pagination options & calculations.
     $this->set_pagination_args(array('total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page)));
 }
 public static function processAmazonShipmentsReportPage($report, $rows, $job, $task)
 {
     $wc_orders_processed = 0;
     // process rows
     foreach ($rows as $row) {
         // check for MCF order ID
         $order_id = str_replace('#', '', $row['merchant-order-id']);
         $order_item_id = $row['merchant-order-item-id'];
         $is_mcf_order = true;
         // if ( empty( $order_id ) ) continue;
         // if ( empty( $order_item_id ) ) continue;
         // no merchant-order-id means this order was placed on Amazon - find WooCommerce order by reference
         if (empty($order_id)) {
             $amazon_order_id = $row['amazon-order-id'];
             $is_mcf_order = false;
             $om = new WPLA_OrdersModel();
             $order = $om->getOrderByOrderID($amazon_order_id);
             if ($order) {
                 $order_id = $order->post_id;
             }
         }
         if (empty($order_id)) {
             continue;
         }
         // get WooCommerce order
         $_order = wc_get_order($order_id);
         if (!$_order) {
             continue;
         }
         // echo "<pre>";print_r($_order);echo"</pre>";#die();
         // echo "<pre>";print_r($row);echo"</pre>";die();
         $shipment_date = $row['shipment-date'];
         $estimated_arrival_date = $row['estimated-arrival-date'];
         $ship_service_level = $row['ship-service-level'];
         $tracking_number = $row['tracking-number'];
         $carrier = $row['carrier'];
         // update order meta fields
         update_post_meta($order_id, '_wpla_fba_submission_status', 'shipped');
         update_post_meta($order_id, '_wpla_fba_shipment_date', $shipment_date);
         update_post_meta($order_id, '_wpla_fba_estimated_arrival_date', $estimated_arrival_date);
         update_post_meta($order_id, '_wpla_fba_ship_service_level', $ship_service_level);
         update_post_meta($order_id, '_wpla_fba_tracking_number', $tracking_number);
         update_post_meta($order_id, '_wpla_fba_ship_carrier', $carrier);
         // update meta fields for WooCommerce Shipment Tracking plugin
         update_post_meta($order_id, '_date_shipped', strtotime($shipment_date));
         update_post_meta($order_id, '_tracking_number', $tracking_number);
         update_post_meta($order_id, '_custom_tracking_provider', $carrier);
         update_post_meta($order_id, '_tracking_provider', '');
         // known providers - would require mapping ('usps' <=> 'USPS')
         $wc_orders_processed++;
         // skip further processing for non-MCF orders - no need to to update orders placed on Amazon
         if (!$is_mcf_order) {
             continue;
         }
         // complete order
         $_order->update_status('completed');
         // notify WPLE - mark order as shipped on eBay
         $args = array();
         $args['TrackingNumber'] = $tracking_number;
         $args['TrackingCarrier'] = $carrier;
         $args['ShippedTime'] = $shipment_date;
         // $args['FeedbackText']    = 'Thank You...';
         do_action('wple_complete_sale_on_ebay', $order_id, $args);
     }
     // build response
     $response = new stdClass();
     $response->job = $job;
     $response->task = $task;
     $response->errors = '';
     $response->success = true;
     $response->count = $wc_orders_processed;
     return $response;
 }
 public function importOrder($order, $account)
 {
     global $wpdb;
     $table = $wpdb->prefix . self::TABLENAME;
     // skip processing if requests are throttled already
     if ($this->throttling_is_active == true) {
         return false;
     }
     // if ( ! is_object($order) )
     // 	echo "<pre>order is not an object: ";print_r($order);echo"</pre>";die();
     // check if order exists in WPLA and is already up to date (TODO: optimize)
     if ($id = $this->order_id_exists($order->AmazonOrderId)) {
         $om = new WPLA_OrdersModel();
         $amazon_order = $om->getItem($id);
         if ($amazon_order['LastTimeModified'] == $this->convertIsoDateToSql($order->LastUpdateDate)) {
             WPLA()->logger->info('Order ' . $order->AmazonOrderId . ' has not been modified since ' . $amazon_order['LastTimeModified'] . ' and is up to date.');
             wpla_show_message('Order ' . $order->AmazonOrderId . ' has not been modified since ' . $amazon_order['LastTimeModified'] . ' and is up to date.');
             return null;
         }
     }
     $data = array('order_id' => $order->AmazonOrderId, 'status' => $order->OrderStatus, 'total' => isset($order->OrderTotal->Amount) ? $order->OrderTotal->Amount : '', 'currency' => isset($order->OrderTotal->CurrencyCode) ? $order->OrderTotal->CurrencyCode : '', 'buyer_name' => isset($order->BuyerName) ? $order->BuyerName : '', 'buyer_email' => isset($order->BuyerEmail) ? $order->BuyerEmail : '', 'PaymentMethod' => isset($order->PaymentMethod) ? $order->PaymentMethod : '', 'ShippingAddress_City' => isset($order->ShippingAddress->City) ? $order->ShippingAddress->City : '', 'date_created' => $this->convertIsoDateToSql($order->PurchaseDate), 'LastTimeModified' => $this->convertIsoDateToSql($order->LastUpdateDate), 'account_id' => $account->id, 'details' => json_encode($order));
     // fetch order line items from Amazon - required for both new and updated orders
     $this->api = new WPLA_AmazonAPI($account->id);
     $items = $this->api->getOrderLineItems($order->AmazonOrderId);
     $data['items'] = maybe_serialize($items);
     // check if ListOrderItems request is throttled
     // if true, skip ALL further requests / order processing until next cron run
     if (is_object($items) && isset($items->Error->Message)) {
         $this->throttling_is_active = true;
         wpla_show_message('ListOrderItems requests are throttled. Skipping further order processing until next run.', 'warn');
         return false;
     }
     // check if order exists in WPLA
     if ($id = $this->order_id_exists($order->AmazonOrderId)) {
         // load existing order record from wp_amazon_orders
         $ordersModel = new WPLA_OrdersModel();
         $wpla_order = $ordersModel->getItem($id);
         // check if order status was updated
         // if pending -> Canceled: revert stock reduction by processing history records
         // if pending -> Shipped / Unshipped: create WooCommerce order if enabled (done in createOrUpdateWooCommerceOrder())
         if ($order->OrderStatus != $wpla_order['status']) {
             $old_order_status = $wpla_order['status'];
             $new_order_status = $order->OrderStatus;
             // add history record
             $history_message = "Order status has changed from " . $old_order_status . " to " . $new_order_status;
             $history_details = array('id' => $id, 'new_status' => $new_order_status, 'old_status' => $old_order_status, 'LastTimeModified' => $data['LastTimeModified']);
             $this->addHistory($data['order_id'], 'order_status_changed', $history_message, $history_details);
             // if pending -> Canceled: revert stock reduction by processing history records
             if ($old_order_status == 'Pending' && $new_order_status == 'Canceled') {
                 // revert stock reduction
                 $this->revertStockReduction($wpla_order);
                 // add history record
                 $history_message = "Stock levels have been replenished";
                 $history_details = array('id' => $id);
                 $this->addHistory($data['order_id'], 'revert_stock', $history_message, $history_details);
             }
         }
         // if status changed
         // update existing order
         $wpdb->update($table, $data, array('order_id' => $order->AmazonOrderId));
         $this->updated_count++;
         // TODO: update WooCommerce order!
         // add history record
         $history_message = "Order details were updated - " . $data['LastTimeModified'];
         $history_details = array('id' => $id, 'status' => $data['status'], 'LastTimeModified' => $data['LastTimeModified']);
         $this->addHistory($data['order_id'], 'order_updated', $history_message, $history_details);
     } else {
         // insert new order
         $wpdb->insert($table, $data);
         $this->imported_count++;
         $id = $wpdb->insert_id;
         echo $wpdb->last_error;
         // add history record
         $history_message = "Order was added with status: " . $data['status'];
         $history_details = array('id' => $id, 'status' => $data['status'], 'LastTimeModified' => $data['LastTimeModified']);
         $this->addHistory($data['order_id'], 'order_inserted', $history_message, $history_details);
         // process ordered items - unless order has been cancelled
         if ($data['status'] != 'Canceled') {
             foreach ($items as $item) {
                 // process each item and reduce stock level
                 $success = $this->processListingItem($item, $order);
             }
         }
     }
     // if order does not exist
     return $id;
 }
 function wpla_woocommerce_admin_order_filter_query($query)
 {
     global $typenow, $wp_query, $wpdb;
     if ($typenow == 'shop_order') {
         // filter by amazon status
         if (!empty($_GET['is_from_amazon'])) {
             if ($_GET['is_from_amazon'] == 'yes') {
                 $account_id = isset($_REQUEST['wpla_account_id']) ? $_REQUEST['wpla_account_id'] : false;
                 if ($account_id) {
                     // find post_ids for all orders for this account
                     $post_ids = array();
                     $orders = WPLA_OrdersModel::getWhere('account_id', $account_id);
                     foreach ($orders as $order) {
                         if (!$order->post_id) {
                             continue;
                         }
                         $post_ids[] = $order->post_id;
                     }
                     if (empty($post_ids)) {
                         $post_ids = array('0');
                     }
                     $query->query_vars['post__in'] = $post_ids;
                 } else {
                     $query->query_vars['meta_query'][] = array('key' => '_wpla_amazon_order_id', 'compare' => 'EXISTS');
                 }
             } elseif ($_GET['is_from_amazon'] == 'no') {
                 $query->query_vars['meta_query'][] = array('key' => '_wpla_amazon_order_id', 'compare' => 'NOT EXISTS');
             }
         }
     }
 }