Skip to content

Commit

Permalink
refs #49022 listen for order state update
Browse files Browse the repository at this point in the history
  • Loading branch information
bogdan202 committed Nov 28, 2024
1 parent e2fe331 commit ec70941
Show file tree
Hide file tree
Showing 9 changed files with 292 additions and 42 deletions.
2 changes: 1 addition & 1 deletion 202/build.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<property name="src-dir" value="${basedir}" />
<property name="TARGETNAME" value="shoppingfeed" />
<property name="TARGETBRANCH" value="${env.GIT_BRANCH}" />
<property name="TARGETVERSION" value="1.12.0" />
<property name="TARGETVERSION" value="2.0.0" />
<target name="build" depends="build-common,package-zip,psvalidator,tot-testing" />

<target name="build-common" depends="lint,prepare" />
Expand Down
8 changes: 7 additions & 1 deletion classes/ShoppingfeedTaskOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ class ShoppingfeedTaskOrder extends ObjectModel
{
const ACTION_SYNC_STATUS = 'SYNC_STATUS';

const ACTION_UPLOAD_INVOICE = 'UPLOAD_INVOICE';

// As in, "check the ticket related to the Order Status synchronization"
const ACTION_CHECK_TICKET_SYNC_STATUS = 'CHECK_TICKET_SYNC_STATUS';

Expand Down Expand Up @@ -60,7 +62,11 @@ class ShoppingfeedTaskOrder extends ObjectModel
'validate' => 'isGenericName',
'required' => true,
'unique' => true,
'values' => [self::ACTION_SYNC_STATUS, self::ACTION_CHECK_TICKET_SYNC_STATUS],
'values' => [
self::ACTION_SYNC_STATUS,
self::ACTION_CHECK_TICKET_SYNC_STATUS,
self::ACTION_UPLOAD_INVOICE,
],
],
'id_order' => [
'type' => ObjectModel::TYPE_INT,
Expand Down
137 changes: 137 additions & 0 deletions classes/actions/ShoppingfeedOrderSyncActions.php
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,78 @@ public function prepareTaskOrdersSyncStatus()
return true;
}

public function prepareTaskOrdersSyncInvoice()
{
if (empty($this->conveyor['id_shop'])) {
ProcessLoggerHandler::logError(
$this->l('No ID Shop found.', 'ShoppingfeedOrderSyncActions'),
'Order'
);

return false;
}
if (empty($this->conveyor['taskOrders'])) {
ProcessLoggerHandler::logInfo(
$this->l('No Task Orders to prepare.', 'ShoppingfeedOrderSyncActions'),
'Order'
);

return false;
}

$taskOrders = $this->conveyor['taskOrders'];
$this->conveyor['preparedTaskOrders'] = [];

foreach ($taskOrders as $taskOrder) {
/** @var $taskOrder ShoppingfeedTaskOrder */
$logPrefix = self::getLogPrefix($taskOrder->id_order);
$order = new Order($taskOrder->id_order);
$sfOrder = ShoppingfeedOrder::getByIdOrder($taskOrder->id_order);

if (!Validate::isLoadedObject($order)) {
ProcessLoggerHandler::logError(
$logPrefix . ' ' .
$this->l('Order could not be loaded.', 'ShoppingfeedOrderSyncActions'),
'Order',
$taskOrder->id_order
);
Registry::increment('syncStatusErrors');
continue;
}

if (empty($sfOrder->id_internal_shoppingfeed)) {
ProcessLoggerHandler::logError(
$logPrefix . ' ' .
$this->l('No SF Order id set.', 'ShoppingfeedOrderSyncActions'),
'Order',
$taskOrder->id_order
);
Registry::increment('syncStatusErrors');
continue;
}

foreach ($order->getInvoicesCollection() as $invoice) {
$pdf = new PDF($invoice, PDF::TEMPLATE_INVOICE, Context::getContext()->smarty);
$file = _PS_MODULE_DIR_ . 'shoppingfeed/views/tmp/' . $invoice->id . '.pdf';
$isInvoiceExist = file_put_contents($file, $pdf->render(false));

if ($isInvoiceExist) {
$this->conveyor['preparedTaskOrders'][Shoppingfeed::ORDER_OPERATION_UPLOAD_DOCUMENTS][] = [
'id_internal_shoppingfeed' => $sfOrder->id_internal_shoppingfeed,
'taskOrder' => $taskOrder,
'file' => $file,
'operation' => Shoppingfeed::ORDER_OPERATION_UPLOAD_DOCUMENTS,
'payload' => [
'uri' => $file,
],
];
}
}
}

return true;
}

protected function initCarrierFinder()
{
return new CarrierFinder();
Expand Down Expand Up @@ -460,6 +532,71 @@ public function sendTaskOrdersSyncStatus()
return true;
}

