Skip to content

Commit

Permalink
Merge pull request #1 from forter/v1.0.1
Browse files Browse the repository at this point in the history
v1.0.1: Added forter:historical-data-upload CLI command
  • Loading branch information
pniel-cohen authored Jan 30, 2024
2 parents 009cf1b + 08efc94 commit e120efd
Show file tree
Hide file tree
Showing 12 changed files with 266 additions and 28 deletions.
199 changes: 199 additions & 0 deletions app/Console/Commands/ForterHistoricalDataUpload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
<?php
/**
* Forter Commercetools app
*
* @package Forter Commercetools app
* @author Forter (https://www.forter.com/)
* @author Developer: Pniel Cohen (Trus)
*/

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use App\Helpers\UtilsHelper;
use App\Models\Forter\ForterOrder;
use App\Services\Commercetools\CommercetoolsOrdersService;
use App\Services\Forter\SchemaBuilders\ForterSchemaBuilder;

class ForterHistoricalDataUpload extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'forter:historical-data-upload';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Generates historical orders data for upload to Forter, in order to optimize the model\'s accuracy.';

/**
* Progress bar
*/
private $progressBar;

/**
* @method createProgressBar
* @param integer $maxNumberOfTasks
* @return void
*/
protected function createProgressBar($maxNumberOfTasks = 0)
{
$this->progressBar = $this->output->createProgressBar($maxNumberOfTasks);
}

protected function advanceProgressBar()
{
$this->progressBar->advance();
}

protected function lineSepartor()
{
$this->newLine();
$this->line('------------------------------------------');
$this->newLine();
}

/**
* Execute the console command.
*/
public function handle()
{
try {
Log::info("[Commands\ForterHistoricalDataUpload::handle] [START]");

$this->printHeading();

$filename = 'historical-data_generated-on-' . Carbon::now()->format('Y-m-d') . '.jsonl';
// Delete previously generated file.
Storage::disk('local_forter')->delete($filename);

$expand = ['paymentInfo.payments[*]', 'cart'];
$fromDate = Carbon::now()->subMonths(12)->format('Y-m-d\TH:i:s.000\Z');

// Check how many historical orders exists
$request = CommercetoolsOrdersService::get(null, 1, true);
$request = $request->withWhere(sprintf('createdAt > "%s"', $fromDate));
$totalOrders = $request->execute()->getTotal();
$this->comment("Found {$totalOrders} orders.");

// If found orders
if ($totalOrders) {
$this->comment("Processing...");
$this->createProgressBar($totalOrders);

$bulkLimit = 100;
$lastId = null;
$continue = true;
$skippedAlreadySent = [];
$prepared = [];

while ($continue) {
sleep(1);

if ($lastId === null) {
$request = CommercetoolsOrdersService::get($expand, $bulkLimit, true);
$request = $request
->withSort('id asc')
->withWithTotal('false')
->withWhere(sprintf('createdAt > "%s"', $fromDate));
} else {
$request = CommercetoolsOrdersService::get($expand, $bulkLimit, true);
$request = $request
->withSort('id asc')
->withWithTotal('false')
->withWhere(sprintf('createdAt > "%s" and id > "%s"', $fromDate, $lastId));
}

$response = $request->execute();
$results = $response->getResults();
$continue = $response->getCount() == $bulkLimit;

if (!empty($results)) {
$lastId = $results->end()->getId();

foreach ($results as $order) {
try {
//$this->line(" Preparing Commercetools order ID: {$order->getId()}");
$orderModel = ForterOrder::getInstance($order);
if (!empty($orderModel->getForterResponse())) {
$skippedAlreadySent[] = $order->getId();
} else {
$orderSchema = ForterSchemaBuilder::buildHistoricalOrderSchema($orderModel);
$jsonLine = \json_encode($orderSchema);
if (! Storage::disk('local_forter')->append($filename, $jsonLine)) {
throw new \Exception("Couldn't write data to local file ('forter/{$filename}')");
}
$prepared[] = $order->getId();
}
} catch (\Exception $e) {
$this->error(" [ERROR] " . $e->getMessage());
Log::error("[Commands\ForterHistoricalDataUpload::handle] [ERROR] while preparing order (ID) {$order->getId()} | " . $e->getMessage(), ['exception' => $e]);
}

$this->advanceProgressBar();
//$this->newLine();
}
}
}

$this->newLine();

if ($skippedAlreadySent) {
$this->lineSepartor();
$this->comment("Some of the orders have already been sent to the Forter and therefore have been skipped:");
$this->line(implode(',', $skippedAlreadySent));
}

$this->lineSepartor();

if (Storage::disk('local_forter')->exists($filename) && $prepared) {
$this->comment("Orders on file: " . count($prepared));
$this->newLine();

$this->info("The file in ready and can be found on: " . Storage::disk('local_forter')->path($filename));
$this->info("Please proceed by uploading it manually to your dedicated folder on Forter's AWS (as instructed on your Forter Portal)");
} else {
$this->comment("No file has been created.");
}
}

// Setup Completed
$this->printEnding();

Log::info("[Commands\ForterHistoricalDataUpload::handle] [END]");
} catch (\Exception $e) {
Log::error("[Commands\ForterHistoricalDataUpload::handle] [ERROR] " . $e->getMessage(), ['exception' => $e]);
if ($filename && Storage::disk('local_forter')->exists($filename)) {
Storage::disk('local_forter')->delete($filename);
}

throw $e;
}
}

