Files
ladill-woo-manager/app/Services/Woo/OrderIngestService.php
T
isaacclad e709de6593
Deploy Ladill Woo Manager / deploy (push) Successful in 35s
Use WooCommerce store currency for product and order money.
Sync currency from the plugin, format product prices and totals with it, and show the store currency on product price fields instead of hard-coding GHS.
2026-07-24 15:38:07 +00:00

85 lines
3.0 KiB
PHP

<?php
namespace App\Services\Woo;
use App\Models\WooOrder;
use App\Models\WooStore;
use Carbon\Carbon;
class OrderIngestService
{
/** @param array<string, mixed> $payload */
public function ingest(WooStore $store, array $payload): WooOrder
{
$externalId = (int) ($payload['id'] ?? 0);
if ($externalId === 0) {
throw new \InvalidArgumentException('WooCommerce order id missing.');
}
$billing = (array) ($payload['billing'] ?? []);
$shipping = (array) ($payload['shipping'] ?? []);
$lineItems = collect((array) ($payload['line_items'] ?? []))
->map(fn (array $item) => [
'name' => (string) ($item['name'] ?? ''),
'sku' => (string) ($item['sku'] ?? ''),
'quantity' => max(1, (int) ($item['quantity'] ?? 1)),
'total_minor' => (int) round(((float) ($item['total'] ?? 0)) * 100),
])
->filter(fn (array $i) => $i['name'] !== '')
->values()
->all();
$totalMinor = (int) round(((float) ($payload['total'] ?? 0)) * 100);
$currency = strtoupper(trim((string) ($payload['currency'] ?? '')));
if (preg_match('/^[A-Z]{3}$/', $currency) !== 1) {
$currency = $store->currency();
}
if ($currency === '') {
$currency = 'XXX';
}
$wcUpdatedAt = isset($payload['date_modified_gmt'])
? Carbon::parse($payload['date_modified_gmt'].' UTC')
: null;
$order = WooOrder::query()->updateOrCreate(
[
'woo_store_id' => $store->id,
'external_order_id' => $externalId,
],
[
'order_number' => (string) ($payload['number'] ?? $externalId),
'wc_status' => (string) ($payload['status'] ?? ''),
'payment_status' => $this->paymentStatus($payload),
'customer_name' => trim(collect([$billing['first_name'] ?? '', $billing['last_name'] ?? ''])->filter()->implode(' ')) ?: null,
'customer_email' => $billing['email'] ?? null,
'customer_phone' => $billing['phone'] ?? null,
'line_items' => $lineItems,
'billing_address' => $billing ?: null,
'shipping_address' => $shipping ?: null,
'currency' => $currency,
'total_minor' => $totalMinor,
'wc_updated_at' => $wcUpdatedAt,
'metadata' => [
'payment_method' => $payload['payment_method_title'] ?? null,
'customer_note' => $payload['customer_note'] ?? null,
],
],
);
$store->update(['last_webhook_at' => now()]);
return $order;
}
/** @param array<string, mixed> $payload */
private function paymentStatus(array $payload): string
{
if (! empty($payload['date_paid']) || ($payload['needs_payment'] ?? true) === false) {
return 'paid';
}
return 'unpaid';
}
}