MigrateAsteriaOrders.php 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968
  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. * Also imports Magento shipments/tracking. Does not create invoices/refunds,
  19. * does not decrement inventory, 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. /** @var array{id: int|null, name: string|null}|null */
  49. private ?array $defaultInventorySource = null;
  50. public function handle(): int
  51. {
  52. $connection = (string) $this->option('connection');
  53. $batchSize = max(1, (int) $this->option('batch-size'));
  54. $resetProgress = (bool) $this->option('reset-progress');
  55. $dryRun = (bool) $this->option('dry-run');
  56. DB::disableQueryLog();
  57. try {
  58. DB::connection($connection)->getPdo();
  59. } catch (\Throwable $e) {
  60. $this->error("Cannot connect to Asteria DB (connection='{$connection}'): ".$e->getMessage());
  61. return self::FAILURE;
  62. }
  63. foreach ([
  64. 'sales_flat_order',
  65. 'sales_flat_order_item',
  66. 'sales_flat_order_address',
  67. 'sales_flat_order_payment',
  68. ] as $table) {
  69. if (! Schema::connection($connection)->hasTable($table)) {
  70. $this->error("Asteria table '{$table}' is missing on connection '{$connection}'.");
  71. return self::FAILURE;
  72. }
  73. }
  74. if (! Schema::hasColumn('orders', 'migrated_from_asteria_id')) {
  75. $this->error('orders.migrated_from_asteria_id is missing. Run php artisan migrate.');
  76. return self::FAILURE;
  77. }
  78. if (! Schema::hasColumn('orders', 'reward_points_used')) {
  79. $this->warn('orders.reward_points_used is missing. Run php artisan migrate to import order reward points.');
  80. }
  81. if (! Schema::hasColumn('orders', 'shipping_insurance_amount')) {
  82. $this->warn('orders.shipping_insurance_amount is missing. Run php artisan migrate to import lost-package insurance.');
  83. }
  84. if (! Schema::hasColumn('orders', 'remote_ip')) {
  85. $this->warn('orders.remote_ip is missing. Run php artisan migrate to import Magento remote_ip.');
  86. }
  87. if (! Schema::hasColumn('orders', 'giftcard_amount')) {
  88. $this->warn('orders.giftcard_amount is missing. Gift card amounts will not be imported.');
  89. }
  90. if (! Schema::hasColumn('orders', 'vip_plus_amount')) {
  91. $this->warn('orders.vip_plus_amount is missing. Plus fee amounts will not be imported.');
  92. }
  93. if (! Schema::hasColumn('orders', 'vip_discount_amount')) {
  94. $this->warn('orders.vip_discount_amount is missing. Magento member discounts will not be imported.');
  95. }
  96. if (! Schema::hasColumn('shipments', 'migrated_from_asteria_id')) {
  97. $this->warn('shipments.migrated_from_asteria_id is missing. Run php artisan migrate to import Magento shipments.');
  98. }
  99. $channel = core()->getDefaultChannel() ?? core()->getCurrentChannel();
  100. if (! $channel) {
  101. $this->error('Bagisto default channel was not found.');
  102. return self::FAILURE;
  103. }
  104. $reader = new Magento1OrderReader($connection);
  105. $lastId = $resetProgress ? 0 : (int) Cache::get(self::PROGRESS_KEY, 0);
  106. if ($resetProgress) {
  107. Cache::forget(self::PROGRESS_KEY);
  108. }
  109. if ($lastId > 0) {
  110. $this->line("Resuming from Asteria entity_id > {$lastId} (use --reset-progress to restart).");
  111. }
  112. $created = 0;
  113. $skipped = 0;
  114. $itemsImported = 0;
  115. $addressesImported = 0;
  116. $shipmentsImported = 0;
  117. $batchNumber = 0;
  118. $this->info($dryRun ? '[DRY RUN] Scanning Magento orders…' : 'Migrating Magento orders…');
  119. do {
  120. $started = microtime(true);
  121. $orders = $reader->fetchOrders($lastId, $batchSize);
  122. if ($orders->isEmpty()) {
  123. break;
  124. }
  125. $batchNumber++;
  126. $lastId = (int) $orders->max('entity_id');
  127. $orderIds = $orders->pluck('entity_id')->map(fn ($id) => (int) $id)->all();
  128. $items = $reader->fetchItems($orderIds)->groupBy(fn (array $row) => (int) $row['order_id']);
  129. $addresses = $reader->fetchAddresses($orderIds)->groupBy(fn (array $row) => (int) $row['parent_id']);
  130. $payments = $reader->fetchPayments($orderIds)->groupBy(fn (array $row) => (int) $row['parent_id']);
  131. $rewardPoints = $reader->fetchRewardPoints($orderIds)->keyBy(fn (array $row) => (int) $row['order_id']);
  132. if ($dryRun) {
  133. $shipments = $reader->fetchShipments($orderIds);
  134. $created += $orders->count();
  135. $itemsImported += $items->flatten(1)->count();
  136. $addressesImported += $addresses->flatten(1)->count();
  137. $shipmentsImported += $shipments->count();
  138. $this->line(sprintf(
  139. ' Batch #%d: %d orders, %d items, %d addresses, %d shipments (last entity_id=%d) [skipped – dry-run] (%.1fs)',
  140. $batchNumber,
  141. $orders->count(),
  142. $items->flatten(1)->count(),
  143. $addresses->flatten(1)->count(),
  144. $shipments->count(),
  145. $lastId,
  146. microtime(true) - $started
  147. ));
  148. continue;
  149. }
  150. [$customersByAsteriaId, $customersByEmail] = $this->loadCustomers($orders);
  151. $productIndex = $this->loadProductIndex($items->collapse(), $reader);
  152. $result = $this->persistBatch(
  153. $orders,
  154. $items,
  155. $addresses,
  156. $payments,
  157. $rewardPoints,
  158. $channel,
  159. $customersByAsteriaId,
  160. $customersByEmail,
  161. $productIndex
  162. );
  163. $shipments = $reader->fetchShipments($orderIds);
  164. $shipmentIds = $shipments->pluck('entity_id')->map(fn ($id) => (int) $id)->all();
  165. $shipmentItems = $reader->fetchShipmentItems($shipmentIds)->groupBy(fn (array $row) => (int) $row['parent_id']);
  166. $shipmentTracks = $reader->fetchShipmentTracks($shipmentIds)->groupBy(fn (array $row) => (int) $row['parent_id']);
  167. $extras = $this->syncOrderExtras($orders, $items, $payments, $shipments, $shipmentItems, $shipmentTracks);
  168. Cache::put(self::PROGRESS_KEY, $lastId, now()->addDays(30));
  169. $created += $result['created'];
  170. $skipped += $result['skipped'];
  171. $itemsImported += $result['items'];
  172. $addressesImported += $result['addresses'];
  173. $shipmentsImported += $extras['shipments'];
  174. $this->line(sprintf(
  175. ' Batch #%d: created=%d skipped=%d items=%d addresses=%d shipments=%d (last entity_id=%d) (%.1fs)',
  176. $batchNumber,
  177. $result['created'],
  178. $result['skipped'],
  179. $result['items'],
  180. $result['addresses'],
  181. $extras['shipments'],
  182. $lastId,
  183. microtime(true) - $started
  184. ));
  185. Log::info('MigrateAsteriaOrders: batch '.$batchNumber.', last_id='.$lastId);
  186. } while ($orders->count() === $batchSize);
  187. $this->newLine();
  188. $this->info("Done. Batches: {$batchNumber}, created: {$created}, skipped: {$skipped}, items: {$itemsImported}, addresses: {$addressesImported}, shipments: {$shipmentsImported}.");
  189. if (! $dryRun) {
  190. $linked = $this->backfillMissingProductIds($reader);
  191. if ($linked > 0) {
  192. $this->info("Backfilled product_id on {$linked} existing order items.");
  193. }
  194. }
  195. return self::SUCCESS;
  196. }
  197. /**
  198. * @param Collection<int, array<string, mixed>> $orders
  199. * @param Collection<int, Collection<int, array<string, mixed>>> $items
  200. * @param Collection<int, Collection<int, array<string, mixed>>> $addresses
  201. * @param Collection<int, Collection<int, array<string, mixed>>> $payments
  202. * @param Collection<int, array<string, mixed>> $rewardPoints
  203. * @param array<int, Customer> $customersByAsteriaId
  204. * @param array<string, Customer> $customersByEmail
  205. * @param array{by_sku: array<string, Product>, by_asteria_id: array<int, Product>, catalog_sku: array<int, string>} $productIndex
  206. * @return array{created: int, skipped: int, items: int, addresses: int}
  207. */
  208. private function persistBatch(
  209. Collection $orders,
  210. Collection $items,
  211. Collection $addresses,
  212. Collection $payments,
  213. Collection $rewardPoints,
  214. Channel $channel,
  215. array $customersByAsteriaId,
  216. array $customersByEmail,
  217. array $productIndex
  218. ): array {
  219. $asteriaIds = $orders->pluck('entity_id')->map(fn ($id) => (int) $id)->filter()->unique()->values()->all();
  220. $incrementIds = $orders
  221. ->pluck('increment_id')
  222. ->map(fn ($id) => trim((string) $id))
  223. ->filter()
  224. ->unique()
  225. ->values()
  226. ->all();
  227. $existingAsteria = $asteriaIds === []
  228. ? []
  229. : DB::table('orders')
  230. ->whereIn('migrated_from_asteria_id', $asteriaIds)
  231. ->pluck('migrated_from_asteria_id')
  232. ->map(fn ($id) => (int) $id)
  233. ->flip()
  234. ->all();
  235. $existingIncrements = $incrementIds === []
  236. ? []
  237. : DB::table('orders')
  238. ->whereIn('increment_id', $incrementIds)
  239. ->pluck('increment_id')
  240. ->map(fn ($id) => (string) $id)
  241. ->flip()
  242. ->all();
  243. $now = now()->format('Y-m-d H:i:s');
  244. $orderInserts = [];
  245. $pending = [];
  246. $skipped = 0;
  247. $seenIncrements = [];
  248. foreach ($orders as $row) {
  249. $asteriaId = (int) $row['entity_id'];
  250. $incrementId = trim((string) ($row['increment_id'] ?? ''));
  251. if ($asteriaId < 1 || $incrementId === ''
  252. || isset($existingAsteria[$asteriaId])
  253. || isset($existingIncrements[$incrementId])
  254. || isset($seenIncrements[$incrementId])) {
  255. $skipped++;
  256. continue;
  257. }
  258. $seenIncrements[$incrementId] = true;
  259. $orderInserts[] = $this->buildOrderRow(
  260. $row,
  261. $channel,
  262. $customersByAsteriaId,
  263. $customersByEmail,
  264. $items->get($asteriaId, collect()),
  265. $rewardPoints->get($asteriaId),
  266. $now
  267. );
  268. $pending[] = $row;
  269. }
  270. $created = count($orderInserts);
  271. $importedItems = 0;
  272. $importedAddresses = 0;
  273. if ($orderInserts === []) {
  274. return ['created' => 0, 'skipped' => $skipped, 'items' => 0, 'addresses' => 0];
  275. }
  276. DB::transaction(function () use (
  277. $orderInserts,
  278. $pending,
  279. $items,
  280. $addresses,
  281. $payments,
  282. $productIndex,
  283. $customersByAsteriaId,
  284. $customersByEmail,
  285. &$importedItems,
  286. &$importedAddresses
  287. ) {
  288. $this->insertRows('orders', $orderInserts);
  289. $idMap = DB::table('orders')
  290. ->whereIn('migrated_from_asteria_id', array_column($orderInserts, 'migrated_from_asteria_id'))
  291. ->pluck('id', 'migrated_from_asteria_id')
  292. ->mapWithKeys(fn ($id, $asteriaId) => [(int) $asteriaId => (int) $id])
  293. ->all();
  294. $paymentInserts = [];
  295. $addressInserts = [];
  296. $parentItemInserts = [];
  297. $childItemRows = [];
  298. $now = now()->format('Y-m-d H:i:s');
  299. foreach ($pending as $row) {
  300. $asteriaId = (int) $row['entity_id'];
  301. $orderId = $idMap[$asteriaId] ?? null;
  302. if (! $orderId) {
  303. continue;
  304. }
  305. $customer = $this->resolveCustomer($row, $customersByAsteriaId, $customersByEmail);
  306. $email = strtolower(trim((string) ($row['customer_email'] ?? '')));
  307. if ($email === '' && $customer) {
  308. $email = strtolower((string) $customer->email);
  309. }
  310. $paymentInserts[] = $this->buildPaymentRow($orderId, $payments->get($asteriaId, collect())->first(), $now);
  311. foreach ($addresses->get($asteriaId, collect()) as $addressRow) {
  312. $addressInserts[] = $this->buildAddressRow($orderId, $addressRow, $customer, $email, $row, $now);
  313. $importedAddresses++;
  314. }
  315. $itemRows = $items->get($asteriaId, collect());
  316. $parents = $itemRows->filter(fn (array $item) => empty($item['parent_item_id']));
  317. $children = $itemRows->filter(fn (array $item) => ! empty($item['parent_item_id']));
  318. foreach ($parents as $itemRow) {
  319. $parentItemInserts[] = $this->buildItemRow($orderId, $itemRow, null, $productIndex, $now);
  320. $importedItems++;
  321. }
  322. foreach ($children as $itemRow) {
  323. $childItemRows[] = ['order_id' => $orderId, 'row' => $itemRow];
  324. $importedItems++;
  325. }
  326. }
  327. if ($paymentInserts !== []) {
  328. $this->insertRows('order_payment', $paymentInserts);
  329. }
  330. if ($addressInserts !== []) {
  331. $this->insertRows('addresses', $addressInserts);
  332. }
  333. if ($parentItemInserts !== []) {
  334. $this->insertRows('order_items', $parentItemInserts);
  335. }
  336. if ($childItemRows !== []) {
  337. $itemIdMap = $this->loadInsertedItemIds(array_values($idMap));
  338. $childInserts = [];
  339. foreach ($childItemRows as $child) {
  340. $parentId = $itemIdMap[(int) $child['row']['parent_item_id']] ?? null;
  341. $childInserts[] = $this->buildItemRow($child['order_id'], $child['row'], $parentId, $productIndex, $now);
  342. }
  343. $this->insertRows('order_items', $childInserts);
  344. }
  345. });
  346. return [
  347. 'created' => $created,
  348. 'skipped' => $skipped,
  349. 'items' => $importedItems,
  350. 'addresses' => $importedAddresses,
  351. ];
  352. }
  353. /**
  354. * Backfill remote_ip / product options / PayPal details and import Magento
  355. * shipments for both newly created and previously skipped Asteria orders.
  356. *
  357. * @param Collection<int, array<string, mixed>> $orders
  358. * @param Collection<int, Collection<int, array<string, mixed>>> $items
  359. * @param Collection<int, Collection<int, array<string, mixed>>> $payments
  360. * @param Collection<int, array<string, mixed>> $shipments
  361. * @param Collection<int, Collection<int, array<string, mixed>>> $shipmentItems
  362. * @param Collection<int, Collection<int, array<string, mixed>>> $shipmentTracks
  363. * @return array{shipments: int}
  364. */
  365. private function syncOrderExtras(
  366. Collection $orders,
  367. Collection $items,
  368. Collection $payments,
  369. Collection $shipments,
  370. Collection $shipmentItems,
  371. Collection $shipmentTracks
  372. ): array {
  373. $asteriaIds = $orders->pluck('entity_id')->map(fn ($id) => (int) $id)->filter()->unique()->values()->all();
  374. if ($asteriaIds === []) {
  375. return ['shipments' => 0];
  376. }
  377. $orderColumns = ['id', 'migrated_from_asteria_id', 'customer_id', 'customer_type'];
  378. if ($this->hasDestinationColumn('remote_ip')) {
  379. $orderColumns[] = 'remote_ip';
  380. }
  381. if ($this->hasDestinationColumn('giftcard_amount')) {
  382. $orderColumns[] = 'giftcard_amount';
  383. $orderColumns[] = 'base_giftcard_amount';
  384. if ($this->hasDestinationColumn('giftcard_number')) {
  385. $orderColumns[] = 'giftcard_number';
  386. }
  387. }
  388. if ($this->hasDestinationColumn('vip_plus_amount')) {
  389. $orderColumns[] = 'vip_plus_amount';
  390. $orderColumns[] = 'base_vip_plus_amount';
  391. }
  392. if ($this->hasDestinationColumn('vip_discount_amount')) {
  393. $orderColumns[] = 'vip_discount_amount';
  394. $orderColumns[] = 'base_vip_discount_amount';
  395. }
  396. $bagistoOrders = DB::table('orders')
  397. ->whereIn('migrated_from_asteria_id', $asteriaIds)
  398. ->get($orderColumns);
  399. if ($bagistoOrders->isEmpty()) {
  400. return ['shipments' => 0];
  401. }
  402. $orderIdMap = $bagistoOrders
  403. ->mapWithKeys(fn ($order) => [(int) $order->migrated_from_asteria_id => (int) $order->id])
  404. ->all();
  405. $importedShipments = 0;
  406. DB::transaction(function () use (
  407. $orders,
  408. $items,
  409. $payments,
  410. $shipments,
  411. $shipmentItems,
  412. $shipmentTracks,
  413. $bagistoOrders,
  414. $orderIdMap,
  415. &$importedShipments
  416. ) {
  417. $this->syncRemoteIps($orders, $bagistoOrders);
  418. $this->syncGiftcardAndPlus($orders, $bagistoOrders);
  419. $this->syncPaypalPayments($payments, $orderIdMap);
  420. $this->syncItemProductOptions($items, $orderIdMap);
  421. $importedShipments = $this->persistShipments(
  422. $shipments,
  423. $shipmentItems,
  424. $shipmentTracks,
  425. $bagistoOrders,
  426. $orderIdMap
  427. );
  428. });
  429. return ['shipments' => $importedShipments];
  430. }
  431. /**
  432. * @param Collection<int, array<string, mixed>> $orders
  433. * @param Collection<int, object> $bagistoOrders
  434. */
  435. private function syncRemoteIps(Collection $orders, $bagistoOrders): void
  436. {
  437. if (! $this->hasDestinationColumn('remote_ip')) {
  438. return;
  439. }
  440. $remoteIps = $orders
  441. ->mapWithKeys(fn (array $row) => [(int) $row['entity_id'] => $this->nullableString($row['remote_ip'] ?? null)])
  442. ->all();
  443. foreach ($bagistoOrders as $order) {
  444. $remoteIp = $remoteIps[(int) $order->migrated_from_asteria_id] ?? null;
  445. if ($remoteIp === null || (string) $order->remote_ip === $remoteIp) {
  446. continue;
  447. }
  448. DB::table('orders')->where('id', $order->id)->update(['remote_ip' => $remoteIp]);
  449. }
  450. }
  451. /**
  452. * @param Collection<int, array<string, mixed>> $orders
  453. * @param Collection<int, object> $bagistoOrders
  454. */
  455. private function syncGiftcardAndPlus(Collection $orders, $bagistoOrders): void
  456. {
  457. if (! $this->hasDestinationColumn('giftcard_amount')
  458. && ! $this->hasDestinationColumn('vip_plus_amount')
  459. && ! $this->hasDestinationColumn('vip_discount_amount')) {
  460. return;
  461. }
  462. $byAsteriaId = $orders->keyBy(fn (array $row) => (int) $row['entity_id']);
  463. foreach ($bagistoOrders as $order) {
  464. $row = $byAsteriaId->get((int) $order->migrated_from_asteria_id);
  465. if (! is_array($row)) {
  466. continue;
  467. }
  468. $payload = $this->mapGiftcardAndPlus($row);
  469. if ($payload === []) {
  470. continue;
  471. }
  472. $changed = false;
  473. foreach ($payload as $column => $value) {
  474. $current = $order->{$column} ?? null;
  475. if (is_numeric($value)) {
  476. if ($this->money($current) !== $this->money($value)) {
  477. $changed = true;
  478. break;
  479. }
  480. continue;
  481. }
  482. if ((string) ($current ?? '') !== (string) ($value ?? '')) {
  483. $changed = true;
  484. break;
  485. }
  486. }
  487. if (! $changed) {
  488. continue;
  489. }
  490. DB::table('orders')->where('id', $order->id)->update($payload);
  491. }
  492. }
  493. /**
  494. * @param Collection<int, Collection<int, array<string, mixed>>> $payments
  495. * @param array<int, int> $orderIdMap
  496. */
  497. private function syncPaypalPayments(Collection $payments, array $orderIdMap): void
  498. {
  499. $bagistoOrderIds = array_values($orderIdMap);
  500. if ($bagistoOrderIds === [] || $payments->isEmpty()) {
  501. return;
  502. }
  503. $existing = DB::table('order_payment')
  504. ->whereIn('order_id', $bagistoOrderIds)
  505. ->get(['id', 'order_id', 'additional'])
  506. ->keyBy(fn ($row) => (int) $row->order_id);
  507. foreach ($orderIdMap as $asteriaOrderId => $bagistoOrderId) {
  508. $paymentRow = $payments->get($asteriaOrderId, collect())->first();
  509. if (! is_array($paymentRow) || ! $this->isPaypalMethod($paymentRow['method'] ?? null)) {
  510. continue;
  511. }
  512. $current = $existing->get($bagistoOrderId);
  513. if (! $current) {
  514. continue;
  515. }
  516. $additional = $this->appendPaypalAdditional(
  517. $this->decodeAdditional($current->additional),
  518. $paymentRow
  519. );
  520. $transactionId = $this->nullableString($paymentRow['last_trans_id'] ?? null);
  521. if ($transactionId !== null) {
  522. $additional['last_trans_id'] = $transactionId;
  523. }
  524. if ($additional == $this->decodeAdditional($current->additional)) {
  525. continue;
  526. }
  527. DB::table('order_payment')->where('id', $current->id)->update([
  528. 'additional' => $this->encodeAdditional($additional),
  529. ]);
  530. }
  531. }
  532. /**
  533. * @param Collection<int, Collection<int, array<string, mixed>>> $items
  534. * @param array<int, int> $orderIdMap
  535. */
  536. private function syncItemProductOptions(Collection $items, array $orderIdMap): void
  537. {
  538. $bagistoOrderIds = array_values($orderIdMap);
  539. if ($bagistoOrderIds === []) {
  540. return;
  541. }
  542. $existing = [];
  543. foreach (DB::table('order_items')->whereIn('order_id', $bagistoOrderIds)->get(['id', 'additional']) as $item) {
  544. $additional = $this->decodeAdditional($item->additional);
  545. $asteriaItemId = (int) ($additional['asteria_item_id'] ?? 0);
  546. if ($asteriaItemId > 0) {
  547. $existing[$asteriaItemId] = [
  548. 'id' => (int) $item->id,
  549. 'additional' => $additional,
  550. ];
  551. }
  552. }
  553. foreach ($items->flatten(1) as $row) {
  554. if (! is_array($row)) {
  555. continue;
  556. }
  557. $asteriaItemId = (int) ($row['item_id'] ?? 0);
  558. $current = $existing[$asteriaItemId] ?? null;
  559. if (! $current) {
  560. continue;
  561. }
  562. $merged = $this->mergeItemAdditional($current['additional'], $row);
  563. if ($merged === $current['additional']) {
  564. continue;
  565. }
  566. DB::table('order_items')->where('id', $current['id'])->update([
  567. 'additional' => $this->encodeAdditional($merged),
  568. ]);
  569. }
  570. }
  571. /**
  572. * @param Collection<int, array<string, mixed>> $shipments
  573. * @param Collection<int, Collection<int, array<string, mixed>>> $shipmentItems
  574. * @param Collection<int, Collection<int, array<string, mixed>>> $shipmentTracks
  575. * @param Collection<int, object> $bagistoOrders
  576. * @param array<int, int> $orderIdMap
  577. */
  578. private function persistShipments(
  579. Collection $shipments,
  580. Collection $shipmentItems,
  581. Collection $shipmentTracks,
  582. $bagistoOrders,
  583. array $orderIdMap
  584. ): int {
  585. if ($shipments->isEmpty() || ! Schema::hasColumn('shipments', 'migrated_from_asteria_id')) {
  586. return 0;
  587. }
  588. $asteriaShipmentIds = $shipments
  589. ->pluck('entity_id')
  590. ->map(fn ($id) => (int) $id)
  591. ->filter()
  592. ->unique()
  593. ->values()
  594. ->all();
  595. $existing = $asteriaShipmentIds === []
  596. ? []
  597. : DB::table('shipments')
  598. ->whereIn('migrated_from_asteria_id', $asteriaShipmentIds)
  599. ->pluck('migrated_from_asteria_id')
  600. ->map(fn ($id) => (int) $id)
  601. ->flip()
  602. ->all();
  603. $ordersByAsteriaId = $bagistoOrders->keyBy(fn ($order) => (int) $order->migrated_from_asteria_id);
  604. $shippingAddressIds = DB::table('addresses')
  605. ->whereIn('order_id', array_values($orderIdMap))
  606. ->where('address_type', OrderAddress::ADDRESS_TYPE_SHIPPING)
  607. ->pluck('id', 'order_id');
  608. $itemIdMap = $this->loadInsertedItemIds(array_values($orderIdMap));
  609. $orderItems = $this->loadOrderItemsById(array_values($itemIdMap));
  610. $inventory = $this->defaultInventorySource();
  611. $hasInclTax = Schema::hasColumn('shipment_items', 'price_incl_tax');
  612. $now = now()->format('Y-m-d H:i:s');
  613. $inserts = [];
  614. $pending = [];
  615. foreach ($shipments as $row) {
  616. $asteriaId = (int) ($row['entity_id'] ?? 0);
  617. $magentoOrderId = (int) ($row['order_id'] ?? 0);
  618. $orderId = $orderIdMap[$magentoOrderId] ?? null;
  619. $order = $ordersByAsteriaId->get($magentoOrderId);
  620. if ($asteriaId < 1 || ! $orderId || ! $order || isset($existing[$asteriaId])) {
  621. continue;
  622. }
  623. $tracks = $shipmentTracks->get($asteriaId, collect());
  624. [$carrierCode, $carrierTitle, $trackNumber] = $this->mapShipmentTracks($tracks);
  625. $inserts[] = [
  626. 'migrated_from_asteria_id' => $asteriaId,
  627. 'status' => null,
  628. 'total_qty' => $this->qty($row['total_qty'] ?? 0),
  629. 'total_weight' => $this->money($row['total_weight'] ?? 0),
  630. 'carrier_code' => $carrierCode,
  631. 'carrier_title' => $carrierTitle,
  632. 'track_number' => $trackNumber,
  633. 'email_sent' => ((int) ($row['email_sent'] ?? 0)) === 1 ? 1 : 0,
  634. 'customer_id' => $order->customer_id,
  635. 'customer_type' => $order->customer_type,
  636. 'order_id' => $orderId,
  637. 'order_address_id' => $shippingAddressIds[$orderId] ?? null,
  638. 'inventory_source_id' => $inventory['id'],
  639. 'inventory_source_name' => $inventory['name'],
  640. 'created_at' => ! empty($row['created_at']) ? $row['created_at'] : $now,
  641. 'updated_at' => $now,
  642. ];
  643. $pending[] = $row;
  644. }
  645. if ($inserts === []) {
  646. return 0;
  647. }
  648. $this->insertRows('shipments', $inserts);
  649. $idMap = DB::table('shipments')
  650. ->whereIn('migrated_from_asteria_id', array_column($inserts, 'migrated_from_asteria_id'))
  651. ->pluck('id', 'migrated_from_asteria_id')
  652. ->mapWithKeys(fn ($id, $asteriaId) => [(int) $asteriaId => (int) $id])
  653. ->all();
  654. $itemInserts = [];
  655. foreach ($pending as $row) {
  656. $asteriaId = (int) $row['entity_id'];
  657. $shipmentId = $idMap[$asteriaId] ?? null;
  658. if (! $shipmentId) {
  659. continue;
  660. }
  661. foreach ($shipmentItems->get($asteriaId, collect()) as $itemRow) {
  662. $orderItemId = isset($itemRow['order_item_id']) ? (int) $itemRow['order_item_id'] : 0;
  663. $bagistoItemId = $orderItemId > 0 ? ($itemIdMap[$orderItemId] ?? null) : null;
  664. $orderItem = $bagistoItemId ? ($orderItems[$bagistoItemId] ?? null) : null;
  665. $price = array_key_exists('price', $itemRow) && $itemRow['price'] !== null
  666. ? $this->money($itemRow['price'])
  667. : $this->money($orderItem->price ?? 0);
  668. $qty = $this->qty($itemRow['qty'] ?? 0);
  669. $total = array_key_exists('row_total', $itemRow) && $itemRow['row_total'] !== null
  670. ? $this->money($itemRow['row_total'])
  671. : $price * $qty;
  672. $basePrice = $this->money($orderItem->base_price ?? $price);
  673. $payload = [
  674. 'name' => $this->nullableString($itemRow['name'] ?? null)
  675. ?? $this->nullableString($orderItem->name ?? null)
  676. ?? '-',
  677. 'description' => $this->nullableString($itemRow['description'] ?? null),
  678. 'sku' => $this->nullableString($itemRow['sku'] ?? null)
  679. ?? $this->nullableString($orderItem->sku ?? null),
  680. 'qty' => $qty,
  681. 'weight' => $this->money($itemRow['weight'] ?? $orderItem->weight ?? 0),
  682. 'price' => $price,
  683. 'base_price' => $basePrice,
  684. 'total' => $total,
  685. 'base_total' => $basePrice * $qty,
  686. 'product_id' => $orderItem->product_id ?? null,
  687. 'product_type' => $orderItem->product_type ?? null,
  688. 'order_item_id'=> $bagistoItemId,
  689. 'shipment_id' => $shipmentId,
  690. 'additional' => $this->encodeAdditional([
  691. 'asteria_shipment_item_id' => (int) ($itemRow['entity_id'] ?? 0),
  692. ]),
  693. 'created_at' => $now,
  694. 'updated_at' => $now,
  695. ];
  696. if ($hasInclTax) {
  697. $payload['price_incl_tax'] = $this->money($orderItem->price_incl_tax ?? $price);
  698. $payload['base_price_incl_tax'] = $this->money($orderItem->base_price_incl_tax ?? $basePrice);
  699. }
  700. $itemInserts[] = $payload;
  701. }
  702. }
  703. if ($itemInserts !== []) {
  704. $this->insertRows('shipment_items', $itemInserts);
  705. }
  706. return count($inserts);
  707. }
  708. /**
  709. * @param array<int, int> $ids
  710. * @return array<int, object>
  711. */
  712. private function loadOrderItemsById(array $ids): array
  713. {
  714. if ($ids === []) {
  715. return [];
  716. }
  717. $columns = ['id', 'name', 'sku', 'weight', 'price', 'base_price', 'product_id', 'product_type'];
  718. if (Schema::hasColumn('order_items', 'price_incl_tax')) {
  719. $columns[] = 'price_incl_tax';
  720. $columns[] = 'base_price_incl_tax';
  721. }
  722. return DB::table('order_items')
  723. ->whereIn('id', $ids)
  724. ->get($columns)
  725. ->keyBy(fn ($item) => (int) $item->id)
  726. ->all();
  727. }
  728. /**
  729. * @param Collection<int, array<string, mixed>> $tracks
  730. * @return array{0: ?string, 1: ?string, 2: ?string}
  731. */
  732. private function mapShipmentTracks($tracks): array
  733. {
  734. $numbers = [];
  735. $carrierCode = null;
  736. $carrierTitle = null;
  737. foreach ($tracks as $track) {
  738. $number = $this->nullableString($track['track_number'] ?? null);
  739. if ($number !== null) {
  740. $numbers[] = $number;
  741. }
  742. if ($carrierCode === null) {
  743. $carrierCode = $this->nullableString($track['carrier_code'] ?? null);
  744. $carrierTitle = $this->nullableString($track['title'] ?? null);
  745. }
  746. }
  747. $numbers = array_values(array_unique($numbers));
  748. return [
  749. $carrierCode,
  750. $carrierTitle,
  751. $numbers === [] ? null : implode(', ', $numbers),
  752. ];
  753. }
  754. /**
  755. * @return array{id: int|null, name: string|null}
  756. */
  757. private function defaultInventorySource(): array
  758. {
  759. if ($this->defaultInventorySource !== null) {
  760. return $this->defaultInventorySource;
  761. }
  762. $row = Schema::hasTable('inventory_sources')
  763. ? DB::table('inventory_sources')->orderBy('id')->first(['id', 'name'])
  764. : null;
  765. return $this->defaultInventorySource = [
  766. 'id' => $row ? (int) $row->id : null,
  767. 'name' => $row ? $this->nullableString($row->name ?? null) : null,
  768. ];
  769. }
  770. /**
  771. * @param array<string, mixed> $row
  772. * @param array<int, Customer> $customersByAsteriaId
  773. * @param array<string, Customer> $customersByEmail
  774. * @param Collection<int, array<string, mixed>> $itemRows
  775. * @param array<string, mixed>|null $rewardRow
  776. * @return array<string, mixed>
  777. */
  778. private function buildOrderRow(
  779. array $row,
  780. Channel $channel,
  781. array $customersByAsteriaId,
  782. array $customersByEmail,
  783. $itemRows,
  784. ?array $rewardRow,
  785. string $now
  786. ): array {
  787. $customer = $this->resolveCustomer($row, $customersByAsteriaId, $customersByEmail);
  788. $email = strtolower(trim((string) ($row['customer_email'] ?? '')));
  789. if ($email === '' && $customer) {
  790. $email = strtolower((string) $customer->email);
  791. }
  792. $subTotal = $this->money($row['subtotal'] ?? 0);
  793. $baseSubTotal = $this->money($row['base_subtotal'] ?? $subTotal);
  794. $taxAmount = $this->money($row['tax_amount'] ?? 0);
  795. $baseTaxAmount = $this->money($row['base_tax_amount'] ?? $taxAmount);
  796. $shippingAmount = $this->money($row['shipping_amount'] ?? 0);
  797. $baseShippingAmount = $this->money($row['base_shipping_amount'] ?? $shippingAmount);
  798. $shippingTaxAmount = $this->money($row['shipping_tax_amount'] ?? 0);
  799. $baseShippingTaxAmount = $this->money($row['base_shipping_tax_amount'] ?? $shippingTaxAmount);
  800. $discountAmount = $this->money($row['discount_amount'] ?? 0);
  801. $baseDiscountAmount = $this->money($row['base_discount_amount'] ?? $discountAmount);
  802. $grandTotal = $this->money($row['grand_total'] ?? 0);
  803. $baseGrandTotal = $this->money($row['base_grand_total'] ?? $grandTotal);
  804. $subTotalInclTax = array_key_exists('subtotal_incl_tax', $row)
  805. ? $this->money($row['subtotal_incl_tax'])
  806. : $subTotal + $taxAmount;
  807. $baseSubTotalInclTax = array_key_exists('base_subtotal_incl_tax', $row)
  808. ? $this->money($row['base_subtotal_incl_tax'])
  809. : $baseSubTotal + $baseTaxAmount;
  810. $shippingInclTax = array_key_exists('shipping_incl_tax', $row)
  811. ? $this->money($row['shipping_incl_tax'])
  812. : $shippingAmount + $shippingTaxAmount;
  813. $baseShippingInclTax = array_key_exists('base_shipping_incl_tax', $row)
  814. ? $this->money($row['base_shipping_incl_tax'])
  815. : $baseShippingAmount + $baseShippingTaxAmount;
  816. $insert = [
  817. 'migrated_from_asteria_id' => (int) $row['entity_id'],
  818. 'increment_id' => trim((string) $row['increment_id']),
  819. 'status' => $this->mapStatus($row),
  820. 'channel_name' => $channel->name,
  821. 'is_guest' => $customer ? 0 : 1,
  822. 'customer_email' => $email !== '' ? $email : null,
  823. 'customer_first_name' => $this->requiredName($row['customer_firstname'] ?? null, $customer?->first_name ?? $email),
  824. 'customer_last_name' => trim((string) ($row['customer_lastname'] ?? '')) ?: ($customer?->last_name ?? '-'),
  825. 'customer_id' => $customer?->id,
  826. 'customer_type' => $customer ? Customer::class : null,
  827. 'channel_id' => $channel->id,
  828. 'channel_type' => get_class($channel),
  829. 'cart_id' => null,
  830. 'shipping_method' => $this->nullableString($row['shipping_method'] ?? null),
  831. 'shipping_title' => $this->nullableString($row['shipping_description'] ?? null),
  832. 'shipping_description' => $this->nullableString($row['shipping_description'] ?? null),
  833. 'coupon_code' => $this->nullableString($row['coupon_code'] ?? null),
  834. 'is_gift' => 0,
  835. 'total_item_count' => $this->qty($row['total_item_count'] ?? $itemRows->count()),
  836. 'total_qty_ordered' => $this->qty($row['total_qty_ordered'] ?? $itemRows->sum(fn (array $item) => (float) ($item['qty_ordered'] ?? 0))),
  837. 'base_currency_code' => $this->nullableString($row['base_currency_code'] ?? null) ?? 'USD',
  838. 'channel_currency_code' => $this->nullableString($row['store_currency_code'] ?? null)
  839. ?? $this->nullableString($row['order_currency_code'] ?? null)
  840. ?? 'USD',
  841. 'order_currency_code' => $this->nullableString($row['order_currency_code'] ?? null) ?? 'USD',
  842. 'grand_total' => $grandTotal,
  843. 'base_grand_total' => $baseGrandTotal,
  844. 'grand_total_invoiced' => $this->money($row['total_invoiced'] ?? 0),
  845. 'base_grand_total_invoiced' => $this->money($row['base_total_invoiced'] ?? 0),
  846. 'grand_total_refunded' => $this->money($row['total_refunded'] ?? 0),
  847. 'base_grand_total_refunded' => $this->money($row['base_total_refunded'] ?? 0),
  848. 'sub_total' => $subTotal,
  849. 'base_sub_total' => $baseSubTotal,
  850. 'sub_total_incl_tax' => $subTotalInclTax,
  851. 'base_sub_total_incl_tax' => $baseSubTotalInclTax,
  852. 'sub_total_invoiced' => $this->money($row['subtotal_invoiced'] ?? 0),
  853. 'base_sub_total_invoiced' => $this->money($row['base_subtotal_invoiced'] ?? 0),
  854. 'sub_total_refunded' => $this->money($row['subtotal_refunded'] ?? 0),
  855. 'base_sub_total_refunded' => $this->money($row['base_subtotal_refunded'] ?? 0),
  856. 'discount_amount' => $discountAmount,
  857. 'base_discount_amount' => $baseDiscountAmount,
  858. 'discount_invoiced' => $this->money($row['discount_invoiced'] ?? 0),
  859. 'base_discount_invoiced' => $this->money($row['base_discount_invoiced'] ?? 0),
  860. 'discount_refunded' => $this->money($row['discount_refunded'] ?? 0),
  861. 'base_discount_refunded' => $this->money($row['base_discount_refunded'] ?? 0),
  862. 'tax_amount' => $taxAmount,
  863. 'base_tax_amount' => $baseTaxAmount,
  864. 'tax_amount_invoiced' => $this->money($row['tax_invoiced'] ?? 0),
  865. 'base_tax_amount_invoiced' => $this->money($row['base_tax_invoiced'] ?? 0),
  866. 'tax_amount_refunded' => $this->money($row['tax_refunded'] ?? 0),
  867. 'base_tax_amount_refunded' => $this->money($row['base_tax_refunded'] ?? 0),
  868. 'shipping_amount' => $shippingAmount,
  869. 'base_shipping_amount' => $baseShippingAmount,
  870. 'shipping_amount_incl_tax' => $shippingInclTax,
  871. 'base_shipping_amount_incl_tax' => $baseShippingInclTax,
  872. 'shipping_invoiced' => $this->money($row['shipping_invoiced'] ?? 0),
  873. 'base_shipping_invoiced' => $this->money($row['base_shipping_invoiced'] ?? 0),
  874. 'shipping_refunded' => $this->money($row['shipping_refunded'] ?? 0),
  875. 'base_shipping_refunded' => $this->money($row['base_shipping_refunded'] ?? 0),
  876. 'shipping_tax_amount' => $shippingTaxAmount,
  877. 'base_shipping_tax_amount' => $baseShippingTaxAmount,
  878. 'created_at' => ! empty($row['created_at']) ? $row['created_at'] : $now,
  879. 'updated_at' => $now,
  880. ];
  881. if ($this->hasDestinationColumn('remote_ip')) {
  882. $insert['remote_ip'] = $this->nullableString($row['remote_ip'] ?? null);
  883. }
  884. if ($this->hasDestinationColumn('shipping_discount_amount')) {
  885. $insert['shipping_discount_amount'] = $this->money($row['shipping_discount_amount'] ?? 0);
  886. $insert['base_shipping_discount_amount'] = $this->money(
  887. $row['base_shipping_discount_amount'] ?? $insert['shipping_discount_amount']
  888. );
  889. }
  890. return $this->appendRewardAndInsurance(
  891. array_merge($insert, $this->mapGiftcardAndPlus($row)),
  892. $row,
  893. $rewardRow
  894. );
  895. }
  896. /**
  897. * Magento stores giftcard_amount and member_amount as negative discounts; Bagisto stores positive amounts.
  898. * Magento member_free_amount is the Plus membership fee (14.99 / 17.90).
  899. *
  900. * @param array<string, mixed> $row
  901. * @return array<string, mixed>
  902. */
  903. private function mapGiftcardAndPlus(array $row): array
  904. {
  905. $payload = [];
  906. if ($this->hasDestinationColumn('giftcard_amount')) {
  907. $amount = $this->absMoney($row['giftcard_amount'] ?? 0);
  908. $base = array_key_exists('base_giftcard_amount', $row)
  909. ? $this->absMoney($row['base_giftcard_amount'])
  910. : $amount;
  911. $payload['giftcard_amount'] = $amount;
  912. $payload['base_giftcard_amount'] = $base > 0 ? $base : $amount;
  913. if ($this->hasDestinationColumn('giftcard_number')) {
  914. $giftcardId = (int) ($row['giftcard_id'] ?? 0);
  915. $payload['giftcard_number'] = $giftcardId > 0 ? (string) $giftcardId : null;
  916. }
  917. }
  918. if ($this->hasDestinationColumn('vip_plus_amount')) {
  919. $plus = $this->absMoney($row['member_free_amount'] ?? 0);
  920. $basePlus = array_key_exists('base_member_free_amount', $row)
  921. ? $this->absMoney($row['base_member_free_amount'])
  922. : $plus;
  923. $payload['vip_plus_amount'] = $plus;
  924. $payload['base_vip_plus_amount'] = $basePlus > 0 ? $basePlus : $plus;
  925. }
  926. if ($this->hasDestinationColumn('vip_discount_amount')) {
  927. $discount = $this->absMoney($row['member_amount'] ?? 0);
  928. $baseDiscount = array_key_exists('base_member_amount', $row)
  929. ? $this->absMoney($row['base_member_amount'])
  930. : $discount;
  931. $payload['vip_discount_amount'] = $discount;
  932. $payload['base_vip_discount_amount'] = $baseDiscount > 0 ? $baseDiscount : $discount;
  933. }
  934. return $payload;
  935. }
  936. /**
  937. * @param array<string, mixed> $insert
  938. * @param array<string, mixed> $row
  939. * @param array<string, mixed>|null $rewardRow
  940. * @return array<string, mixed>
  941. */
  942. private function appendRewardAndInsurance(array $insert, array $row, ?array $rewardRow): array
  943. {
  944. $rewardRow ??= [];
  945. if ($this->hasDestinationColumn('reward_points_used')) {
  946. $usedFromOrder = (int) ($row['mw_rewardpoint'] ?? 0);
  947. $usedFromHistory = (int) ($rewardRow['reward_point'] ?? 0);
  948. $amountFromOrder = $this->absMoney($row['mw_rewardpoint_discount'] ?? 0);
  949. $amountFromHistory = $this->absMoney($rewardRow['money'] ?? 0);
  950. $insert['reward_points_used'] = max($usedFromOrder, $usedFromHistory);
  951. $insert['reward_points_amount'] = $amountFromOrder > 0 ? $amountFromOrder : $amountFromHistory;
  952. $insert['base_reward_points_amount'] = $insert['reward_points_amount'];
  953. $insert['reward_points_earned'] = (int) ($rewardRow['earn_rewardpoint'] ?? 0);
  954. }
  955. if ($this->hasDestinationColumn('shipping_insurance_amount')) {
  956. $insurance = $this->absMoney($row['amcheckoutfees_amount'] ?? 0);
  957. $baseInsurance = array_key_exists('base_amcheckoutfees_amount', $row)
  958. ? $this->absMoney($row['base_amcheckoutfees_amount'])
  959. : $insurance;
  960. $insert['shipping_insurance_amount'] = $insurance;
  961. $insert['base_shipping_insurance_amount'] = $baseInsurance > 0 ? $baseInsurance : $insurance;
  962. }
  963. return $insert;
  964. }
  965. private function hasDestinationColumn(string $column): bool
  966. {
  967. $this->destinationOrderColumns ??= [];
  968. if (! array_key_exists($column, $this->destinationOrderColumns)) {
  969. $this->destinationOrderColumns[$column] = Schema::hasColumn('orders', $column);
  970. }
  971. return $this->destinationOrderColumns[$column];
  972. }
  973. private function absMoney(mixed $value): float
  974. {
  975. return abs($this->money($value));
  976. }
  977. /**
  978. * @param array<string, mixed>|null $paymentRow
  979. * @return array<string, mixed>
  980. */
  981. private function buildPaymentRow(int $orderId, ?array $paymentRow, string $now): array
  982. {
  983. $magentoMethod = trim((string) ($paymentRow['method'] ?? ''));
  984. $additional = [
  985. 'magento_method' => $magentoMethod !== '' ? $magentoMethod : null,
  986. ];
  987. if ($paymentRow) {
  988. $additional['asteria_payment_id'] = (int) ($paymentRow['entity_id'] ?? 0);
  989. foreach (['last_trans_id', 'cc_type', 'cc_last4'] as $key) {
  990. $value = $this->nullableString($paymentRow[$key] ?? null);
  991. if ($value !== null) {
  992. $additional[$key] = $value;
  993. }
  994. }
  995. $additional = $this->appendPaypalAdditional($additional, $paymentRow);
  996. }
  997. return [
  998. 'order_id' => $orderId,
  999. 'method' => $this->mapPaymentMethod($magentoMethod),
  1000. 'method_title' => $magentoMethod !== '' ? $magentoMethod : null,
  1001. 'additional' => $this->encodeAdditional($additional),
  1002. 'created_at' => $now,
  1003. 'updated_at' => $now,
  1004. ];
  1005. }
  1006. /**
  1007. * @param array<string, mixed> $additional
  1008. * @param array<string, mixed> $paymentRow
  1009. * @return array<string, mixed>
  1010. */
  1011. private function appendPaypalAdditional(array $additional, array $paymentRow): array
  1012. {
  1013. if (! $this->isPaypalMethod($paymentRow['method'] ?? null)) {
  1014. return $additional;
  1015. }
  1016. $info = $this->unserializeMagento($paymentRow['additional_information'] ?? null) ?? [];
  1017. $fields = [
  1018. 'paypal_payer_id' => ['Payer ID', $info['paypal_payer_id'] ?? $info['paypal_express_checkout_payer_id'] ?? null],
  1019. 'paypal_payer_email' => ['Payer Email', $info['paypal_payer_email'] ?? null],
  1020. 'paypal_payer_status' => ['Payer Status', $info['paypal_payer_status'] ?? $paymentRow['account_status'] ?? null],
  1021. 'paypal_address_status' => ['Payer Address Status', $info['paypal_address_status'] ?? $paymentRow['address_status'] ?? null],
  1022. 'paypal_protection_eligibility' => ['Merchant Protection Eligibility', $info['paypal_protection_eligibility'] ?? $paymentRow['protection_eligibility'] ?? null],
  1023. 'paypal_correlation_id' => ['Last Correlation ID', $info['paypal_correlation_id'] ?? null],
  1024. ];
  1025. $paypal = [];
  1026. foreach ($fields as $key => [$label, $raw]) {
  1027. $value = $this->nullableString($raw);
  1028. if ($value === null) {
  1029. continue;
  1030. }
  1031. $additional[$key] = $value;
  1032. $paypal[$label] = $value;
  1033. }
  1034. $transactionId = $this->nullableString($paymentRow['last_trans_id'] ?? $info['paypal_transaction_id'] ?? null);
  1035. if ($transactionId !== null) {
  1036. $paypal['Last Transaction ID'] = $transactionId;
  1037. }
  1038. foreach (['paypal_payment_status', 'paypal_pending_reason', 'paypal_express_checkout_token'] as $key) {
  1039. $value = $this->nullableString($info[$key] ?? null);
  1040. if ($value !== null) {
  1041. $additional[$key] = $value;
  1042. }
  1043. }
  1044. if ($paypal !== []) {
  1045. $additional['paypal'] = $paypal;
  1046. }
  1047. return $additional;
  1048. }
  1049. private function isPaypalMethod(mixed $method): bool
  1050. {
  1051. $method = strtolower(trim((string) $method));
  1052. return $method !== '' && (str_starts_with($method, 'paypal') || str_starts_with($method, 'paypaluk_'));
  1053. }
  1054. /**
  1055. * @param array<string, mixed> $row
  1056. * @param array<string, mixed> $orderRow
  1057. * @return array<string, mixed>
  1058. */
  1059. private function buildAddressRow(int $orderId, array $row, ?object $customer, string $email, array $orderRow, string $now): array
  1060. {
  1061. $type = strtolower(trim((string) ($row['address_type'] ?? '')));
  1062. $addressType = $type === 'shipping'
  1063. ? OrderAddress::ADDRESS_TYPE_SHIPPING
  1064. : OrderAddress::ADDRESS_TYPE_BILLING;
  1065. $firstName = $this->requiredName(
  1066. $row['firstname'] ?? null,
  1067. $this->requiredName($orderRow['customer_firstname'] ?? null, $customer?->first_name ?? $email)
  1068. );
  1069. $lastName = trim((string) ($row['lastname'] ?? ''))
  1070. ?: (trim((string) ($orderRow['customer_lastname'] ?? '')) ?: ($customer?->last_name ?? '-'));
  1071. return [
  1072. 'order_id' => $orderId,
  1073. 'customer_id' => $customer?->id,
  1074. 'address_type' => $addressType,
  1075. 'first_name' => $firstName,
  1076. 'last_name' => $lastName,
  1077. 'company_name' => $this->nullableString($row['company'] ?? null),
  1078. 'address' => $this->mapStreet($row['street'] ?? null) ?: '-',
  1079. 'city' => trim((string) ($row['city'] ?? '')) ?: '-',
  1080. 'state' => $this->nullableString($row['region'] ?? null),
  1081. 'country' => $this->nullableString($row['country_id'] ?? null),
  1082. 'postcode' => $this->nullableString($row['postcode'] ?? null),
  1083. 'email' => $this->nullableString($row['email'] ?? null) ?? ($email !== '' ? $email : null),
  1084. 'phone' => $this->nullableString($row['telephone'] ?? null),
  1085. 'additional' => json_encode(['asteria_address_id' => (int) ($row['entity_id'] ?? 0)]),
  1086. 'created_at' => $now,
  1087. 'updated_at' => $now,
  1088. ];
  1089. }
  1090. /**
  1091. * @param array<string, mixed> $row
  1092. * @param array{by_sku: array<string, Product>, by_asteria_id: array<int, Product>, catalog_sku: array<int, string>} $productIndex
  1093. * @return array<string, mixed>
  1094. */
  1095. private function buildItemRow(int $orderId, array $row, ?int $parentId, array $productIndex, string $now): array
  1096. {
  1097. $sku = trim((string) ($row['sku'] ?? ''));
  1098. $product = $this->resolveProduct($row, $productIndex);
  1099. $type = $this->mapProductType($row['product_type'] ?? null, $product);
  1100. $price = $this->money($row['price'] ?? 0);
  1101. $basePrice = $this->money($row['base_price'] ?? $price);
  1102. $total = $this->money($row['row_total'] ?? 0);
  1103. $baseTotal = $this->money($row['base_row_total'] ?? $total);
  1104. $taxAmount = $this->money($row['tax_amount'] ?? 0);
  1105. $baseTaxAmount = $this->money($row['base_tax_amount'] ?? $taxAmount);
  1106. $additional = $this->buildItemAdditional($row);
  1107. return [
  1108. 'order_id' => $orderId,
  1109. 'parent_id' => $parentId,
  1110. 'sku' => $sku !== '' ? $sku : null,
  1111. 'type' => $type,
  1112. 'name' => $this->nullableString($row['name'] ?? null) ?? '-',
  1113. 'weight' => $this->money($row['weight'] ?? 0),
  1114. 'total_weight' => $this->money($row['row_weight'] ?? $row['weight'] ?? 0),
  1115. 'qty_ordered' => $this->qty($row['qty_ordered'] ?? 0),
  1116. 'qty_shipped' => $this->qty($row['qty_shipped'] ?? 0),
  1117. 'qty_invoiced' => $this->qty($row['qty_invoiced'] ?? 0),
  1118. 'qty_canceled' => $this->qty($row['qty_canceled'] ?? 0),
  1119. 'qty_refunded' => $this->qty($row['qty_refunded'] ?? 0),
  1120. 'price' => $price,
  1121. 'base_price' => $basePrice,
  1122. 'price_incl_tax' => array_key_exists('price_incl_tax', $row) ? $this->money($row['price_incl_tax']) : $price,
  1123. 'base_price_incl_tax' => array_key_exists('base_price_incl_tax', $row) ? $this->money($row['base_price_incl_tax']) : $basePrice,
  1124. 'total' => $total,
  1125. 'base_total' => $baseTotal,
  1126. 'total_incl_tax' => array_key_exists('row_total_incl_tax', $row) ? $this->money($row['row_total_incl_tax']) : $total + $taxAmount,
  1127. 'base_total_incl_tax' => array_key_exists('base_row_total_incl_tax', $row) ? $this->money($row['base_row_total_incl_tax']) : $baseTotal + $baseTaxAmount,
  1128. 'tax_percent' => $this->money($row['tax_percent'] ?? 0),
  1129. 'tax_amount' => $taxAmount,
  1130. 'base_tax_amount' => $baseTaxAmount,
  1131. 'discount_percent' => $this->money($row['discount_percent'] ?? 0),
  1132. 'discount_amount' => $this->money($row['discount_amount'] ?? 0),
  1133. 'base_discount_amount' => $this->money($row['base_discount_amount'] ?? 0),
  1134. 'product_id' => $product?->id,
  1135. 'product_type' => $product ? get_class($product) : null,
  1136. 'additional' => $this->encodeAdditional($additional),
  1137. 'created_at' => $now,
  1138. 'updated_at' => $now,
  1139. ];
  1140. }
  1141. /**
  1142. * @param array<string, mixed> $row
  1143. * @return array<string, mixed>
  1144. */
  1145. private function buildItemAdditional(array $row): array
  1146. {
  1147. return $this->mergeItemAdditional([], $row);
  1148. }
  1149. /**
  1150. * @param array<string, mixed> $additional
  1151. * @param array<string, mixed> $row
  1152. * @return array<string, mixed>
  1153. */
  1154. private function mergeItemAdditional(array $additional, array $row): array
  1155. {
  1156. $asteriaItemId = (int) ($row['item_id'] ?? 0);
  1157. if ($asteriaItemId > 0) {
  1158. $additional['asteria_item_id'] = $asteriaItemId;
  1159. }
  1160. $asteriaProductId = (int) ($row['product_id'] ?? 0);
  1161. if ($asteriaProductId > 0) {
  1162. $additional['asteria_product_id'] = $asteriaProductId;
  1163. }
  1164. $productOptions = $this->unserializeMagento($row['product_options'] ?? null);
  1165. if ($productOptions !== null && empty($additional['product_options'])) {
  1166. $additional['product_options'] = $productOptions;
  1167. }
  1168. $attributes = $this->magentoOptionsToAttributes($productOptions ?? []);
  1169. if ($attributes !== [] && empty($additional['attributes'])) {
  1170. $additional['attributes'] = $attributes;
  1171. }
  1172. return $additional;
  1173. }
  1174. /**
  1175. * @param array<string, mixed> $productOptions
  1176. * @return array<int, array{attribute_name: string, option_label: string, attribute_type: string}>
  1177. */
  1178. private function magentoOptionsToAttributes(array $productOptions): array
  1179. {
  1180. $attributes = [];
  1181. $seen = [];
  1182. foreach (['options', 'attributes_info', 'additional_options'] as $group) {
  1183. $rows = $productOptions[$group] ?? [];
  1184. if (! is_array($rows)) {
  1185. continue;
  1186. }
  1187. foreach ($rows as $option) {
  1188. if (! is_array($option)) {
  1189. continue;
  1190. }
  1191. $name = trim((string) ($option['label'] ?? ''));
  1192. $label = $this->magentoOptionLabel($option);
  1193. $type = trim((string) ($option['option_type'] ?? ($group === 'attributes_info' ? 'select' : 'text')));
  1194. if ($name === '' && $label === '') {
  1195. continue;
  1196. }
  1197. $key = strtolower($name.'|'.$label);
  1198. if (isset($seen[$key])) {
  1199. continue;
  1200. }
  1201. $seen[$key] = true;
  1202. $attributes[] = [
  1203. 'attribute_name' => $name !== '' ? $name : $label,
  1204. 'option_label' => $label !== '' ? $label : $name,
  1205. 'attribute_type' => $type !== '' ? $type : 'text',
  1206. ];
  1207. }
  1208. }
  1209. return $attributes;
  1210. }
  1211. /**
  1212. * @param array<string, mixed> $option
  1213. */
  1214. private function magentoOptionLabel(array $option): string
  1215. {
  1216. foreach (['print_value', 'value'] as $key) {
  1217. if (! array_key_exists($key, $option)) {
  1218. continue;
  1219. }
  1220. $value = $option[$key];
  1221. if (is_array($value)) {
  1222. $value = $value['title']
  1223. ?? $value['url']
  1224. ?? implode(', ', array_filter($value, 'is_scalar'));
  1225. }
  1226. $value = trim((string) $value);
  1227. if ($value !== '') {
  1228. return $value;
  1229. }
  1230. }
  1231. return '';
  1232. }
  1233. private function unserializeMagento(mixed $value): ?array
  1234. {
  1235. if (is_array($value)) {
  1236. return $value;
  1237. }
  1238. $raw = trim((string) $value);
  1239. if ($raw === '') {
  1240. return null;
  1241. }
  1242. $first = $raw[0];
  1243. if ($first === '{' || $first === '[') {
  1244. $json = json_decode($raw, true);
  1245. return is_array($json) ? $json : null;
  1246. }
  1247. $decoded = @unserialize($raw, ['allowed_classes' => false]);
  1248. return is_array($decoded) ? $decoded : null;
  1249. }
  1250. /**
  1251. * @return array<string, mixed>
  1252. */
  1253. private function decodeAdditional(mixed $value): array
  1254. {
  1255. if (is_array($value)) {
  1256. return $value;
  1257. }
  1258. if (is_string($value) && $value !== '') {
  1259. $decoded = json_decode($value, true);
  1260. return is_array($decoded) ? $decoded : [];
  1261. }
  1262. return [];
  1263. }
  1264. /**
  1265. * @param array<string, mixed> $additional
  1266. */
  1267. private function encodeAdditional(array $additional): string
  1268. {
  1269. $encoded = json_encode($additional, JSON_UNESCAPED_UNICODE);
  1270. if ($encoded !== false) {
  1271. return $encoded;
  1272. }
  1273. unset($additional['product_options']);
  1274. $encoded = json_encode($additional, JSON_UNESCAPED_UNICODE);
  1275. return $encoded !== false ? $encoded : '{}';
  1276. }
  1277. /**
  1278. * @param array<int, int> $orderIds
  1279. * @return array<int, int>
  1280. */
  1281. private function loadInsertedItemIds(array $orderIds): array
  1282. {
  1283. if ($orderIds === []) {
  1284. return [];
  1285. }
  1286. $map = [];
  1287. foreach (DB::table('order_items')->whereIn('order_id', $orderIds)->get(['id', 'additional']) as $item) {
  1288. $additional = $item->additional;
  1289. if (is_string($additional) && $additional !== '') {
  1290. $additional = json_decode($additional, true);
  1291. }
  1292. if (is_array($additional) && isset($additional['asteria_item_id'])) {
  1293. $map[(int) $additional['asteria_item_id']] = (int) $item->id;
  1294. }
  1295. }
  1296. return $map;
  1297. }
  1298. /**
  1299. * @param array<int, array<string, mixed>> $rows
  1300. */
  1301. private function insertRows(string $table, array $rows): void
  1302. {
  1303. foreach (array_chunk($rows, self::INSERT_CHUNK) as $chunk) {
  1304. DB::table($table)->insert($chunk);
  1305. }
  1306. }
  1307. /**
  1308. * @param Collection<int, array<string, mixed>> $orders
  1309. * @return array{0: array<int, object>, 1: array<string, object>}
  1310. */
  1311. private function loadCustomers($orders): array
  1312. {
  1313. $asteriaIds = $orders
  1314. ->pluck('customer_id')
  1315. ->filter(fn ($id) => (int) $id > 0)
  1316. ->map(fn ($id) => (int) $id)
  1317. ->unique()
  1318. ->values()
  1319. ->all();
  1320. $emails = $orders
  1321. ->pluck('customer_email')
  1322. ->map(fn ($email) => strtolower(trim((string) $email)))
  1323. ->filter()
  1324. ->unique()
  1325. ->values()
  1326. ->all();
  1327. $byAsteriaId = [];
  1328. $byEmail = [];
  1329. if ($asteriaIds !== []) {
  1330. foreach (
  1331. DB::table('customers')
  1332. ->select('id', 'email', 'first_name', 'last_name', 'migrated_from_asteria_id')
  1333. ->whereIn('migrated_from_asteria_id', $asteriaIds)
  1334. ->get() as $customer
  1335. ) {
  1336. $byAsteriaId[(int) $customer->migrated_from_asteria_id] = $customer;
  1337. }
  1338. }
  1339. if ($emails !== []) {
  1340. foreach (
  1341. DB::table('customers')
  1342. ->select('id', 'email', 'first_name', 'last_name', 'migrated_from_asteria_id')
  1343. ->whereIn(DB::raw('LOWER(email)'), $emails)
  1344. ->get() as $customer
  1345. ) {
  1346. $byEmail[strtolower((string) $customer->email)] = $customer;
  1347. }
  1348. }
  1349. return [$byAsteriaId, $byEmail];
  1350. }
  1351. /**
  1352. * @param Collection<int, array<string, mixed>> $itemRows
  1353. * @return array{by_sku: array<string, Product>, by_asteria_id: array<int, Product>, catalog_sku: array<int, string>}
  1354. */
  1355. private function loadProductIndex($itemRows, Magento1OrderReader $reader): array
  1356. {
  1357. $itemRows = collect($itemRows);
  1358. $skus = $itemRows
  1359. ->pluck('sku')
  1360. ->map(fn ($sku) => trim((string) $sku))
  1361. ->filter()
  1362. ->unique()
  1363. ->values()
  1364. ->all();
  1365. $asteriaIds = $itemRows
  1366. ->pluck('product_id')
  1367. ->map(fn ($id) => (int) $id)
  1368. ->filter(fn ($id) => $id > 0)
  1369. ->unique()
  1370. ->values()
  1371. ->all();
  1372. $catalogSkuById = $reader->fetchCatalogSkus($asteriaIds);
  1373. foreach ($catalogSkuById as $catalogSku) {
  1374. $skus[] = $catalogSku;
  1375. }
  1376. $skus = array_values(array_unique(array_filter($skus)));
  1377. $bySku = [];
  1378. $byAsteriaId = [];
  1379. $hasAsteriaColumn = Schema::hasColumn('products', 'migrated_from_asteria_id');
  1380. $select = ['id', 'sku', 'type', 'attribute_family_id'];
  1381. if ($hasAsteriaColumn) {
  1382. $select[] = 'migrated_from_asteria_id';
  1383. }
  1384. $index = function (object $row) use (&$bySku, &$byAsteriaId): void {
  1385. $product = new Product;
  1386. $product->exists = true;
  1387. $product->setRawAttributes((array) $row, true);
  1388. $attributes = $product->getAttributes();
  1389. $sku = trim((string) ($attributes['sku'] ?? ''));
  1390. if ($sku !== '') {
  1391. $bySku[$sku] = $product;
  1392. $bySku[strtolower($sku)] = $bySku[strtolower($sku)] ?? $product;
  1393. }
  1394. $asteriaId = (int) ($attributes['migrated_from_asteria_id'] ?? 0);
  1395. if ($asteriaId > 0) {
  1396. $byAsteriaId[$asteriaId] = $product;
  1397. }
  1398. };
  1399. foreach (array_chunk($skus, 500) as $chunk) {
  1400. foreach (DB::table('products')->whereIn('sku', $chunk)->get($select) as $row) {
  1401. $index($row);
  1402. }
  1403. }
  1404. if ($hasAsteriaColumn && $asteriaIds !== []) {
  1405. foreach (array_chunk($asteriaIds, 500) as $chunk) {
  1406. foreach (DB::table('products')->whereIn('migrated_from_asteria_id', $chunk)->get($select) as $row) {
  1407. $index($row);
  1408. }
  1409. }
  1410. }
  1411. return [
  1412. 'by_sku' => $bySku,
  1413. 'by_asteria_id' => $byAsteriaId,
  1414. 'catalog_sku' => $catalogSkuById,
  1415. ];
  1416. }
  1417. /**
  1418. * @param array<string, mixed> $itemRow
  1419. * @param array{by_sku: array<string, Product>, by_asteria_id: array<int, Product>, catalog_sku: array<int, string>} $productIndex
  1420. */
  1421. private function resolveProduct(array $itemRow, array $productIndex): ?Product
  1422. {
  1423. $asteriaProductId = (int) ($itemRow['product_id'] ?? 0);
  1424. if ($asteriaProductId > 0 && isset($productIndex['by_asteria_id'][$asteriaProductId])) {
  1425. return $productIndex['by_asteria_id'][$asteriaProductId];
  1426. }
  1427. $catalogSku = $asteriaProductId > 0
  1428. ? trim((string) ($productIndex['catalog_sku'][$asteriaProductId] ?? ''))
  1429. : '';
  1430. if ($catalogSku !== '') {
  1431. $hit = $productIndex['by_sku'][$catalogSku]
  1432. ?? $productIndex['by_sku'][strtolower($catalogSku)]
  1433. ?? null;
  1434. if ($hit) {
  1435. return $hit;
  1436. }
  1437. }
  1438. $sku = trim((string) ($itemRow['sku'] ?? ''));
  1439. if ($sku === '') {
  1440. return null;
  1441. }
  1442. return $productIndex['by_sku'][$sku]
  1443. ?? $productIndex['by_sku'][strtolower($sku)]
  1444. ?? null;
  1445. }
  1446. private function backfillMissingProductIds(Magento1OrderReader $reader): int
  1447. {
  1448. $updated = 0;
  1449. DB::table('order_items as oi')
  1450. ->join('orders as o', 'o.id', '=', 'oi.order_id')
  1451. ->whereNotNull('o.migrated_from_asteria_id')
  1452. ->where(function ($query) {
  1453. $query->whereNull('oi.product_id')->orWhere('oi.product_id', 0);
  1454. })
  1455. ->select('oi.id', 'oi.additional')
  1456. ->orderBy('oi.id')
  1457. ->chunkById(500, function ($rows) use ($reader, &$updated) {
  1458. $asteriaItemIds = [];
  1459. foreach ($rows as $row) {
  1460. $additional = $row->additional;
  1461. if (is_string($additional) && $additional !== '') {
  1462. $additional = json_decode($additional, true);
  1463. }
  1464. $asteriaItemId = is_array($additional) ? (int) ($additional['asteria_item_id'] ?? 0) : 0;
  1465. if ($asteriaItemId > 0) {
  1466. $asteriaItemIds[(int) $row->id] = $asteriaItemId;
  1467. }
  1468. }
  1469. if ($asteriaItemIds === []) {
  1470. return;
  1471. }
  1472. $magentoItems = $reader->fetchItemsByItemIds(array_values($asteriaItemIds))
  1473. ->keyBy(fn (array $item) => (int) $item['item_id']);
  1474. $productIndex = $this->loadProductIndex($magentoItems->values(), $reader);
  1475. foreach ($asteriaItemIds as $orderItemId => $asteriaItemId) {
  1476. $magentoItem = $magentoItems->get($asteriaItemId);
  1477. if (! is_array($magentoItem)) {
  1478. continue;
  1479. }
  1480. $product = $this->resolveProduct($magentoItem, $productIndex);
  1481. if (! $product) {
  1482. continue;
  1483. }
  1484. $payload = [
  1485. 'product_id' => $product->id,
  1486. 'product_type' => get_class($product),
  1487. 'type' => $this->mapProductType($magentoItem['product_type'] ?? null, $product),
  1488. ];
  1489. $asteriaProductId = (int) ($magentoItem['product_id'] ?? 0);
  1490. if ($asteriaProductId > 0) {
  1491. $additional = $rows->firstWhere('id', $orderItemId)?->additional ?? null;
  1492. if (is_string($additional) && $additional !== '') {
  1493. $additional = json_decode($additional, true) ?: [];
  1494. }
  1495. if (! is_array($additional)) {
  1496. $additional = [];
  1497. }
  1498. $additional['asteria_product_id'] = $asteriaProductId;
  1499. $payload['additional'] = json_encode($additional);
  1500. }
  1501. DB::table('order_items')->where('id', $orderItemId)->update($payload);
  1502. $updated++;
  1503. }
  1504. }, 'oi.id', 'id');
  1505. return $updated;
  1506. }
  1507. /**
  1508. * @param array<string, mixed> $row
  1509. * @param array<int, Customer> $customersByAsteriaId
  1510. * @param array<string, Customer> $customersByEmail
  1511. */
  1512. private function resolveCustomer(array $row, array $customersByAsteriaId, array $customersByEmail): ?object
  1513. {
  1514. $asteriaCustomerId = (int) ($row['customer_id'] ?? 0);
  1515. if ($asteriaCustomerId > 0 && isset($customersByAsteriaId[$asteriaCustomerId])) {
  1516. return $customersByAsteriaId[$asteriaCustomerId];
  1517. }
  1518. $email = strtolower(trim((string) ($row['customer_email'] ?? '')));
  1519. if ($email !== '' && isset($customersByEmail[$email])) {
  1520. return $customersByEmail[$email];
  1521. }
  1522. return null;
  1523. }
  1524. /**
  1525. * @param array<string, mixed> $row
  1526. */
  1527. private function mapStatus(array $row): string
  1528. {
  1529. $status = strtolower(trim((string) ($row['status'] ?? '')));
  1530. $state = strtolower(trim((string) ($row['state'] ?? '')));
  1531. $value = $status !== '' ? $status : $state;
  1532. return match ($value) {
  1533. 'complete' => Order::STATUS_COMPLETED,
  1534. 'canceled', 'cancelled' => Order::STATUS_CANCELED,
  1535. 'pending_payment', 'payment_review', 'pending_paypal' => Order::STATUS_PENDING_PAYMENT,
  1536. 'holded' => Order::STATUS_PENDING,
  1537. 'fraud' => Order::STATUS_FRAUD,
  1538. 'closed' => Order::STATUS_CLOSED,
  1539. 'processing' => Order::STATUS_PROCESSING,
  1540. default => Order::STATUS_PENDING,
  1541. };
  1542. }
  1543. private function mapPaymentMethod(string $method): string
  1544. {
  1545. $method = strtolower(trim($method));
  1546. if ($method === '') {
  1547. return 'unknown';
  1548. }
  1549. if (in_array($method, ['paypal_express', 'paypal_standard'], true) || str_starts_with($method, 'paypaluk_')) {
  1550. return 'paypal_standard';
  1551. }
  1552. if ($method === 'checkmo') {
  1553. return 'moneytransfer';
  1554. }
  1555. if ($method === 'cashondelivery') {
  1556. return 'cashondelivery';
  1557. }
  1558. if (str_starts_with($method, 'klarna')) {
  1559. return 'klarna';
  1560. }
  1561. if (str_starts_with($method, 'afterpay') || str_starts_with($method, 'clearpay')) {
  1562. return 'afterpay';
  1563. }
  1564. return $method;
  1565. }
  1566. private function mapProductType(mixed $magentoType, ?Product $product): string
  1567. {
  1568. $bagistoType = is_object($product) ? trim((string) ($product->getAttributes()['type'] ?? '')) : '';
  1569. if ($bagistoType !== '') {
  1570. return $bagistoType;
  1571. }
  1572. $type = strtolower(trim((string) $magentoType));
  1573. if (in_array($type, self::BAGISTO_PRODUCT_TYPES, true)) {
  1574. return $type;
  1575. }
  1576. return 'simple';
  1577. }
  1578. private function mapStreet(mixed $value): string
  1579. {
  1580. $value = trim((string) $value);
  1581. if ($value === '') {
  1582. return '';
  1583. }
  1584. $lines = preg_split("/\r\n|\n|\r/", $value) ?: [];
  1585. return implode(', ', array_filter(array_map('trim', $lines)));
  1586. }
  1587. private function requiredName(mixed $value, string $fallback): string
  1588. {
  1589. $value = trim((string) $value);
  1590. if ($value !== '') {
  1591. return $value;
  1592. }
  1593. $fallback = trim($fallback);
  1594. if ($fallback !== '') {
  1595. $local = strstr($fallback, '@', true);
  1596. return $local !== false && $local !== '' ? $local : $fallback;
  1597. }
  1598. return 'Customer';
  1599. }
  1600. private function nullableString(mixed $value): ?string
  1601. {
  1602. $value = trim((string) $value);
  1603. return $value === '' ? null : $value;
  1604. }
  1605. private function money(mixed $value): float
  1606. {
  1607. return is_numeric($value) ? (float) $value : 0.0;
  1608. }
  1609. private function qty(mixed $value): int
  1610. {
  1611. return (int) round((float) $value);
  1612. }
  1613. }