MigrateAsteriaOrders.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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. use Webkul\Sales\Models\OrderItem;
  16. use Webkul\Sales\Models\OrderPayment;
  17. /**
  18. * Migrates storefront orders from Asteria (Magento 1.x).
  19. *
  20. * Does not create invoices/shipments/refunds, does not decrement inventory,
  21. * and does not fire checkout.order.save.after listeners.
  22. *
  23. * Usage
  24. * ─────
  25. * php artisan orders:migrate-asteria
  26. * php artisan orders:migrate-asteria --batch-size=200
  27. * php artisan orders:migrate-asteria --reset-progress
  28. * php artisan orders:migrate-asteria --dry-run
  29. */
  30. class MigrateAsteriaOrders extends Command
  31. {
  32. protected $signature = 'orders:migrate-asteria
  33. {--batch-size=100 : Number of Magento orders per batch}
  34. {--reset-progress : Ignore saved progress and start from entity_id=0}
  35. {--dry-run : Count records without writing}
  36. {--connection=asteria : Laravel DB connection for the Asteria database}';
  37. protected $description = 'Migrate Asteria (Magento 1.x) orders into Bagisto';
  38. private const PROGRESS_KEY = 'migrate_asteria_orders_last_id';
  39. private const BAGISTO_PRODUCT_TYPES = [
  40. 'simple',
  41. 'configurable',
  42. 'virtual',
  43. 'downloadable',
  44. 'bundle',
  45. 'grouped',
  46. ];
  47. public function handle(): int
  48. {
  49. $connection = (string) $this->option('connection');
  50. $batchSize = max(1, (int) $this->option('batch-size'));
  51. $resetProgress = (bool) $this->option('reset-progress');
  52. $dryRun = (bool) $this->option('dry-run');
  53. try {
  54. DB::connection($connection)->getPdo();
  55. } catch (\Throwable $e) {
  56. $this->error("Cannot connect to Asteria DB (connection='{$connection}'): ".$e->getMessage());
  57. return self::FAILURE;
  58. }
  59. foreach ([
  60. 'sales_flat_order',
  61. 'sales_flat_order_item',
  62. 'sales_flat_order_address',
  63. 'sales_flat_order_payment',
  64. ] as $table) {
  65. if (! Schema::connection($connection)->hasTable($table)) {
  66. $this->error("Asteria table '{$table}' is missing on connection '{$connection}'.");
  67. return self::FAILURE;
  68. }
  69. }
  70. if (! Schema::hasColumn('orders', 'migrated_from_asteria_id')) {
  71. $this->error('orders.migrated_from_asteria_id is missing. Run php artisan migrate.');
  72. return self::FAILURE;
  73. }
  74. $channel = core()->getDefaultChannel() ?? core()->getCurrentChannel();
  75. if (! $channel) {
  76. $this->error('Bagisto default channel was not found.');
  77. return self::FAILURE;
  78. }
  79. $reader = new Magento1OrderReader($connection);
  80. $lastId = $resetProgress ? 0 : (int) Cache::get(self::PROGRESS_KEY, 0);
  81. if ($resetProgress) {
  82. Cache::forget(self::PROGRESS_KEY);
  83. }
  84. if ($lastId > 0) {
  85. $this->line("Resuming from Asteria entity_id > {$lastId} (use --reset-progress to restart).");
  86. }
  87. $created = 0;
  88. $skipped = 0;
  89. $itemsImported = 0;
  90. $addressesImported = 0;
  91. $batchNumber = 0;
  92. $this->info($dryRun ? '[DRY RUN] Scanning Magento orders…' : 'Migrating Magento orders…');
  93. do {
  94. $orders = $reader->fetchOrders($lastId, $batchSize);
  95. if ($orders->isEmpty()) {
  96. break;
  97. }
  98. $batchNumber++;
  99. $lastId = (int) $orders->max('entity_id');
  100. $orderIds = $orders->pluck('entity_id')->map(fn ($id) => (int) $id)->all();
  101. $items = $reader->fetchItems($orderIds)->groupBy(fn (array $row) => (int) $row['order_id']);
  102. $addresses = $reader->fetchAddresses($orderIds)->groupBy(fn (array $row) => (int) $row['parent_id']);
  103. $payments = $reader->fetchPayments($orderIds)->groupBy(fn (array $row) => (int) $row['parent_id']);
  104. if ($dryRun) {
  105. $created += $orders->count();
  106. $itemsImported += $items->flatten(1)->count();
  107. $addressesImported += $addresses->flatten(1)->count();
  108. $this->line(sprintf(
  109. ' Batch #%d: %d orders, %d items, %d addresses (last entity_id=%d) [skipped – dry-run]',
  110. $batchNumber,
  111. $orders->count(),
  112. $items->flatten(1)->count(),
  113. $addresses->flatten(1)->count(),
  114. $lastId
  115. ));
  116. continue;
  117. }
  118. [$customersByAsteriaId, $customersByEmail] = $this->loadCustomers($orders);
  119. $productsBySku = $this->loadProducts($items);
  120. $batchCreated = 0;
  121. $batchSkipped = 0;
  122. $batchItems = 0;
  123. $batchAddresses = 0;
  124. DB::transaction(function () use (
  125. $orders,
  126. $items,
  127. $addresses,
  128. $payments,
  129. $channel,
  130. $customersByAsteriaId,
  131. $customersByEmail,
  132. $productsBySku,
  133. &$batchCreated,
  134. &$batchSkipped,
  135. &$batchItems,
  136. &$batchAddresses
  137. ) {
  138. foreach ($orders as $row) {
  139. $result = $this->migrateOrder(
  140. $row,
  141. $items->get((int) $row['entity_id'], collect()),
  142. $addresses->get((int) $row['entity_id'], collect()),
  143. $payments->get((int) $row['entity_id'], collect())->first(),
  144. $channel,
  145. $customersByAsteriaId,
  146. $customersByEmail,
  147. $productsBySku
  148. );
  149. $batchCreated += $result['created'];
  150. $batchSkipped += $result['skipped'];
  151. $batchItems += $result['items'];
  152. $batchAddresses += $result['addresses'];
  153. }
  154. });
  155. Cache::put(self::PROGRESS_KEY, $lastId, now()->addDays(30));
  156. $created += $batchCreated;
  157. $skipped += $batchSkipped;
  158. $itemsImported += $batchItems;
  159. $addressesImported += $batchAddresses;
  160. $this->line(sprintf(
  161. ' Batch #%d: created=%d skipped=%d items=%d addresses=%d (last entity_id=%d)',
  162. $batchNumber,
  163. $batchCreated,
  164. $batchSkipped,
  165. $batchItems,
  166. $batchAddresses,
  167. $lastId
  168. ));
  169. Log::info('MigrateAsteriaOrders: batch '.$batchNumber.', last_id='.$lastId);
  170. } while ($orders->count() === $batchSize);
  171. $this->newLine();
  172. $this->info("Done. Batches: {$batchNumber}, created: {$created}, skipped: {$skipped}, items: {$itemsImported}, addresses: {$addressesImported}.");
  173. return self::SUCCESS;
  174. }
  175. /**
  176. * @param array<string, mixed> $row
  177. * @param Collection<int, array<string, mixed>> $itemRows
  178. * @param Collection<int, array<string, mixed>> $addressRows
  179. * @param array<string, mixed>|null $paymentRow
  180. * @param array<int, Customer> $customersByAsteriaId
  181. * @param array<string, Customer> $customersByEmail
  182. * @param array<string, Product> $productsBySku
  183. * @return array{created: int, skipped: int, items: int, addresses: int}
  184. */
  185. private function migrateOrder(
  186. array $row,
  187. $itemRows,
  188. $addressRows,
  189. ?array $paymentRow,
  190. Channel $channel,
  191. array $customersByAsteriaId,
  192. array $customersByEmail,
  193. array $productsBySku
  194. ): array {
  195. $asteriaId = (int) $row['entity_id'];
  196. $incrementId = trim((string) ($row['increment_id'] ?? ''));
  197. if ($asteriaId < 1 || $incrementId === '') {
  198. return ['created' => 0, 'skipped' => 1, 'items' => 0, 'addresses' => 0];
  199. }
  200. $alreadyMigrated = Order::query()
  201. ->where('migrated_from_asteria_id', $asteriaId)
  202. ->exists();
  203. if ($alreadyMigrated) {
  204. return ['created' => 0, 'skipped' => 1, 'items' => 0, 'addresses' => 0];
  205. }
  206. $incrementTaken = Order::query()
  207. ->where('increment_id', $incrementId)
  208. ->exists();
  209. if ($incrementTaken) {
  210. return ['created' => 0, 'skipped' => 1, 'items' => 0, 'addresses' => 0];
  211. }
  212. $customer = $this->resolveCustomer($row, $customersByAsteriaId, $customersByEmail);
  213. $email = strtolower(trim((string) ($row['customer_email'] ?? '')));
  214. if ($email === '' && $customer) {
  215. $email = strtolower((string) $customer->email);
  216. }
  217. $subTotal = $this->money($row['subtotal'] ?? 0);
  218. $baseSubTotal = $this->money($row['base_subtotal'] ?? $subTotal);
  219. $taxAmount = $this->money($row['tax_amount'] ?? 0);
  220. $baseTaxAmount = $this->money($row['base_tax_amount'] ?? $taxAmount);
  221. $shippingAmount = $this->money($row['shipping_amount'] ?? 0);
  222. $baseShippingAmount = $this->money($row['base_shipping_amount'] ?? $shippingAmount);
  223. $shippingTaxAmount = $this->money($row['shipping_tax_amount'] ?? 0);
  224. $baseShippingTaxAmount = $this->money($row['base_shipping_tax_amount'] ?? $shippingTaxAmount);
  225. $discountAmount = $this->money($row['discount_amount'] ?? 0);
  226. $baseDiscountAmount = $this->money($row['base_discount_amount'] ?? $discountAmount);
  227. $grandTotal = $this->money($row['grand_total'] ?? 0);
  228. $baseGrandTotal = $this->money($row['base_grand_total'] ?? $grandTotal);
  229. $subTotalInclTax = array_key_exists('subtotal_incl_tax', $row)
  230. ? $this->money($row['subtotal_incl_tax'])
  231. : $subTotal + $taxAmount;
  232. $baseSubTotalInclTax = array_key_exists('base_subtotal_incl_tax', $row)
  233. ? $this->money($row['base_subtotal_incl_tax'])
  234. : $baseSubTotal + $baseTaxAmount;
  235. $shippingInclTax = array_key_exists('shipping_incl_tax', $row)
  236. ? $this->money($row['shipping_incl_tax'])
  237. : $shippingAmount + $shippingTaxAmount;
  238. $baseShippingInclTax = array_key_exists('base_shipping_incl_tax', $row)
  239. ? $this->money($row['base_shipping_incl_tax'])
  240. : $baseShippingAmount + $baseShippingTaxAmount;
  241. $order = new Order;
  242. $order->forceFill([
  243. 'migrated_from_asteria_id' => $asteriaId,
  244. 'increment_id' => $incrementId,
  245. 'status' => $this->mapStatus($row),
  246. 'channel_name' => $channel->name,
  247. 'is_guest' => $customer ? 0 : 1,
  248. 'customer_email' => $email !== '' ? $email : null,
  249. 'customer_first_name' => $this->requiredName($row['customer_firstname'] ?? null, $customer?->first_name ?? $email),
  250. 'customer_last_name' => trim((string) ($row['customer_lastname'] ?? '')) ?: ($customer?->last_name ?? '-'),
  251. 'customer_id' => $customer?->id,
  252. 'customer_type' => $customer ? Customer::class : null,
  253. 'channel_id' => $channel->id,
  254. 'channel_type' => get_class($channel),
  255. 'cart_id' => null,
  256. 'shipping_method' => $this->nullableString($row['shipping_method'] ?? null),
  257. 'shipping_title' => $this->nullableString($row['shipping_description'] ?? null),
  258. 'shipping_description' => $this->nullableString($row['shipping_description'] ?? null),
  259. 'coupon_code' => $this->nullableString($row['coupon_code'] ?? null),
  260. 'is_gift' => 0,
  261. 'total_item_count' => $this->qty($row['total_item_count'] ?? $itemRows->count()),
  262. 'total_qty_ordered' => $this->qty($row['total_qty_ordered'] ?? $itemRows->sum(fn (array $item) => (float) ($item['qty_ordered'] ?? 0))),
  263. 'base_currency_code' => $this->nullableString($row['base_currency_code'] ?? null) ?? 'USD',
  264. 'channel_currency_code' => $this->nullableString($row['store_currency_code'] ?? null)
  265. ?? $this->nullableString($row['order_currency_code'] ?? null)
  266. ?? 'USD',
  267. 'order_currency_code' => $this->nullableString($row['order_currency_code'] ?? null) ?? 'USD',
  268. 'grand_total' => $grandTotal,
  269. 'base_grand_total' => $baseGrandTotal,
  270. 'grand_total_invoiced' => $this->money($row['total_invoiced'] ?? 0),
  271. 'base_grand_total_invoiced' => $this->money($row['base_total_invoiced'] ?? 0),
  272. 'grand_total_refunded' => $this->money($row['total_refunded'] ?? 0),
  273. 'base_grand_total_refunded' => $this->money($row['base_total_refunded'] ?? 0),
  274. 'sub_total' => $subTotal,
  275. 'base_sub_total' => $baseSubTotal,
  276. 'sub_total_incl_tax' => $subTotalInclTax,
  277. 'base_sub_total_incl_tax' => $baseSubTotalInclTax,
  278. 'sub_total_invoiced' => $this->money($row['subtotal_invoiced'] ?? 0),
  279. 'base_sub_total_invoiced' => $this->money($row['base_subtotal_invoiced'] ?? 0),
  280. 'sub_total_refunded' => $this->money($row['subtotal_refunded'] ?? 0),
  281. 'base_sub_total_refunded' => $this->money($row['base_subtotal_refunded'] ?? 0),
  282. 'discount_amount' => $discountAmount,
  283. 'base_discount_amount' => $baseDiscountAmount,
  284. 'discount_invoiced' => $this->money($row['discount_invoiced'] ?? 0),
  285. 'base_discount_invoiced' => $this->money($row['base_discount_invoiced'] ?? 0),
  286. 'discount_refunded' => $this->money($row['discount_refunded'] ?? 0),
  287. 'base_discount_refunded' => $this->money($row['base_discount_refunded'] ?? 0),
  288. 'tax_amount' => $taxAmount,
  289. 'base_tax_amount' => $baseTaxAmount,
  290. 'tax_amount_invoiced' => $this->money($row['tax_invoiced'] ?? 0),
  291. 'base_tax_amount_invoiced' => $this->money($row['base_tax_invoiced'] ?? 0),
  292. 'tax_amount_refunded' => $this->money($row['tax_refunded'] ?? 0),
  293. 'base_tax_amount_refunded' => $this->money($row['base_tax_refunded'] ?? 0),
  294. 'shipping_amount' => $shippingAmount,
  295. 'base_shipping_amount' => $baseShippingAmount,
  296. 'shipping_amount_incl_tax' => $shippingInclTax,
  297. 'base_shipping_amount_incl_tax' => $baseShippingInclTax,
  298. 'shipping_invoiced' => $this->money($row['shipping_invoiced'] ?? 0),
  299. 'base_shipping_invoiced' => $this->money($row['base_shipping_invoiced'] ?? 0),
  300. 'shipping_refunded' => $this->money($row['shipping_refunded'] ?? 0),
  301. 'base_shipping_refunded' => $this->money($row['base_shipping_refunded'] ?? 0),
  302. 'shipping_tax_amount' => $shippingTaxAmount,
  303. 'base_shipping_tax_amount' => $baseShippingTaxAmount,
  304. ]);
  305. if (! empty($row['created_at'])) {
  306. $order->created_at = $row['created_at'];
  307. }
  308. $order->save();
  309. $this->importPayment($order, $paymentRow);
  310. $importedAddresses = $this->importAddresses($order, $addressRows, $customer, $email);
  311. $importedItems = $this->importItems($order, $itemRows, $productsBySku);
  312. return [
  313. 'created' => 1,
  314. 'skipped' => 0,
  315. 'items' => $importedItems,
  316. 'addresses' => $importedAddresses,
  317. ];
  318. }
  319. /**
  320. * @param array<string, mixed>|null $paymentRow
  321. */
  322. private function importPayment(Order $order, ?array $paymentRow): void
  323. {
  324. $magentoMethod = trim((string) ($paymentRow['method'] ?? ''));
  325. $additional = [
  326. 'magento_method' => $magentoMethod !== '' ? $magentoMethod : null,
  327. ];
  328. if ($paymentRow) {
  329. $additional['asteria_payment_id'] = (int) ($paymentRow['entity_id'] ?? 0);
  330. foreach (['last_trans_id', 'cc_type', 'cc_last4'] as $key) {
  331. $value = $this->nullableString($paymentRow[$key] ?? null);
  332. if ($value !== null) {
  333. $additional[$key] = $value;
  334. }
  335. }
  336. }
  337. $payment = new OrderPayment;
  338. $payment->forceFill([
  339. 'order_id' => $order->id,
  340. 'method' => $this->mapPaymentMethod($magentoMethod),
  341. 'method_title' => $magentoMethod !== '' ? $magentoMethod : null,
  342. 'additional' => $additional,
  343. ]);
  344. $payment->save();
  345. }
  346. /**
  347. * @param Collection<int, array<string, mixed>> $addressRows
  348. */
  349. private function importAddresses(Order $order, $addressRows, ?Customer $customer, string $email): int
  350. {
  351. $imported = 0;
  352. foreach ($addressRows as $row) {
  353. $type = strtolower(trim((string) ($row['address_type'] ?? '')));
  354. $addressType = $type === 'shipping'
  355. ? OrderAddress::ADDRESS_TYPE_SHIPPING
  356. : OrderAddress::ADDRESS_TYPE_BILLING;
  357. $address = new OrderAddress;
  358. $address->forceFill([
  359. 'order_id' => $order->id,
  360. 'customer_id' => $customer?->id,
  361. 'address_type' => $addressType,
  362. 'first_name' => $this->requiredName($row['firstname'] ?? null, $order->customer_first_name),
  363. 'last_name' => trim((string) ($row['lastname'] ?? '')) ?: $order->customer_last_name,
  364. 'company_name' => $this->nullableString($row['company'] ?? null),
  365. 'address' => $this->mapStreet($row['street'] ?? null) ?: '-',
  366. 'city' => trim((string) ($row['city'] ?? '')) ?: '-',
  367. 'state' => $this->nullableString($row['region'] ?? null),
  368. 'country' => $this->nullableString($row['country_id'] ?? null),
  369. 'postcode' => $this->nullableString($row['postcode'] ?? null),
  370. 'email' => $this->nullableString($row['email'] ?? null) ?? ($email !== '' ? $email : null),
  371. 'phone' => $this->nullableString($row['telephone'] ?? null),
  372. 'additional' => json_encode(['asteria_address_id' => (int) ($row['entity_id'] ?? 0)]),
  373. ]);
  374. $address->save();
  375. $imported++;
  376. }
  377. return $imported;
  378. }
  379. /**
  380. * @param Collection<int, array<string, mixed>> $itemRows
  381. * @param array<string, Product> $productsBySku
  382. */
  383. private function importItems(Order $order, $itemRows, array $productsBySku): int
  384. {
  385. if ($itemRows->isEmpty()) {
  386. return 0;
  387. }
  388. $parents = $itemRows->filter(fn (array $row) => empty($row['parent_item_id']));
  389. $children = $itemRows->filter(fn (array $row) => ! empty($row['parent_item_id']));
  390. $idMap = [];
  391. $imported = 0;
  392. foreach ($parents as $row) {
  393. $item = $this->createOrderItem($order, $row, null, $productsBySku);
  394. $idMap[(int) $row['item_id']] = $item->id;
  395. $imported++;
  396. }
  397. foreach ($children as $row) {
  398. $parentId = $idMap[(int) $row['parent_item_id']] ?? null;
  399. $this->createOrderItem($order, $row, $parentId, $productsBySku);
  400. $imported++;
  401. }
  402. return $imported;
  403. }
  404. /**
  405. * @param array<string, mixed> $row
  406. * @param array<string, Product> $productsBySku
  407. */
  408. private function createOrderItem(Order $order, array $row, ?int $parentId, array $productsBySku): OrderItem
  409. {
  410. $sku = trim((string) ($row['sku'] ?? ''));
  411. $product = $sku !== '' ? ($productsBySku[$sku] ?? null) : null;
  412. $type = $this->mapProductType($row['product_type'] ?? null, $product);
  413. $price = $this->money($row['price'] ?? 0);
  414. $basePrice = $this->money($row['base_price'] ?? $price);
  415. $total = $this->money($row['row_total'] ?? 0);
  416. $baseTotal = $this->money($row['base_row_total'] ?? $total);
  417. $taxAmount = $this->money($row['tax_amount'] ?? 0);
  418. $baseTaxAmount = $this->money($row['base_tax_amount'] ?? $taxAmount);
  419. $item = new OrderItem;
  420. $item->forceFill([
  421. 'order_id' => $order->id,
  422. 'parent_id' => $parentId,
  423. 'sku' => $sku !== '' ? $sku : null,
  424. 'type' => $type,
  425. 'name' => $this->nullableString($row['name'] ?? null) ?? '-',
  426. 'weight' => $this->money($row['weight'] ?? 0),
  427. 'total_weight' => $this->money($row['row_weight'] ?? $row['weight'] ?? 0),
  428. 'qty_ordered' => $this->qty($row['qty_ordered'] ?? 0),
  429. 'qty_shipped' => $this->qty($row['qty_shipped'] ?? 0),
  430. 'qty_invoiced' => $this->qty($row['qty_invoiced'] ?? 0),
  431. 'qty_canceled' => $this->qty($row['qty_canceled'] ?? 0),
  432. 'qty_refunded' => $this->qty($row['qty_refunded'] ?? 0),
  433. 'price' => $price,
  434. 'base_price' => $basePrice,
  435. 'price_incl_tax' => array_key_exists('price_incl_tax', $row) ? $this->money($row['price_incl_tax']) : $price,
  436. 'base_price_incl_tax' => array_key_exists('base_price_incl_tax', $row) ? $this->money($row['base_price_incl_tax']) : $basePrice,
  437. 'total' => $total,
  438. 'base_total' => $baseTotal,
  439. 'total_incl_tax' => array_key_exists('row_total_incl_tax', $row) ? $this->money($row['row_total_incl_tax']) : $total + $taxAmount,
  440. 'base_total_incl_tax' => array_key_exists('base_row_total_incl_tax', $row) ? $this->money($row['base_row_total_incl_tax']) : $baseTotal + $baseTaxAmount,
  441. 'tax_percent' => $this->money($row['tax_percent'] ?? 0),
  442. 'tax_amount' => $taxAmount,
  443. 'base_tax_amount' => $baseTaxAmount,
  444. 'discount_percent' => $this->money($row['discount_percent'] ?? 0),
  445. 'discount_amount' => $this->money($row['discount_amount'] ?? 0),
  446. 'base_discount_amount' => $this->money($row['base_discount_amount'] ?? 0),
  447. 'product_id' => $product?->id,
  448. 'product_type' => $product ? get_class($product) : null,
  449. 'additional' => [
  450. 'asteria_item_id' => (int) ($row['item_id'] ?? 0),
  451. ],
  452. ]);
  453. $item->save();
  454. return $item;
  455. }
  456. /**
  457. * @param Collection<int, array<string, mixed>> $orders
  458. * @return array{0: array<int, Customer>, 1: array<string, Customer>}
  459. */
  460. private function loadCustomers($orders): array
  461. {
  462. $asteriaIds = $orders
  463. ->pluck('customer_id')
  464. ->filter(fn ($id) => (int) $id > 0)
  465. ->map(fn ($id) => (int) $id)
  466. ->unique()
  467. ->values()
  468. ->all();
  469. $emails = $orders
  470. ->pluck('customer_email')
  471. ->map(fn ($email) => strtolower(trim((string) $email)))
  472. ->filter()
  473. ->unique()
  474. ->values()
  475. ->all();
  476. $byAsteriaId = [];
  477. $byEmail = [];
  478. if ($asteriaIds !== []) {
  479. foreach (Customer::query()->whereIn('migrated_from_asteria_id', $asteriaIds)->get() as $customer) {
  480. $byAsteriaId[(int) $customer->migrated_from_asteria_id] = $customer;
  481. }
  482. }
  483. if ($emails !== []) {
  484. $query = Customer::query();
  485. $query->where(function ($inner) use ($emails) {
  486. foreach ($emails as $email) {
  487. $inner->orWhereRaw('LOWER(email) = ?', [$email]);
  488. }
  489. });
  490. foreach ($query->get() as $customer) {
  491. $byEmail[strtolower((string) $customer->email)] = $customer;
  492. }
  493. }
  494. return [$byAsteriaId, $byEmail];
  495. }
  496. /**
  497. * @param Collection<int, Collection<int, array<string, mixed>>> $items
  498. * @return array<string, Product>
  499. */
  500. private function loadProducts($items): array
  501. {
  502. $skus = $items
  503. ->flatten(1)
  504. ->pluck('sku')
  505. ->map(fn ($sku) => trim((string) $sku))
  506. ->filter()
  507. ->unique()
  508. ->values()
  509. ->all();
  510. if ($skus === []) {
  511. return [];
  512. }
  513. return Product::query()
  514. ->whereIn('sku', $skus)
  515. ->get(['id', 'sku', 'type'])
  516. ->keyBy('sku')
  517. ->all();
  518. }
  519. /**
  520. * @param array<string, mixed> $row
  521. * @param array<int, Customer> $customersByAsteriaId
  522. * @param array<string, Customer> $customersByEmail
  523. */
  524. private function resolveCustomer(array $row, array $customersByAsteriaId, array $customersByEmail): ?Customer
  525. {
  526. $asteriaCustomerId = (int) ($row['customer_id'] ?? 0);
  527. if ($asteriaCustomerId > 0 && isset($customersByAsteriaId[$asteriaCustomerId])) {
  528. return $customersByAsteriaId[$asteriaCustomerId];
  529. }
  530. $email = strtolower(trim((string) ($row['customer_email'] ?? '')));
  531. if ($email !== '' && isset($customersByEmail[$email])) {
  532. return $customersByEmail[$email];
  533. }
  534. return null;
  535. }
  536. /**
  537. * @param array<string, mixed> $row
  538. */
  539. private function mapStatus(array $row): string
  540. {
  541. $status = strtolower(trim((string) ($row['status'] ?? '')));
  542. $state = strtolower(trim((string) ($row['state'] ?? '')));
  543. $value = $status !== '' ? $status : $state;
  544. return match ($value) {
  545. 'complete' => Order::STATUS_COMPLETED,
  546. 'canceled', 'cancelled' => Order::STATUS_CANCELED,
  547. 'pending_payment', 'payment_review', 'pending_paypal' => Order::STATUS_PENDING_PAYMENT,
  548. 'holded' => Order::STATUS_PENDING,
  549. 'fraud' => Order::STATUS_FRAUD,
  550. 'closed' => Order::STATUS_CLOSED,
  551. 'processing' => Order::STATUS_PROCESSING,
  552. default => Order::STATUS_PENDING,
  553. };
  554. }
  555. private function mapPaymentMethod(string $method): string
  556. {
  557. $method = strtolower(trim($method));
  558. if ($method === '') {
  559. return 'unknown';
  560. }
  561. if (in_array($method, ['paypal_express', 'paypal_standard'], true) || str_starts_with($method, 'paypaluk_')) {
  562. return 'paypal_standard';
  563. }
  564. if ($method === 'checkmo') {
  565. return 'moneytransfer';
  566. }
  567. if ($method === 'cashondelivery') {
  568. return 'cashondelivery';
  569. }
  570. if (str_starts_with($method, 'klarna')) {
  571. return 'klarna';
  572. }
  573. if (str_starts_with($method, 'afterpay') || str_starts_with($method, 'clearpay')) {
  574. return 'afterpay';
  575. }
  576. return $method;
  577. }
  578. private function mapProductType(mixed $magentoType, ?Product $product): string
  579. {
  580. if ($product && in_array($product->type, self::BAGISTO_PRODUCT_TYPES, true)) {
  581. return $product->type;
  582. }
  583. $type = strtolower(trim((string) $magentoType));
  584. if (in_array($type, self::BAGISTO_PRODUCT_TYPES, true)) {
  585. return $type;
  586. }
  587. return 'simple';
  588. }
  589. private function mapStreet(mixed $value): string
  590. {
  591. $value = trim((string) $value);
  592. if ($value === '') {
  593. return '';
  594. }
  595. $lines = preg_split("/\r\n|\n|\r/", $value) ?: [];
  596. return implode(', ', array_filter(array_map('trim', $lines)));
  597. }
  598. private function requiredName(mixed $value, string $fallback): string
  599. {
  600. $value = trim((string) $value);
  601. if ($value !== '') {
  602. return $value;
  603. }
  604. $fallback = trim($fallback);
  605. if ($fallback !== '') {
  606. $local = strstr($fallback, '@', true);
  607. return $local !== false && $local !== '' ? $local : $fallback;
  608. }
  609. return 'Customer';
  610. }
  611. private function nullableString(mixed $value): ?string
  612. {
  613. $value = trim((string) $value);
  614. return $value === '' ? null : $value;
  615. }
  616. private function money(mixed $value): float
  617. {
  618. return is_numeric($value) ? (float) $value : 0.0;
  619. }
  620. private function qty(mixed $value): int
  621. {
  622. return (int) round((float) $value);
  623. }
  624. }