protected function printHeading()
{
$this->newLine();
$this->info("***********************************************************");
$this->info("*** Forter Commercetools App - Historical Data Upload ***");
$this->info("***********************************************************");
$this->newLine(2);
}

protected function printEnding()
{
$this->newLine();
$this->info("***************************************************************");
$this->info("*** Forter historical data upload completed successfully! ***");
$this->info("***************************************************************");
$this->newLine(2);
}
}
12 changes: 12 additions & 0 deletions app/Models/Forter/ForterOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,18 @@ public function getTaxedPriceTotalGross($field)
return isset($this->_data['taxedPrice']['totalGross']) ? $this->_data['taxedPrice']['totalGross'] : [];
}

/**
* @method getTotalPrice
* @return mixed
*/
public function getTotalPrice($field)
{
if ($field) {
return isset($this->_data['totalPrice'][$field]) ? $this->_data['totalPrice'][$field] : null;
}
return isset($this->_data['totalPrice']) ? $this->_data['totalPrice'] : [];
}

/**
* @method getShippingInfo
* @return mixed
Expand Down
4 changes: 2 additions & 2 deletions app/Services/Commercetools/CommercetoolsCartsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

class CommercetoolsCartsService extends CommercetoolsClientService
{
public static function getAll($expand = null, $limit = null)
public static function get($expand = null, $limit = null)
{
$request = parent::getApiClientBuilder()
->carts()->get();
Expand All @@ -32,7 +32,7 @@ public static function getAll($expand = null, $limit = null)
}

if ($limit) {
$request = $request->withLimit(1);
$request = $request->withLimit($limit);
}

return $request->execute();
Expand Down
4 changes: 2 additions & 2 deletions app/Services/Commercetools/CommercetoolsExtensionsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

class CommercetoolsExtensionsService extends CommercetoolsClientService
{
public static function getAll($expand = null, $limit = null)
public static function get($expand = null, $limit = null)
{
$request = parent::getApiClientBuilder()
->extensions()->get();
Expand All @@ -36,7 +36,7 @@ public static function getAll($expand = null, $limit = null)
}

if ($limit) {
$request = $request->withLimit(1);
$request = $request->withLimit($limit);
}

return $request->execute();
Expand Down
20 changes: 10 additions & 10 deletions app/Services/Commercetools/CommercetoolsOrdersService.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace App\Services\Commercetools;

use Illuminate\Support\Carbon;
use Commercetools\Api\Models\Order\OrderFromCartDraftBuilder;
use Commercetools\Api\Models\Order\OrderSetCustomTypeActionBuilder;
use Commercetools\Api\Models\Order\OrderUpdateActionBuilder;
Expand All @@ -22,7 +23,7 @@

class CommercetoolsOrdersService extends CommercetoolsClientService
{
public static function getAll($expand = null, $limit = null)
public static function get($expand = null, $limit = null, $returnBuilder = false)
{
$request = parent::getApiClientBuilder()
->orders()->get();
Expand All @@ -32,7 +33,11 @@ public static function getAll($expand = null, $limit = null)
}

if ($limit) {
$request = $request->withLimit(1);
$request = $request->withLimit($limit);
}

if ($returnBuilder) {
return $request;
}

return $request->execute();
Expand Down Expand Up @@ -64,15 +69,10 @@ public static function getByOrderNumber($orderNumber, $expand = null)

public static function getOrderByPaymentId($paymentId, $expand = null)
{
$request = parent::getApiClientBuilder()
->orders()->get()
$request = self::get($expand, 1, true);
$request = $request
->withWhere('paymentInfo(payments(id=:paymentId))')
->withPredicateVar("paymentId", $paymentId)
->withLimit(1);

if ($expand) {
$request = $request->withExpand($expand);
}
->withPredicateVar("paymentId", $paymentId);

$results = $request->execute()->getResults();
return !empty($results) ? $results[0] : false;
Expand Down
4 changes: 2 additions & 2 deletions app/Services/Commercetools/CommercetoolsPaymentsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

class CommercetoolsPaymentsService extends CommercetoolsClientService
{
public static function getAll($expand = null, $limit = null)
public static function get($expand = null, $limit = null)
{
$request = parent::getApiClientBuilder()
->payments()->get();
Expand All @@ -39,7 +39,7 @@ public static function getAll($expand = null, $limit = null)
}

if ($limit) {
$request = $request->withLimit(1);
$request = $request->withLimit($limit);
}

return $request->execute();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

class CommercetoolsSubscriptionsService extends CommercetoolsClientService
{
public static function getAll($expand = null, $limit = null)
public static function get($expand = null, $limit = null)
{
$request = parent::getApiClientBuilder()
->subscriptions()->get();
Expand All @@ -39,7 +39,7 @@ public static function getAll($expand = null, $limit = null)
}

if ($limit) {
$request = $request->withLimit(1);
$request = $request->withLimit($limit);
}

return $request->execute();
Expand Down
4 changes: 2 additions & 2 deletions app/Services/Commercetools/CommercetoolsTypesService.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

class CommercetoolsTypesService extends CommercetoolsClientService
{
public static function getAll($expand = null, $limit = null)
public static function get($expand = null, $limit = null)
{
$request = parent::getApiClientBuilder()
->types()->get();
Expand All @@ -38,7 +38,7 @@ public static function getAll($expand = null, $limit = null)
}

if ($limit) {
$request = $request->withLimit(1);
$request = $request->withLimit($limit);
}

return $request->execute();
Expand Down
12 changes: 6 additions & 6 deletions app/Services/Forter/ForterSetupService.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,12 @@ public static function isValidCommercetoolsCredentials()
throw new \Exception("Missing required Commercetools config value: `{$configKey}`");
}
}
$orders = CommercetoolsOrdersService::getAll(null, 1)->getCount();
$carts = CommercetoolsCartsService::getAll(null, 1)->getCount();
$payments = CommercetoolsPaymentsService::getAll(null, 1)->getCount();
$types = CommercetoolsTypesService::getAll(null, 1)->getCount();
$extensions = CommercetoolsExtensionsService::getAll(null, 1)->getCount();
$subscriptions = CommercetoolsSubscriptionsService::getAll(null, 1)->getCount();
$orders = CommercetoolsOrdersService::get(null, 1)->getCount();
$carts = CommercetoolsCartsService::get(null, 1)->getCount();
$payments = CommercetoolsPaymentsService::get(null, 1)->getCount();
$types = CommercetoolsTypesService::get(null, 1)->getCount();
$extensions = CommercetoolsExtensionsService::get(null, 1)->getCount();
$subscriptions = CommercetoolsSubscriptionsService::get(null, 1)->getCount();
return true;
} catch (\Exception $e) {
Log::error("[ForterSetupService::isValidCommercetoolsCredentials] [ERROR] " . $e->getMessage(), ['exception' => $e]);
Expand Down
Loading

0 comments on commit e120efd

Please sign in to comment.