MigrateAsteriaOrders.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\Asteria\Magento1OrderReader;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Collection;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use Illuminate\Support\Facades\Schema;
  10. use Webkul\Core\Models\Channel;
  11. use Webkul\Customer\Models\Customer;
  12. use Webkul\Product\Models\Product;
  13. use Webkul\Sales\Models\Order;
  14. use Webkul\Sales\Models\OrderAddress;
  15. /**
  16. * Migrates storefront orders from Asteria (Magento 1.x).
  17. *
  18. * Does not create invoices/shipments/refunds, does not decrement inventory,
  19. * and does not fire checkout.order.save.after listeners.
  20. *
  21. * Usage
  22. * ─────
  23. * php artisan orders:migrate-asteria
  24. * php artisan orders:migrate-asteria --batch-size=200
  25. * php artisan orders:migrate-asteria --reset-progress
  26. * php artisan orders:migrate-asteria --dry-run
  27. */
  28. class MigrateAsteriaOrders extends Command
  29. {
  30. protected $signature = 'orders:migrate-asteria
  31. {--batch-size=500 : Number of Magento orders per batch}
  32. {--reset-progress : Ignore saved progress and start from entity_id=0}
  33. {--dry-run : Count records without writing}
  34. {--connection=asteria : Laravel DB connection for the Asteria database}';
  35. protected $description = 'Migrate Asteria (Magento 1.x) orders into Bagisto';
  36. private const PROGRESS_KEY = 'migrate_asteria_orders_last_id';
  37. private const BAGISTO_PRODUCT_TYPES = [
  38. 'simple',
  39. 'configurable',
  40. 'virtual',
  41. 'downloadable',
  42. 'bundle',
  43. 'grouped',
  44. ];
  45. private const INSERT_CHUNK = 200;
  46. /** @var array<string, bool>|null */
  47. private ?array $destinationOrderColumns = null;
  48. public function handle(): int
  49. {
  50. $connection = (string) $this->option('connection');
  51. $batchSize = max(1, (int) $this->option('batch-size'));
  52. $resetProgress = (bool) $this->option('reset-progress');
  53. $dryRun = (bool) $this->option('dry-run');
  54. DB::disableQueryLog();
  55. try {
  56. DB::connection($connection)->getPdo();
  57. } catch (\Throwable $e) {
  58. $this->error("Cannot connect to Asteria DB (connection='{$connection}'): ".$e->getMessage());
  59. return self::FAILURE;
  60. }
  61. foreach ([
  62. 'sales_flat_order',
  63. 'sales_flat_order_item',
  64. 'sales_flat_order_address',
  65. 'sales_flat_order_payment',
  66. ] as $table) {
  67. if (! Schema::connection($connection)->hasTable($table)) {
  68. $this->error("Asteria table '{$table}' is missing on connection '{$connection}'.");
  69. return self::FAILURE;
  70. }
  71. }
  72. if (! Schema::hasColumn('orders', 'migrated_from_asteria_id')) {
  73. $this->error('orders.migrated_from_asteria_id is missing. Run php artisan migrate.');
  74. return self::FAILURE;
  75. }
  76. if (! Schema::hasColumn('orders', 'reward_points_used')) {
  77. $this->warn('orders.reward_points_used is missing. Run php artisan migrate to import order reward points.');
  78. }
  79. if (! Schema::hasColumn('orders', 'shipping_insurance_amount')) {
  80. $this->warn('orders.shipping_insurance_amount is missing. Run php artisan migrate to import lost-package insurance.');
  81. }
  82. $channel = core()->getDefaultChannel() ?? core()->getCurrentChannel();
  83. if (! $channel) {
  84. $this->error('Bagisto default channel was not found.');
  85. return self::FAILURE;
  86. }
  87. $reader = new Magento1OrderReader($connection);
  88. $lastId = $resetProgress ? 0 : (int) Cache::get(self::PROGRESS_KEY, 0);
  89. if ($resetProgress) {
  90. Cache::forget(self::PROGRESS_KEY);
  91. }
  92. if ($lastId > 0) {
  93. $this->line("Resuming from Asteria entity_id > {$lastId} (use --reset-progress to restart).");
  94. }
  95. $created = 0;
  96. $skipped = 0;
  97. $itemsImported = 0;
  98. $addressesImported = 0;
  99. $batchNumber = 0;
  100. $this->info($dryRun ? '[DRY RUN] Scanning Magento orders…' : 'Migrating Magento orders…');
  101. do {
  102. $started = microtime(true);
  103. $orders = $reader->fetchOrders($lastId, $batchSize);
  104. if ($orders->isEmpty()) {
  105. break;
  106. }
  107. $batchNumber++;
  108. $lastId = (int) $orders->max('entity_id');
  109. $orderIds = $orders->pluck('entity_id')->map(fn ($id) => (int) $id)->all();
  110. $items = $reader->fetchItems($orderIds)->groupBy(fn (array $row) => (int) $row['order_id']);
  111. $addresses = $reader->fetchAddresses($orderIds)->groupBy(fn (array $row) => (int) $row['parent_id']);
  112. $payments = $reader->fetchPayments($orderIds)->groupBy(fn (array $row) => (int) $row['parent_id']);
  113. $rewardPoints = $reader->fetchRewardPoints($orderIds)->keyBy(fn (array $row) => (int) $row['order_id']);
  114. if ($dryRun) {
  115. $created += $orders->count();
  116. $itemsImported += $items->flatten(1)->count();
  117. $addressesImported += $addresses->flatten(1)->count();
  118. $this->line(sprintf(
  119. ' Batch #%d: %d orders, %d items, %d addresses (last entity_id=%d) [skipped – dry-run] (%.1fs)',
  120. $batchNumber,
  121. $orders->count(),
  122. $items->flatten(1)->count(),
  123. $addresses->flatten(1)->count(),
  124. $lastId,
  125. microtime(true) - $started
  126. ));
  127. continue;
  128. }
  129. [$customersByAsteriaId, $customersByEmail] = $this->loadCustomers($orders);
  130. $productsBySku = $this->loadProducts($items);
  131. $result = $this->persistBatch(
  132. $orders,
  133. $items,
  134. $addresses,
  135. $payments,
  136. $rewardPoints,
  137. $channel,
  138. $customersByAsteriaId,
  139. $customersByEmail,
  140. $productsBySku
  141. );
  142. Cache::put(self::PROGRESS_KEY, $lastId, now()->addDays(30));
  143. $created += $result['created'];
  144. $skipped += $result['skipped'];
  145. $itemsImported += $result['items'];
  146. $addressesImported += $result['addresses'];
  147. $this->line(sprintf(
  148. ' Batch #%d: created=%d skipped=%d items=%d addresses=%d (last entity_id=%d) (%.1fs)',
  149. $batchNumber,
  150. $result['created'],
  151. $result['skipped'],
  152. $result['items'],
  153. $result['addresses'],
  154. $lastId,
  155. microtime(true) - $started
  156. ));
  157. Log::info('MigrateAsteriaOrders: batch '.$batchNumber.', last_id='.$lastId);
  158. } while ($orders->count() === $batchSize);
  159. $this->newLine();
  160. $this->info("Done. Batches: {$batchNumber}, created: {$created}, skipped: {$skipped}, items: {$itemsImported}, addresses: {$addressesImported}.");
  161. return self::SUCCESS;
  162. }
  163. /**
  164. * @param Collection<int, array<string, mixed>> $orders
  165. * @param Collection<int, Collection<int, array<string, mixed>>> $items
  166. * @param Collection<int, Collection<int, array<string, mixed>>> $addresses
  167. * @param Collection<int, Collection<int, array<string, mixed>>> $payments
  168. * @param Collection<int, array<string, mixed>> $rewardPoints
  169. * @param array<int, Customer> $customersByAsteriaId
  170. * @param array<string, Customer> $customersByEmail
  171. * @param array<string, Product> $productsBySku
  172. * @return array{created: int, skipped: int, items: int, addresses: int}
  173. */
  174. private function persistBatch(
  175. Collection $orders,
  176. Collection $items,
  177. Collection $addresses,
  178. Collection $payments,
  179. Collection $rewardPoints,
  180. Channel $channel,
  181. array $customersByAsteriaId,
  182. array $customersByEmail,
  183. array $productsBySku
  184. ): array {
  185. $asteriaIds = $orders->pluck('entity_id')->map(fn ($id) => (int) $id)->filter()->unique()->values()->all();
  186. $incrementIds = $orders
  187. ->pluck('increment_id')
  188. ->map(fn ($id) => trim((string) $id))
  189. ->filter()
  190. ->unique()
  191. ->values()
  192. ->all();
  193. $existingAsteria = $asteriaIds === []
  194. ? []
  195. : DB::table('orders')
  196. ->whereIn('migrated_from_asteria_id', $asteriaIds)
  197. ->pluck('migrated_from_asteria_id')
  198. ->map(fn ($id) => (int) $id)
  199. ->flip()
  200. ->all();
  201. $existingIncrements = $incrementIds === []
  202. ? []
  203. : DB::table('orders')
  204. ->whereIn('increment_id', $incrementIds)
  205. ->pluck('increment_id')
  206. ->map(fn ($id) => (string) $id)
  207. ->flip()
  208. ->all();
  209. $now = now()->format('Y-m-d H:i:s');
  210. $orderInserts = [];
  211. $pending = [];
  212. $skipped = 0;
  213. $seenIncrements = [];
  214. foreach ($orders as $row) {
  215. $asteriaId = (int) $row['entity_id'];
  216. $incrementId = trim((string) ($row['increment_id'] ?? ''));
  217. if ($asteriaId < 1 || $incrementId === ''
  218. || isset($existingAsteria[$asteriaId])
  219. || isset($existingIncrements[$incrementId])
  220. || isset($seenIncrements[$incrementId])) {
  221. $skipped++;
  222. continue;
  223. }
  224. $seenIncrements[$incrementId] = true;
  225. $orderInserts[] = $this->buildOrderRow(
  226. $row,
  227. $channel,
  228. $customersByAsteriaId,
  229. $customersByEmail,
  230. $items->get($asteriaId, collect()),
  231. $rewardPoints->get($asteriaId),
  232. $now
  233. );
  234. $pending[] = $row;
  235. }
  236. $created = count($orderInserts);
  237. $importedItems = 0;
  238. $importedAddresses = 0;
  239. if ($orderInserts === []) {
  240. return ['created' => 0, 'skipped' => $skipped, 'items' => 0, 'addresses' => 0];
  241. }
  242. DB::transaction(function () use (
  243. $orderInserts,
  244. $pending,
  245. $items,
  246. $addresses,
  247. $payments,
  248. $productsBySku,
  249. $customersByAsteriaId,
  250. $customersByEmail,
  251. &$importedItems,
  252. &$importedAddresses
  253. ) {
  254. $this->insertRows('orders', $orderInserts);
  255. $idMap = DB::table('orders')
  256. ->whereIn('migrated_from_asteria_id', array_column($orderInserts, 'migrated_from_asteria_id'))
  257. ->pluck('id', 'migrated_from_asteria_id')
  258. ->mapWithKeys(fn ($id, $asteriaId) => [(int) $asteriaId => (int) $id])
  259. ->all();
  260. $paymentInserts = [];
  261. $addressInserts = [];
  262. $parentItemInserts = [];
  263. $childItemRows = [];
  264. $now = now()->format('Y-m-d H:i:s');
  265. foreach ($pending as $row) {
  266. $asteriaId = (int) $row['entity_id'];
  267. $orderId = $idMap[$asteriaId] ?? null;
  268. if (! $orderId) {
  269. continue;
  270. }
  271. $customer = $this->resolveCustomer($row, $customersByAsteriaId, $customersByEmail);
  272. $email = strtolower(trim((string) ($row['customer_email'] ?? '')));
  273. if ($email === '' && $customer) {
  274. $email = strtolower((string) $customer->email);
  275. }
  276. $paymentInserts[] = $this->buildPaymentRow($orderId, $payments->get($asteriaId, collect())->first(), $now);
  277. foreach ($addresses->get($asteriaId, collect()) as $addressRow) {
  278. $addressInserts[] = $this->buildAddressRow($orderId, $addressRow, $customer, $email, $row, $now);
  279. $importedAddresses++;
  280. }
  281. $itemRows = $items->get($asteriaId, collect());
  282. $parents = $itemRows->filter(fn (array $item) => empty($item['parent_item_id']));
  283. $children = $itemRows->filter(fn (array $item) => ! empty($item['parent_item_id']));
  284. foreach ($parents as $itemRow) {
  285. $parentItemInserts[] = $this->buildItemRow($orderId, $itemRow, null, $productsBySku, $now);
  286. $importedItems++;
  287. }
  288. foreach ($children as $itemRow) {
  289. $childItemRows[] = ['order_id' => $orderId, 'row' => $itemRow];
  290. $importedItems++;
  291. }
  292. }
  293. if ($paymentInserts !== []) {
  294. $this->insertRows('order_payment', $paymentInserts);
  295. }
  296. if ($addressInserts !== []) {
  297. $this->insertRows('addresses', $addressInserts);
  298. }
  299. if ($parentItemInserts !== []) {
  300. $this->insertRows('order_items', $parentItemInserts);
  301. }
  302. if ($childItemRows !== []) {
  303. $itemIdMap = $this->loadInsertedItemIds(array_values($idMap));
  304. $childInserts = [];
  305. foreach ($childItemRows as $child) {
  306. $parentId = $itemIdMap[(int) $child['row']['parent_item_id']] ?? null;
  307. $childInserts[] = $this->buildItemRow($child['order_id'], $child['row'], $parentId, $productsBySku, $now);
  308. }
  309. $this->insertRows('order_items', $childInserts);
  310. }
  311. });
  312. return [
  313. 'created' => $created,
  314. 'skipped' => $skipped,
  315. 'items' => $importedItems,
  316. 'addresses' => $importedAddresses,
  317. ];
  318. }
  319. /**
  320. * @param array<string, mixed> $row
  321. * @param array<int, Customer> $customersByAsteriaId
  322. * @param array<string, Customer> $customersByEmail
  323. * @param Collection<int, array<string, mixed>> $itemRows
  324. * @param array<string, mixed>|null $rewardRow
  325. * @return array<string, mixed>
  326. */
  327. private function buildOrderRow(
  328. array $row,
  329. Channel $channel,
  330. array $customersByAsteriaId,
  331. array $customersByEmail,
  332. $itemRows,
  333. ?array $rewardRow,
  334. string $now
  335. ): array {
  336. $customer = $this->resolveCustomer($row, $customersByAsteriaId, $customersByEmail);
  337. $email = strtolower(trim((string) ($row['customer_email'] ?? '')));
  338. if ($email === '' && $customer) {
  339. $email = strtolower((string) $customer->email);
  340. }
  341. $subTotal = $this->money($row['subtotal'] ?? 0);
  342. $baseSubTotal = $this->money($row['base_subtotal'] ?? $subTotal);
  343. $taxAmount = $this->money($row['tax_amount'] ?? 0);
  344. $baseTaxAmount = $this->money($row['base_tax_amount'] ?? $taxAmount);
  345. $shippingAmount = $this->money($row['shipping_amount'] ?? 0);
  346. $baseShippingAmount = $this->money($row['base_shipping_amount'] ?? $shippingAmount);
  347. $shippingTaxAmount = $this->money($row['shipping_tax_amount'] ?? 0);
  348. $baseShippingTaxAmount = $this->money($row['base_shipping_tax_amount'] ?? $shippingTaxAmount);
  349. $discountAmount = $this->money($row['discount_amount'] ?? 0);
  350. $baseDiscountAmount = $this->money($row['base_discount_amount'] ?? $discountAmount);
  351. $grandTotal = $this->money($row['grand_total'] ?? 0);
  352. $baseGrandTotal = $this->money($row['base_grand_total'] ?? $grandTotal);
  353. $subTotalInclTax = array_key_exists('subtotal_incl_tax', $row)
  354. ? $this->money($row['subtotal_incl_tax'])
  355. : $subTotal + $taxAmount;
  356. $baseSubTotalInclTax = array_key_exists('base_subtotal_incl_tax', $row)
  357. ? $this->money($row['base_subtotal_incl_tax'])
  358. : $baseSubTotal + $baseTaxAmount;
  359. $shippingInclTax = array_key_exists('shipping_incl_tax', $row)
  360. ? $this->money($row['shipping_incl_tax'])
  361. : $shippingAmount + $shippingTaxAmount;
  362. $baseShippingInclTax = array_key_exists('base_shipping_incl_tax', $row)
  363. ? $this->money($row['base_shipping_incl_tax'])
  364. : $baseShippingAmount + $baseShippingTaxAmount;
  365. $insert = [
  366. 'migrated_from_asteria_id' => (int) $row['entity_id'],
  367. 'increment_id' => trim((string) $row['increment_id']),
  368. 'status' => $this->mapStatus($row),
  369. 'channel_name' => $channel->name,
  370. 'is_guest' => $customer ? 0 : 1,
  371. 'customer_email' => $email !== '' ? $email : null,
  372. 'customer_first_name' => $this->requiredName($row['customer_firstname'] ?? null, $customer?->first_name ?? $email),
  373. 'customer_last_name' => trim((string) ($row['customer_lastname'] ?? '')) ?: ($customer?->last_name ?? '-'),
  374. 'customer_id' => $customer?->id,
  375. 'customer_type' => $customer ? Customer::class : null,
  376. 'channel_id' => $channel->id,
  377. 'channel_type' => get_class($channel),
  378. 'cart_id' => null,
  379. 'shipping_method' => $this->nullableString($row['shipping_method'] ?? null),
  380. 'shipping_title' => $this->nullableString($row['shipping_description'] ?? null),
  381. 'shipping_description' => $this->nullableString($row['shipping_description'] ?? null),
  382. 'coupon_code' => $this->nullableString($row['coupon_code'] ?? null),
  383. 'is_gift' => 0,
  384. 'total_item_count' => $this->qty($row['total_item_count'] ?? $itemRows->count()),
  385. 'total_qty_ordered' => $this->qty($row['total_qty_ordered'] ?? $itemRows->sum(fn (array $item) => (float) ($item['qty_ordered'] ?? 0))),
  386. 'base_currency_code' => $this->nullableString($row['base_currency_code'] ?? null) ?? 'USD',
  387. 'channel_currency_code' => $this->nullableString($row['store_currency_code'] ?? null)
  388. ?? $this->nullableString($row['order_currency_code'] ?? null)
  389. ?? 'USD',
  390. 'order_currency_code' => $this->nullableString($row['order_currency_code'] ?? null) ?? 'USD',
  391. 'grand_total' => $grandTotal,
  392. 'base_grand_total' => $baseGrandTotal,
  393. 'grand_total_invoiced' => $this->money($row['total_invoiced'] ?? 0),
  394. 'base_grand_total_invoiced' => $this->money($row['base_total_invoiced'] ?? 0),
  395. 'grand_total_refunded' => $this->money($row['total_refunded'] ?? 0),
  396. 'base_grand_total_refunded' => $this->money($row['base_total_refunded'] ?? 0),
  397. 'sub_total' => $subTotal,
  398. 'base_sub_total' => $baseSubTotal,
  399. 'sub_total_incl_tax' => $subTotalInclTax,
  400. 'base_sub_total_incl_tax' => $baseSubTotalInclTax,
  401. 'sub_total_invoiced' => $this->money($row['subtotal_invoiced'] ?? 0),
  402. 'base_sub_total_invoiced' => $this->money($row['base_subtotal_invoiced'] ?? 0),
  403. 'sub_total_refunded' => $this->money($row['subtotal_refunded'] ?? 0),
  404. 'base_sub_total_refunded' => $this->money($row['base_subtotal_refunded'] ?? 0),
  405. 'discount_amount' => $discountAmount,
  406. 'base_discount_amount' => $baseDiscountAmount,
  407. 'discount_invoiced' => $this->money($row['discount_invoiced'] ?? 0),
  408. 'base_discount_invoiced' => $this->money($row['base_discount_invoiced'] ?? 0),
  409. 'discount_refunded' => $this->money($row['discount_refunded'] ?? 0),
  410. 'base_discount_refunded' => $this->money($row['base_discount_refunded'] ?? 0),
  411. 'tax_amount' => $taxAmount,
  412. 'base_tax_amount' => $baseTaxAmount,
  413. 'tax_amount_invoiced' => $this->money($row['tax_invoiced'] ?? 0),
  414. 'base_tax_amount_invoiced' => $this->money($row['base_tax_invoiced'] ?? 0),
  415. 'tax_amount_refunded' => $this->money($row['tax_refunded'] ?? 0),
  416. 'base_tax_amount_refunded' => $this->money($row['base_tax_refunded'] ?? 0),
  417. 'shipping_amount' => $shippingAmount,
  418. 'base_shipping_amount' => $baseShippingAmount,
  419. 'shipping_amount_incl_tax' => $shippingInclTax,
  420. 'base_shipping_amount_incl_tax' => $baseShippingInclTax,
  421. 'shipping_invoiced' => $this->money($row['shipping_invoiced'] ?? 0),
  422. 'base_shipping_invoiced' => $this->money($row['base_shipping_invoiced'] ?? 0),
  423. 'shipping_refunded' => $this->money($row['shipping_refunded'] ?? 0),
  424. 'base_shipping_refunded' => $this->money($row['base_shipping_refunded'] ?? 0),
  425. 'shipping_tax_amount' => $shippingTaxAmount,
  426. 'base_shipping_tax_amount' => $baseShippingTaxAmount,
  427. 'created_at' => ! empty($row['created_at']) ? $row['created_at'] : $now,
  428. 'updated_at' => $now,
  429. ];
  430. return $this->appendRewardAndInsurance($insert, $row, $rewardRow);
  431. }
  432. /**
  433. * @param array<string, mixed> $insert
  434. * @param array<string, mixed> $row
  435. * @param array<string, mixed>|null $rewardRow
  436. * @return array<string, mixed>
  437. */
  438. private function appendRewardAndInsurance(array $insert, array $row, ?array $rewardRow): array
  439. {
  440. $rewardRow ??= [];
  441. if ($this->hasDestinationColumn('reward_points_used')) {
  442. $usedFromOrder = (int) ($row['mw_rewardpoint'] ?? 0);
  443. $usedFromHistory = (int) ($rewardRow['reward_point'] ?? 0);
  444. $amountFromOrder = $this->absMoney($row['mw_rewardpoint_discount'] ?? 0);
  445. $amountFromHistory = $this->absMoney($rewardRow['money'] ?? 0);
  446. $insert['reward_points_used'] = max($usedFromOrder, $usedFromHistory);
  447. $insert['reward_points_amount'] = $amountFromOrder > 0 ? $amountFromOrder : $amountFromHistory;
  448. $insert['base_reward_points_amount'] = $insert['reward_points_amount'];
  449. $insert['reward_points_earned'] = (int) ($rewardRow['earn_rewardpoint'] ?? 0);
  450. }
  451. if ($this->hasDestinationColumn('shipping_insurance_amount')) {
  452. $insurance = $this->absMoney($row['amcheckoutfees_amount'] ?? 0);
  453. $baseInsurance = array_key_exists('base_amcheckoutfees_amount', $row)
  454. ? $this->absMoney($row['base_amcheckoutfees_amount'])
  455. : $insurance;
  456. $insert['shipping_insurance_amount'] = $insurance;
  457. $insert['base_shipping_insurance_amount'] = $baseInsurance > 0 ? $baseInsurance : $insurance;
  458. }
  459. return $insert;
  460. }
  461. private function hasDestinationColumn(string $column): bool
  462. {
  463. $this->destinationOrderColumns ??= [
  464. 'reward_points_used' => Schema::hasColumn('orders', 'reward_points_used'),
  465. 'shipping_insurance_amount' => Schema::hasColumn('orders', 'shipping_insurance_amount'),
  466. ];
  467. return $this->destinationOrderColumns[$column] ?? false;
  468. }
  469. private function absMoney(mixed $value): float
  470. {
  471. return abs($this->money($value));
  472. }
  473. /**
  474. * @param array<string, mixed>|null $paymentRow
  475. * @return array<string, mixed>
  476. */
  477. private function buildPaymentRow(int $orderId, ?array $paymentRow, string $now): array
  478. {
  479. $magentoMethod = trim((string) ($paymentRow['method'] ?? ''));
  480. $additional = [
  481. 'magento_method' => $magentoMethod !== '' ? $magentoMethod : null,
  482. ];
  483. if ($paymentRow) {
  484. $additional['asteria_payment_id'] = (int) ($paymentRow['entity_id'] ?? 0);
  485. foreach (['last_trans_id', 'cc_type', 'cc_last4'] as $key) {
  486. $value = $this->nullableString($paymentRow[$key] ?? null);
  487. if ($value !== null) {
  488. $additional[$key] = $value;
  489. }
  490. }
  491. }
  492. return [
  493. 'order_id' => $orderId,
  494. 'method' => $this->mapPaymentMethod($magentoMethod),
  495. 'method_title' => $magentoMethod !== '' ? $magentoMethod : null,
  496. 'additional' => json_encode($additional),
  497. 'created_at' => $now,
  498. 'updated_at' => $now,
  499. ];
  500. }
  501. /**
  502. * @param array<string, mixed> $row
  503. * @param array<string, mixed> $orderRow
  504. * @return array<string, mixed>
  505. */
  506. private function buildAddressRow(int $orderId, array $row, ?object $customer, string $email, array $orderRow, string $now): array
  507. {
  508. $type = strtolower(trim((string) ($row['address_type'] ?? '')));
  509. $addressType = $type === 'shipping'
  510. ? OrderAddress::ADDRESS_TYPE_SHIPPING
  511. : OrderAddress::ADDRESS_TYPE_BILLING;
  512. $firstName = $this->requiredName(
  513. $row['firstname'] ?? null,
  514. $this->requiredName($orderRow['customer_firstname'] ?? null, $customer?->first_name ?? $email)
  515. );
  516. $lastName = trim((string) ($row['lastname'] ?? ''))
  517. ?: (trim((string) ($orderRow['customer_lastname'] ?? '')) ?: ($customer?->last_name ?? '-'));
  518. return [
  519. 'order_id' => $orderId,
  520. 'customer_id' => $customer?->id,
  521. 'address_type' => $addressType,
  522. 'first_name' => $firstName,
  523. 'last_name' => $lastName,
  524. 'company_name' => $this->nullableString($row['company'] ?? null),
  525. 'address' => $this->mapStreet($row['street'] ?? null) ?: '-',
  526. 'city' => trim((string) ($row['city'] ?? '')) ?: '-',
  527. 'state' => $this->nullableString($row['region'] ?? null),
  528. 'country' => $this->nullableString($row['country_id'] ?? null),
  529. 'postcode' => $this->nullableString($row['postcode'] ?? null),
  530. 'email' => $this->nullableString($row['email'] ?? null) ?? ($email !== '' ? $email : null),
  531. 'phone' => $this->nullableString($row['telephone'] ?? null),
  532. 'additional' => json_encode(['asteria_address_id' => (int) ($row['entity_id'] ?? 0)]),
  533. 'created_at' => $now,
  534. 'updated_at' => $now,
  535. ];
  536. }
  537. /**
  538. * @param array<string, mixed> $row
  539. * @param array<string, Product> $productsBySku
  540. * @return array<string, mixed>
  541. */
  542. private function buildItemRow(int $orderId, array $row, ?int $parentId, array $productsBySku, string $now): array
  543. {
  544. $sku = trim((string) ($row['sku'] ?? ''));
  545. $product = $sku !== '' ? ($productsBySku[$sku] ?? null) : null;
  546. $type = $this->mapProductType($row['product_type'] ?? null, $product);
  547. $price = $this->money($row['price'] ?? 0);
  548. $basePrice = $this->money($row['base_price'] ?? $price);
  549. $total = $this->money($row['row_total'] ?? 0);
  550. $baseTotal = $this->money($row['base_row_total'] ?? $total);
  551. $taxAmount = $this->money($row['tax_amount'] ?? 0);
  552. $baseTaxAmount = $this->money($row['base_tax_amount'] ?? $taxAmount);
  553. return [
  554. 'order_id' => $orderId,
  555. 'parent_id' => $parentId,
  556. 'sku' => $sku !== '' ? $sku : null,
  557. 'type' => $type,
  558. 'name' => $this->nullableString($row['name'] ?? null) ?? '-',
  559. 'weight' => $this->money($row['weight'] ?? 0),
  560. 'total_weight' => $this->money($row['row_weight'] ?? $row['weight'] ?? 0),
  561. 'qty_ordered' => $this->qty($row['qty_ordered'] ?? 0),
  562. 'qty_shipped' => $this->qty($row['qty_shipped'] ?? 0),
  563. 'qty_invoiced' => $this->qty($row['qty_invoiced'] ?? 0),
  564. 'qty_canceled' => $this->qty($row['qty_canceled'] ?? 0),
  565. 'qty_refunded' => $this->qty($row['qty_refunded'] ?? 0),
  566. 'price' => $price,
  567. 'base_price' => $basePrice,
  568. 'price_incl_tax' => array_key_exists('price_incl_tax', $row) ? $this->money($row['price_incl_tax']) : $price,
  569. 'base_price_incl_tax' => array_key_exists('base_price_incl_tax', $row) ? $this->money($row['base_price_incl_tax']) : $basePrice,
  570. 'total' => $total,
  571. 'base_total' => $baseTotal,
  572. 'total_incl_tax' => array_key_exists('row_total_incl_tax', $row) ? $this->money($row['row_total_incl_tax']) : $total + $taxAmount,
  573. 'base_total_incl_tax' => array_key_exists('base_row_total_incl_tax', $row) ? $this->money($row['base_row_total_incl_tax']) : $baseTotal + $baseTaxAmount,
  574. 'tax_percent' => $this->money($row['tax_percent'] ?? 0),
  575. 'tax_amount' => $taxAmount,
  576. 'base_tax_amount' => $baseTaxAmount,
  577. 'discount_percent' => $this->money($row['discount_percent'] ?? 0),
  578. 'discount_amount' => $this->money($row['discount_amount'] ?? 0),
  579. 'base_discount_amount' => $this->money($row['base_discount_amount'] ?? 0),
  580. 'product_id' => $product?->id,
  581. 'product_type' => $product ? get_class($product) : null,
  582. 'additional' => json_encode(['asteria_item_id' => (int) ($row['item_id'] ?? 0)]),
  583. 'created_at' => $now,
  584. 'updated_at' => $now,
  585. ];
  586. }
  587. /**
  588. * @param array<int, int> $orderIds
  589. * @return array<int, int>
  590. */
  591. private function loadInsertedItemIds(array $orderIds): array
  592. {
  593. if ($orderIds === []) {
  594. return [];
  595. }
  596. $map = [];
  597. foreach (DB::table('order_items')->whereIn('order_id', $orderIds)->get(['id', 'additional']) as $item) {
  598. $additional = $item->additional;
  599. if (is_string($additional) && $additional !== '') {
  600. $additional = json_decode($additional, true);
  601. }
  602. if (is_array($additional) && isset($additional['asteria_item_id'])) {
  603. $map[(int) $additional['asteria_item_id']] = (int) $item->id;
  604. }
  605. }
  606. return $map;
  607. }
  608. /**
  609. * @param array<int, array<string, mixed>> $rows
  610. */
  611. private function insertRows(string $table, array $rows): void
  612. {
  613. foreach (array_chunk($rows, self::INSERT_CHUNK) as $chunk) {
  614. DB::table($table)->insert($chunk);
  615. }
  616. }
  617. /**
  618. * @param Collection<int, array<string, mixed>> $orders
  619. * @return array{0: array<int, object>, 1: array<string, object>}
  620. */
  621. private function loadCustomers($orders): array
  622. {
  623. $asteriaIds = $orders
  624. ->pluck('customer_id')
  625. ->filter(fn ($id) => (int) $id > 0)
  626. ->map(fn ($id) => (int) $id)
  627. ->unique()
  628. ->values()
  629. ->all();
  630. $emails = $orders
  631. ->pluck('customer_email')
  632. ->map(fn ($email) => strtolower(trim((string) $email)))
  633. ->filter()
  634. ->unique()
  635. ->values()
  636. ->all();
  637. $byAsteriaId = [];
  638. $byEmail = [];
  639. if ($asteriaIds !== []) {
  640. foreach (
  641. DB::table('customers')
  642. ->select('id', 'email', 'first_name', 'last_name', 'migrated_from_asteria_id')
  643. ->whereIn('migrated_from_asteria_id', $asteriaIds)
  644. ->get() as $customer
  645. ) {
  646. $byAsteriaId[(int) $customer->migrated_from_asteria_id] = $customer;
  647. }
  648. }
  649. if ($emails !== []) {
  650. foreach (
  651. DB::table('customers')
  652. ->select('id', 'email', 'first_name', 'last_name', 'migrated_from_asteria_id')
  653. ->whereIn(DB::raw('LOWER(email)'), $emails)
  654. ->get() as $customer
  655. ) {
  656. $byEmail[strtolower((string) $customer->email)] = $customer;
  657. }
  658. }
  659. return [$byAsteriaId, $byEmail];
  660. }
  661. /**
  662. * @param Collection<int, Collection<int, array<string, mixed>>> $items
  663. * @return array<string, Product>
  664. */
  665. private function loadProducts($items): array
  666. {
  667. $skus = $items
  668. ->flatten(1)
  669. ->pluck('sku')
  670. ->map(fn ($sku) => trim((string) $sku))
  671. ->filter()
  672. ->unique()
  673. ->values()
  674. ->all();
  675. if ($skus === []) {
  676. return [];
  677. }
  678. return Product::query()
  679. ->whereIn('sku', $skus)
  680. ->get(['id', 'sku', 'type'])
  681. ->keyBy('sku')
  682. ->all();
  683. }
  684. /**
  685. * @param array<string, mixed> $row
  686. * @param array<int, Customer> $customersByAsteriaId
  687. * @param array<string, Customer> $customersByEmail
  688. */
  689. private function resolveCustomer(array $row, array $customersByAsteriaId, array $customersByEmail): ?object
  690. {
  691. $asteriaCustomerId = (int) ($row['customer_id'] ?? 0);
  692. if ($asteriaCustomerId > 0 && isset($customersByAsteriaId[$asteriaCustomerId])) {
  693. return $customersByAsteriaId[$asteriaCustomerId];
  694. }
  695. $email = strtolower(trim((string) ($row['customer_email'] ?? '')));
  696. if ($email !== '' && isset($customersByEmail[$email])) {
  697. return $customersByEmail[$email];
  698. }
  699. return null;
  700. }
  701. /**
  702. * @param array<string, mixed> $row
  703. */
  704. private function mapStatus(array $row): string
  705. {
  706. $status = strtolower(trim((string) ($row['status'] ?? '')));
  707. $state = strtolower(trim((string) ($row['state'] ?? '')));
  708. $value = $status !== '' ? $status : $state;
  709. return match ($value) {
  710. 'complete' => Order::STATUS_COMPLETED,
  711. 'canceled', 'cancelled' => Order::STATUS_CANCELED,
  712. 'pending_payment', 'payment_review', 'pending_paypal' => Order::STATUS_PENDING_PAYMENT,
  713. 'holded' => Order::STATUS_PENDING,
  714. 'fraud' => Order::STATUS_FRAUD,
  715. 'closed' => Order::STATUS_CLOSED,
  716. 'processing' => Order::STATUS_PROCESSING,
  717. default => Order::STATUS_PENDING,
  718. };
  719. }
  720. private function mapPaymentMethod(string $method): string
  721. {
  722. $method = strtolower(trim($method));
  723. if ($method === '') {
  724. return 'unknown';
  725. }
  726. if (in_array($method, ['paypal_express', 'paypal_standard'], true) || str_starts_with($method, 'paypaluk_')) {
  727. return 'paypal_standard';
  728. }
  729. if ($method === 'checkmo') {
  730. return 'moneytransfer';
  731. }
  732. if ($method === 'cashondelivery') {
  733. return 'cashondelivery';
  734. }
  735. if (str_starts_with($method, 'klarna')) {
  736. return 'klarna';
  737. }
  738. if (str_starts_with($method, 'afterpay') || str_starts_with($method, 'clearpay')) {
  739. return 'afterpay';
  740. }
  741. return $method;
  742. }
  743. private function mapProductType(mixed $magentoType, ?Product $product): string
  744. {
  745. if ($product && in_array($product->type, self::BAGISTO_PRODUCT_TYPES, true)) {
  746. return $product->type;
  747. }
  748. $type = strtolower(trim((string) $magentoType));
  749. if (in_array($type, self::BAGISTO_PRODUCT_TYPES, true)) {
  750. return $type;
  751. }
  752. return 'simple';
  753. }
  754. private function mapStreet(mixed $value): string
  755. {
  756. $value = trim((string) $value);
  757. if ($value === '') {
  758. return '';
  759. }
  760. $lines = preg_split("/\r\n|\n|\r/", $value) ?: [];
  761. return implode(', ', array_filter(array_map('trim', $lines)));
  762. }
  763. private function requiredName(mixed $value, string $fallback): string
  764. {
  765. $value = trim((string) $value);
  766. if ($value !== '') {
  767. return $value;
  768. }
  769. $fallback = trim($fallback);
  770. if ($fallback !== '') {
  771. $local = strstr($fallback, '@', true);
  772. return $local !== false && $local !== '' ? $local : $fallback;
  773. }
  774. return 'Customer';
  775. }
  776. private function nullableString(mixed $value): ?string
  777. {
  778. $value = trim((string) $value);
  779. return $value === '' ? null : $value;
  780. }
  781. private function money(mixed $value): float
  782. {
  783. return is_numeric($value) ? (float) $value : 0.0;
  784. }
  785. private function qty(mixed $value): int
  786. {
  787. return (int) round((float) $value);
  788. }
  789. }