public function sendTaskOrdersSyncInvoice()
{
if (empty($this->conveyor['id_shop'])) {
ProcessLoggerHandler::logError(
$this->l('No ID Shop found.', 'ShoppingfeedOrderSyncActions'),
'Order'
);

return false;
}

if (empty($this->conveyor['preparedTaskOrders'])) {
ProcessLoggerHandler::logError(
$this->l('No prepared Task Orders found.', 'ShoppingfeedOrderSyncActions'),
'Order'
);

return false;
}

$shoppingfeedApi = ShoppingfeedApi::getInstanceByToken($this->conveyor['id_token']);
if ($shoppingfeedApi == false) {
ProcessLoggerHandler::logError(
$this->l('Could not retrieve Shopping Feed API.', 'ShoppingfeedOrderSyncActions'),
'Order'
);

return false;
}

foreach ($this->conveyor['preparedTaskOrders'] as $preparedTaskOrders) {
$result = $shoppingfeedApi->updateMainStoreOrdersStatus($preparedTaskOrders, $this->conveyor['shoppingfeed_store_id']);

if (!$result) {
continue;
}

$batchId = current($result->getBatchIds());
if (empty($batchId) === true) {
continue;
}

foreach ($preparedTaskOrders as $preparedTaskOrder) {
$taskOrder = $preparedTaskOrder['taskOrder'];
$taskOrder->batch_id = $batchId;
$taskOrder->action = ShoppingfeedTaskOrder::ACTION_CHECK_TICKET_SYNC_STATUS;
$taskOrder->save();

ProcessLoggerHandler::logSuccess(
static::getLogPrefix($taskOrder->id_order) . ' ' . $this->l('Ticket created to upload an order invoice', 'ShoppingfeedOrderSyncActions'),
'Order',
$taskOrder->id_order
);

$this->conveyor['successfulTaskOrders'][] = $taskOrder;
unlink($preparedTaskOrder['file']);
}
}
if (empty($this->conveyor['successfulTaskOrders'])) {
return false;
}

return true;
}

public function prepareTaskOrdersCheckTicketsSyncStatus()
{
if (empty($this->conveyor['taskOrders'])) {
Expand Down
59 changes: 59 additions & 0 deletions controllers/front/syncOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,65 @@ public function syncOrderStatus()
$this->processMonitor->getProcessObjectModelId()
);
}
// Start upload invoices
ProcessLoggerHandler::logInfo(
$logPrefix . ' ' . $this->module->l('Process start : Order invoice sync', 'syncOrder'),
$this->processMonitor->getProcessObjectModelName(),
$this->processMonitor->getProcessObjectModelId()
);

$failedSyncStatusTaskOrders = [];
$successfulSyncTaskOrders = [];
try {
Registry::set('syncStatusErrors', 0);

/** @var ShoppingfeedHandler $orderStatusHandler */
$orderStatusHandler = new ActionsHandler();
$orderStatusHandler->setConveyor([
'id_shop' => $token['id_shop'],
'id_token' => $token['id_shoppingfeed_token'],
'order_action' => ShoppingfeedTaskOrder::ACTION_UPLOAD_INVOICE,
'shoppingfeed_store_id' => $token['shoppingfeed_store_id'],
]);
$orderStatusHandler->addActions(
'getTaskOrders',
'prepareTaskOrdersSyncInvoice',
'sendTaskOrdersSyncInvoice'
);

if ($orderStatusHandler->process('ShoppingfeedOrderSync')) {
$processData = $orderStatusHandler->getConveyor();
$failedSyncStatusTaskOrders = isset($processData['failedTaskOrders']) ? $processData['failedTaskOrders'] : [];
$successfulSyncTaskOrders = isset($processData['successfulTaskOrders']) ? $processData['successfulTaskOrders'] : [];

ProcessLoggerHandler::logSuccess(
sprintf(
$logPrefix . ' ' . $this->module->l('%d tickets created; %d tickets not created; %d errors', 'syncOrder'),
count($successfulSyncTaskOrders),
count($failedSyncStatusTaskOrders),
Registry::get('syncStatusErrors')
),
$this->processMonitor->getProcessObjectModelName(),
$this->processMonitor->getProcessObjectModelId()
);
}

ProcessLoggerHandler::logInfo(
$logPrefix . ' ' . $this->module->l('Process finished : Order invoice sync', 'syncOrder'),
$this->processMonitor->getProcessObjectModelName(),
$this->processMonitor->getProcessObjectModelId()
);
} catch (Throwable $e) {
ProcessLoggerHandler::logError(
sprintf(
$logPrefix . ' ' . $this->module->l('Error : %s', 'syncOrder'),
$e->getMessage() . ' ' . $e->getFile() . ':' . $e->getLine()
),
$this->processMonitor->getProcessObjectModelName(),
$this->processMonitor->getProcessObjectModelId()
);
}
// End upload invoices

// Send mail
try {
Expand Down
82 changes: 44 additions & 38 deletions shoppingfeed.php
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,41 @@ public function hookActionValidateOrder($params)
\ShoppingfeedClasslib\Extensions\ProcessLogger\ProcessLoggerHandler::closeLogger();
}

