MigrateAsteriaOrders.php 74 KB

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