protected function addOrderTask($id_order, $action)
{
$logPrefix = ShoppingfeedOrderSyncActions::getLogPrefix($id_order);
try {
\ShoppingfeedClasslib\Extensions\ProcessLogger\ProcessLoggerHandler::logInfo(
sprintf(
$logPrefix . ' ' .
$this->l('Process started Order %s ', 'ShoppingfeedOrderActions'),
$id_order
),
'Order',
$id_order
);
$handler = new \ShoppingfeedClasslib\Actions\ActionsHandler();
$handler
->setConveyor([
'id_order' => $id_order,
'order_action' => $action,
])
->addActions('saveTaskOrder')
->process('shoppingfeedOrderSync');
} catch (Exception $e) {
\ShoppingfeedClasslib\Extensions\ProcessLogger\ProcessLoggerHandler::logInfo(
sprintf(
$logPrefix . ' ' . $this->l('Order %s not registered for synchronization: %s', 'ShoppingfeedOrderActions'),
$id_order,
$e->getMessage() . ' ' . $e->getFile() . ':' . $e->getLine()
),
'Order',
$id_order
);
}
\ShoppingfeedClasslib\Extensions\ProcessLogger\ProcessLoggerHandler::closeLogger();
}

/**
* Saves an order for status synchronization
*
Expand All @@ -1265,53 +1300,24 @@ public function hookActionOrderStatusPostUpdate($params)
}

$order = new Order($params['id_order']);

// Check if the new status calls for an update with Shopping Feed
/** @var OrderState $newOrderStatus */
$newOrderStatus = $params['newOrderStatus'];
$shipped_status = json_decode(Configuration::get(Shoppingfeed::SHIPPED_ORDERS, null, null, $order->id_shop));
$cancelled_status = json_decode(Configuration::get(Shoppingfeed::CANCELLED_ORDERS, null, null, $order->id_shop));
$refunded_status = json_decode(Configuration::get(Shoppingfeed::REFUNDED_ORDERS, null, null, $order->id_shop));
$delivered_status = json_decode(Configuration::get(Shoppingfeed::DELIVERED_ORDERS, null, null, $order->id_shop));
if (!in_array($newOrderStatus->id, $shipped_status)
&& !in_array($newOrderStatus->id, $cancelled_status)
&& !in_array($newOrderStatus->id, $refunded_status)
&& !in_array($newOrderStatus->id, $delivered_status)

if (in_array($newOrderStatus->id, $shipped_status)
|| in_array($newOrderStatus->id, $cancelled_status)
|| in_array($newOrderStatus->id, $refunded_status)
|| in_array($newOrderStatus->id, $delivered_status)
) {
return;
$this->addOrderTask($shoppingFeedOrder->id_order, ShoppingfeedTaskOrder::ACTION_SYNC_STATUS);
}

$logPrefix = ShoppingfeedOrderSyncActions::getLogPrefix($shoppingFeedOrder->id_order);
try {
\ShoppingfeedClasslib\Extensions\ProcessLogger\ProcessLoggerHandler::logInfo(
sprintf(
$logPrefix . ' ' .
$this->l('Process started Order %s ', 'ShoppingfeedOrderActions'),
$shoppingFeedOrder->id_order
),
'Order',
$shoppingFeedOrder->id_order
);
$handler = new \ShoppingfeedClasslib\Actions\ActionsHandler();
$handler
->setConveyor([
'id_order' => $params['id_order'],
'order_action' => ShoppingfeedTaskOrder::ACTION_SYNC_STATUS,
])
->addActions('saveTaskOrder')
->process('shoppingfeedOrderSync');
} catch (Exception $e) {
\ShoppingfeedClasslib\Extensions\ProcessLogger\ProcessLoggerHandler::logInfo(
sprintf(
$logPrefix . ' ' . $this->l('Order %s not registered for synchronization: %s', 'ShoppingfeedOrderActions'),
$params['id_order'],
$e->getMessage() . ' ' . $e->getFile() . ':' . $e->getLine()
),
'Order',
$params['id_order']
);
if ($newOrderStatus->invoice) {
$this->addOrderTask($shoppingFeedOrder->id_order, ShoppingfeedTaskOrder::ACTION_UPLOAD_INVOICE);
}

\ShoppingfeedClasslib\Extensions\ProcessLogger\ProcessLoggerHandler::closeLogger();
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/OrderInvoiceSync/Hub.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,4 @@ protected function update()
json_encode($settings)
);
}
}
}
2 changes: 1 addition & 1 deletion src/OrderInvoiceSync/Marketplace.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ public function isEnabled()
{
return $this->isEnabled;
}
}
}
31 changes: 31 additions & 0 deletions upgrade/install-2.0.0.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php
/**
* Copyright since 2019 Shopping Feed
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @author 202 ecommerce <[email protected]>
* @copyright Since 2019 Shopping Feed
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License (AFL 3.0)
*/

use ShoppingfeedClasslib\Install\ModuleInstaller;

function upgrade_module_2_0_0($module)
{
/**
* @var Shoppingfeed $module
*/
$installer = new ModuleInstaller($module);
$installer->installObjectModel(ShoppingfeedToken::class);

return true;
}
Loading

0 comments on commit ec70941

Please sign in to comment.