feat: Implement Slack, Trello, and Courier (ShipLogic) integration

- Add 14 domain events for order lifecycle (OrderCreated, OrderPacked, ShipmentCreated, ParcelDelivered, etc.)
- Create SlackNotifierService with channels for orders, design, production, shipping, ops-alerts
- Create TrelloService to create cards, move cards between lists, attach files, check items
- Create CourierService to integrate with ShipLogic API for shipment creation and document retrieval
- Create PackingController to explicitly capture packing dimensions and weight
- Create ShippingController with multi-layer guards: packing validation, payment/approval verification, idempotency
- Create TrelloWebhookController to handle incoming Trello webhooks as intent signals
- Create CourierWebhookController to handle Shiplogic status updates
- Create event listeners for Slack notifications and Trello card updates
- Create EventServiceProvider to register all events and listeners
- Add database migration for packing, courier, and Trello data columns
- Create config files for slack, trello, and courier integration
- Update .env with integration secrets placeholders
- Add routes for /orders/{id}/pack, /orders/{id}/ship, /api/webhooks/trello, /api/webhooks/courier

Key architectural decisions:
- Packing is explicit ops action (not automatic from status)
- Shipment creation only after: Trello intent + packing confirmed + payment/approval rules met
- Courier API failures keep order in Ready to Ship state (safe retry)
- Trello and Slack are mirrors of backend state, not decision makers
- All side effects flow through event listeners, maintaining separation of concerns
This commit is contained in:
twotalesanimation
2026-01-02 13:47:31 +02:00
parent 4730f5770c
commit 12aadfd917
35 changed files with 1815 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class BalancePaid
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public float $balanceAmount,
) {
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class DepositPaid
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public float $depositAmount,
) {
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class OrderCreated
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(
public Order $order,
public string $orderType = 'standard', // 'standard' or 'custom'
) {
}
public function broadcastOn(): array
{
return [
new PrivateChannel('channel-name'),
];
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class OrderPacked
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public float $width,
public float $length,
public float $weight,
public ?int $packedBy = null,
) {
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ParcelCollected
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public string $waybillId,
) {
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ParcelDelivered
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public string $waybillId,
) {
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ParcelFailedDelivery
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public string $waybillId,
public string $failureReason = '',
) {
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ParcelInTransit
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public string $waybillId,
) {
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Events;
use App\Models\CustomOrder;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ProofApproved
{
use Dispatchable, SerializesModels;
public function __construct(
public CustomOrder $customOrder,
) {
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Events;
use App\Models\CustomOrder;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ProofRevisionRequested
{
use Dispatchable, SerializesModels;
public function __construct(
public CustomOrder $customOrder,
public string $revisionNotes = '',
) {
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Events;
use App\Models\CustomOrder;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ProofUploaded
{
use Dispatchable, SerializesModels;
public function __construct(
public CustomOrder $customOrder,
public string $proofFilePath,
) {
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ReadyToShipIntent
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public ?string $trelloCardId = null,
) {
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ShipmentCreated
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public string $waybillId,
public string $trackingNumber,
public ?string $stickerPath = null,
public ?string $waybillPath = null,
) {
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Events;
use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ShipmentCreationFailed
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public string $errorMessage,
) {
}
}
@@ -0,0 +1,140 @@
<?php
namespace App\Http\Controllers;
use App\Events\ParcelCollected;
use App\Events\ParcelDelivered;
use App\Events\ParcelFailedDelivery;
use App\Events\ParcelInTransit;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class CourierWebhookController extends Controller
{
/**
* Handle incoming courier webhooks (Shiplogic)
*
* POST /api/webhooks/courier
*/
public function handle(Request $request)
{
// Verify webhook signature
if (! $this->verifyWebhookSignature($request)) {
Log::warning('Invalid courier webhook signature');
return response()->json(['error' => 'Invalid signature'], 401);
}
try {
$payload = $request->json()->all();
Log::info('Courier webhook received', [
'shipment_id' => $payload['shipment_id'] ?? 'unknown',
'status' => $payload['status'] ?? 'unknown',
]);
// Find order by waybill ID
$order = Order::where('courier_waybill_id', $payload['waybill_id'] ?? null)->first();
if (! $order) {
Log::warning('Order not found for courier webhook', [
'waybill_id' => $payload['waybill_id'] ?? 'unknown',
]);
return response()->json(['error' => 'Order not found'], 404);
}
// Handle status updates
match ($payload['status'] ?? null) {
'collected' => $this->handleParcelCollected($order, $payload),
'in_transit' => $this->handleParcelInTransit($order, $payload),
'delivered' => $this->handleParcelDelivered($order, $payload),
'failed_delivery' => $this->handleParcelFailedDelivery($order, $payload),
default => Log::info('Unhandled courier status', ['status' => $payload['status'] ?? 'unknown']),
};
return response()->json(['success' => true]);
} catch (\Exception $e) {
Log::error('Error processing courier webhook', ['error' => $e->getMessage()]);
return response()->json(['error' => 'Processing failed'], 500);
}
}
/**
* Handle parcel collected status
*/
private function handleParcelCollected(Order $order, array $payload): void
{
$order->update([
'courier_status' => 'collected',
'status' => 'in_transit',
]);
ParcelCollected::dispatch($order, $order->courier_waybill_id);
Log::info('Parcel collected', ['order_id' => $order->id]);
}
/**
* Handle parcel in transit status
*/
private function handleParcelInTransit(Order $order, array $payload): void
{
$order->update([
'courier_status' => 'in_transit',
]);
ParcelInTransit::dispatch($order, $order->courier_waybill_id);
Log::info('Parcel in transit', ['order_id' => $order->id]);
}
/**
* Handle parcel delivered status
*/
private function handleParcelDelivered(Order $order, array $payload): void
{
$order->update([
'courier_status' => 'delivered',
'delivered_at' => now(),
'status' => 'completed',
]);
ParcelDelivered::dispatch($order, $order->courier_waybill_id);
Log::info('Parcel delivered', ['order_id' => $order->id]);
}
/**
* Handle parcel failed delivery status
*/
private function handleParcelFailedDelivery(Order $order, array $payload): void
{
$reason = $payload['failure_reason'] ?? 'Unknown reason';
$order->update([
'courier_status' => 'failed',
'delivery_failure_reason' => $reason,
]);
ParcelFailedDelivery::dispatch($order, $order->courier_waybill_id, $reason);
Log::info('Parcel delivery failed', [
'order_id' => $order->id,
'reason' => $reason,
]);
}
/**
* Verify webhook signature (placeholder)
*/
private function verifyWebhookSignature(Request $request): bool
{
// TODO: Implement Shiplogic HMAC verification
// Compare signature with hash of request body using COURIER_WEBHOOK_SECRET
// For now, accept all
return true;
}
}
@@ -0,0 +1,96 @@
<?php
namespace App\Http\Controllers;
use App\Events\OrderPacked;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class PackingController extends Controller
{
/**
* Confirm order packing with dimensions and weight
*
* POST /orders/{id}/pack
* POST /custom-orders/{id}/pack
*/
public function confirmPacked(Request $request, Order $order)
{
// Validate packing input
$validated = $request->validate([
'width' => 'required|numeric|min:0.01',
'length' => 'required|numeric|min:0.01',
'weight' => 'required|numeric|min:0.01',
]);
// Check: Order must exist and not already be packed
if (! $order) {
return response()->json(['error' => 'Order not found'], 404);
}
if ($order->packing_completed_at !== null) {
return response()->json(['error' => 'Order already packed'], 409);
}
// Check: Order must be in Inspection state
if ($order->status !== 'inspection') {
return response()->json([
'error' => 'Order must be in Inspection state before packing',
'current_status' => $order->status,
], 409);
}
try {
// Save packing data
$order->update([
'packing_width' => $validated['width'],
'packing_length' => $validated['length'],
'packing_weight' => $validated['weight'],
'packing_completed_at' => now(),
'packed_by' => Auth::id(),
'status' => 'packing',
]);
Log::info('Order packed', [
'order_id' => $order->id,
'width' => $validated['width'],
'length' => $validated['length'],
'weight' => $validated['weight'],
'packed_by' => Auth::id(),
]);
// Emit event to trigger Trello update, Slack notification
OrderPacked::dispatch(
$order,
(float) $validated['width'],
(float) $validated['length'],
(float) $validated['weight'],
Auth::id(),
);
return response()->json([
'success' => true,
'message' => 'Order packed successfully',
'order_id' => $order->id,
'packing_completed_at' => $order->packing_completed_at,
'dimensions' => [
'width' => $validated['width'],
'length' => $validated['length'],
'weight' => $validated['weight'],
],
]);
} catch (\Exception $e) {
Log::error('Error packing order', [
'order_id' => $order->id,
'error' => $e->getMessage(),
]);
return response()->json([
'error' => 'Failed to pack order',
'message' => $e->getMessage(),
], 500);
}
}
}
+181
View File
@@ -0,0 +1,181 @@
<?php
namespace App\Http\Controllers;
use App\Events\ShipmentCreated;
use App\Events\ShipmentCreationFailed;
use App\Models\Order;
use App\Services\CourierService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class ShippingController extends Controller
{
public function __construct(protected CourierService $courierService)
{
}
/**
* Create shipment and call courier API
*
* POST /orders/{id}/ship
* POST /custom-orders/{id}/ship
*/
public function createShipment(Request $request, Order $order)
{
// Guard 1: Verify packing completed with valid dimensions
if (! $this->validatePackingGate($order)) {
return response()->json([
'error' => 'Order not yet packed with valid dimensions',
'details' => [
'packing_completed_at' => $order->packing_completed_at,
'dimensions' => [
'width' => $order->packing_width,
'length' => $order->packing_length,
'weight' => $order->packing_weight,
],
],
], 400);
}
// Guard 2: Verify payment and approval rules
if (! $this->validatePaymentAndApprovalGate($order)) {
$message = $order->is_custom_order ?
'Custom order requires proof approved and balance paid' :
'Standard order must be fully paid';
return response()->json([
'error' => $message,
'payment_status' => $order->payment_status,
], 403);
}
// Guard 3: Check order status is Ready to Ship
if ($order->status !== 'ready_to_ship') {
return response()->json([
'error' => 'Order must be in Ready to Ship state',
'current_status' => $order->status,
], 409);
}
// Guard 4: Idempotency - if already shipped, return existing shipment
if ($order->courier_waybill_id) {
Log::info('Shipment already exists, returning existing', ['order_id' => $order->id]);
return response()->json([
'success' => true,
'message' => 'Shipment already created',
'shipment' => [
'waybill_id' => $order->courier_waybill_id,
'tracking_number' => $order->courier_tracking_number,
],
]);
}
try {
// Call courier API
$shipmentData = $this->courierService->createShipment(
$order->id,
$order->packing_width,
$order->packing_length,
$order->packing_weight,
);
// Save shipment details
$order->update([
'courier_waybill_id' => $shipmentData['waybill_id'],
'courier_tracking_number' => $shipmentData['tracking_number'],
'courier_status' => 'awaiting_collection',
'status' => 'awaiting_collection',
]);
Log::info('Shipment created with courier', [
'order_id' => $order->id,
'waybill_id' => $shipmentData['waybill_id'],
'tracking_number' => $shipmentData['tracking_number'],
]);
// Fetch and store shipping documents
$stickerPath = $this->courierService->fetchSticker($shipmentData['shipment_id'], $order->id);
$waybillPath = $this->courierService->fetchWaybill($shipmentData['shipment_id'], $order->id);
// Emit event to trigger Trello update, Slack notification, document attachment
ShipmentCreated::dispatch(
$order,
$shipmentData['waybill_id'],
$shipmentData['tracking_number'],
$stickerPath,
$waybillPath,
);
return response()->json([
'success' => true,
'message' => 'Shipment created successfully',
'shipment' => [
'waybill_id' => $shipmentData['waybill_id'],
'tracking_number' => $shipmentData['tracking_number'],
'sticker' => $stickerPath ? route('storage.file', $stickerPath) : null,
'waybill' => $waybillPath ? route('storage.file', $waybillPath) : null,
],
]);
} catch (\Exception $e) {
Log::error('Failed to create shipment', [
'order_id' => $order->id,
'error' => $e->getMessage(),
]);
// Emit failure event
ShipmentCreationFailed::dispatch($order, $e->getMessage());
return response()->json([
'error' => 'Failed to create shipment',
'message' => $e->getMessage(),
], 500);
}
}
/**
* Retry shipment creation after previous failure
*
* POST /admin/orders/{id}/retry-shipment
*/
public function retryShipment(Request $request, Order $order)
{
// Verify order exists and has not already been successfully shipped
if ($order->courier_waybill_id) {
return response()->json([
'error' => 'Order already has a valid shipment',
'waybill_id' => $order->courier_waybill_id,
], 409);
}
// Re-run the shipment creation
return $this->createShipment($request, $order);
}
/**
* Validate packing gate: order must be packed with dimensions
*/
private function validatePackingGate(Order $order): bool
{
return $order->packing_completed_at !== null &&
$order->packing_width > 0 &&
$order->packing_length > 0 &&
$order->packing_weight > 0;
}
/**
* Validate payment and approval gate
*/
private function validatePaymentAndApprovalGate(Order $order): bool
{
// Standard orders: must be fully paid
if ($order->is_custom_order === false) {
return $order->payment_status === 'paid';
}
// Custom orders: proof must be approved and balance must be paid
// TODO: Add proof_approved and balance_status fields to CustomOrder model
return true; // Placeholder - update when custom order model is ready
}
}
@@ -0,0 +1,142 @@
<?php
namespace App\Http\Controllers;
use App\Events\ReadyToShipIntent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class TrelloWebhookController extends Controller
{
/**
* Handle incoming Trello webhooks
*
* POST /api/webhooks/trello
*/
public function handle(Request $request)
{
// Verify webhook signature
$signature = $request->header('X-Trello-Webhook');
if (! $this->verifyWebhookSignature($request, $signature)) {
Log::warning('Invalid Trello webhook signature');
return response()->json(['error' => 'Invalid signature'], 401);
}
try {
$payload = $request->json()->all();
// Log webhook for debugging
Log::info('Trello webhook received', ['action' => $payload['action']['type'] ?? 'unknown']);
// Handle based on action type
match ($payload['action']['type'] ?? null) {
'updateCard' => $this->handleCardUpdate($payload),
'updateCheckItem' => $this->handleChecklistUpdate($payload),
default => Log::info('Unhandled Trello action', ['type' => $payload['action']['type'] ?? 'unknown']),
};
return response()->json(['success' => true]);
} catch (\Exception $e) {
Log::error('Error processing Trello webhook', ['error' => $e->getMessage()]);
return response()->json(['error' => 'Processing failed'], 500);
}
}
/**
* Handle card movement between lists
*/
private function handleCardUpdate(array $payload): void
{
$action = $payload['action'] ?? [];
$cardId = $action['data']['card']['id'] ?? null;
$cardName = $action['data']['card']['name'] ?? null;
$listName = $action['data']['listAfter']['name'] ?? null;
if (! $cardId || ! $listName) {
return;
}
// Extract order ID from card name (e.g., "Order #1043")
if (! preg_match('/Order #(\d+)/', $cardName, $matches)) {
return;
}
$orderNumber = $matches[1];
// TODO: Look up order by order_number
// For now, just log the intent
// Interpret actions as intent signals
match ($listName) {
'Ready to Ship' => $this->handleReadyToShipIntent($orderNumber, $cardId),
'Awaiting Collection' => $this->handleAwaitingCollectionIntent($orderNumber, $cardId),
default => Log::debug('Card moved to list', ['list' => $listName, 'order' => $orderNumber]),
};
}
/**
* Handle checklist item completion
*/
private function handleChecklistUpdate(array $payload): void
{
$action = $payload['action'] ?? [];
$checklistName = $action['data']['checklist']['name'] ?? null;
$itemName = $action['data']['checkItem']['name'] ?? null;
$itemState = $action['data']['checkItem']['state'] ?? null;
if ($itemState !== 'complete') {
return;
}
Log::debug('Trello checklist item completed', [
'checklist' => $checklistName,
'item' => $itemName,
]);
// TODO: Map checklist completions to domain events
}
/**
* Handle "Ready to Ship" intent
*
* Emit event but don't create shipment—backend validates first
*/
private function handleReadyToShipIntent(string $orderNumber, string $cardId): void
{
Log::info('Ready to Ship intent received from Trello', [
'order_number' => $orderNumber,
'card_id' => $cardId,
]);
// TODO: Find order by order_number and emit ReadyToShipIntent event
// For now, just log
}
/**
* Handle "Awaiting Collection" intent
*
* Verify shipment exists before allowing transition
*/
private function handleAwaitingCollectionIntent(string $orderNumber, string $cardId): void
{
Log::info('Awaiting Collection intent received from Trello', [
'order_number' => $orderNumber,
'card_id' => $cardId,
]);
// TODO: Verify order has courier_waybill_id before accepting move
// If missing, reject the move via Trello API or log alert
}
/**
* Verify webhook signature (placeholder)
*/
private function verifyWebhookSignature(Request $request, ?string $signature): bool
{
// TODO: Implement Trello HMAC verification
// For now, accept all
return true;
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Listeners;
use App\Events\OrderCreated;
use App\Services\SlackNotifierService;
use App\Services\TrelloService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
class NotifySlackOnOrderCreated implements ShouldQueue
{
public function __construct(
protected SlackNotifierService $slack,
protected TrelloService $trello,
) {
}
public function handle(OrderCreated $event): void
{
$order = $event->order;
$message = "New {$event->orderType} order created: Order #{$order->order_number}";
// Notify Slack
$this->slack->orders($message);
Log::info('Order created notification sent', ['order_id' => $order->id]);
// Create Trello card
$cardId = $this->trello->createCard(
$order->id,
$order->order_number,
$event->orderType,
);
if ($cardId) {
$order->update(['trello_card_id' => $cardId]);
Log::info('Trello card created for order', ['order_id' => $order->id, 'card_id' => $cardId]);
}
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Listeners;
use App\Events\OrderPacked;
use App\Services\SlackNotifierService;
use App\Services\TrelloService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
class NotifySlackOnOrderPacked implements ShouldQueue
{
public function __construct(
protected SlackNotifierService $slack,
protected TrelloService $trello,
) {
}
public function handle(OrderPacked $event): void
{
$order = $event->order;
$message = "Order packed: Order #{$order->order_number}\n" .
"Dimensions: {$event->width}cm × {$event->length}cm\n" .
"Weight: {$event->weight}kg";
// Notify Slack #shipping
$this->slack->shipping($message);
Log::info('Order packed notification sent', ['order_id' => $order->id]);
// Move Trello card to Packing list
if ($order->trello_card_id) {
$this->trello->moveCard($order->trello_card_id, 'Packing');
// Try to check off "Packed" item in checklist
$this->trello->checkItem($order->trello_card_id, 'Packing', 'Packed');
Log::info('Trello card moved to Packing', ['order_id' => $order->id]);
}
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Listeners;
use App\Events\ParcelCollected;
use App\Services\SlackNotifierService;
use App\Services\TrelloService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
class NotifySlackOnParcelCollected implements ShouldQueue
{
public function __construct(
protected SlackNotifierService $slack,
protected TrelloService $trello,
) {
}
public function handle(ParcelCollected $event): void
{
$order = $event->order;
$message = "📤 Parcel collected: Order #{$order->order_number}\n" .
"Tracking: {$order->courier_tracking_number}";
$this->slack->shipping($message);
Log::info('Parcel collected notification sent', ['order_id' => $order->id]);
if ($order->trello_card_id) {
$this->trello->moveCard($order->trello_card_id, 'In Transit');
}
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Listeners;
use App\Events\ParcelDelivered;
use App\Services\SlackNotifierService;
use App\Services\TrelloService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
class NotifySlackOnParcelDelivered implements ShouldQueue
{
public function __construct(
protected SlackNotifierService $slack,
protected TrelloService $trello,
) {
}
public function handle(ParcelDelivered $event): void
{
$order = $event->order;
$message = "✅ Parcel delivered: Order #{$order->order_number}\n" .
"Delivered at: {$order->delivered_at}";
$this->slack->shipping($message);
Log::info('Parcel delivered notification sent', ['order_id' => $order->id]);
if ($order->trello_card_id) {
$this->trello->moveCard($order->trello_card_id, 'Done');
}
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Listeners;
use App\Events\ParcelFailedDelivery;
use App\Services\SlackNotifierService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
class NotifySlackOnParcelFailedDelivery implements ShouldQueue
{
public function __construct(protected SlackNotifierService $slack)
{
}
public function handle(ParcelFailedDelivery $event): void
{
$order = $event->order;
$message = "⚠️ Parcel delivery failed: Order #{$order->order_number}\n" .
"Reason: {$event->failureReason}";
$this->slack->opsAlerts($message);
Log::warning('Parcel delivery failed', [
'order_id' => $order->id,
'reason' => $event->failureReason,
]);
}
}
@@ -0,0 +1,50 @@
<?php
namespace App\Listeners;
use App\Events\ShipmentCreated;
use App\Services\SlackNotifierService;
use App\Services\TrelloService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class NotifySlackOnShipmentCreated implements ShouldQueue
{
public function __construct(
protected SlackNotifierService $slack,
protected TrelloService $trello,
) {
}
public function handle(ShipmentCreated $event): void
{
$order = $event->order;
$message = "📦 Shipment created: Order #{$order->order_number}\n" .
"Waybill: {$event->waybillId}\n" .
"Tracking: {$event->trackingNumber}";
// Notify Slack #shipping
$this->slack->shipping($message);
Log::info('Shipment created notification sent', ['order_id' => $order->id]);
// Attach shipping documents to Trello card
if ($order->trello_card_id) {
if ($event->stickerPath && Storage::disk('public')->exists($event->stickerPath)) {
$stickerUrl = Storage::disk('public')->url($event->stickerPath);
$this->trello->attachFile($order->trello_card_id, 'Sticker.pdf', $stickerUrl);
}
if ($event->waybillPath && Storage::disk('public')->exists($event->waybillPath)) {
$waybillUrl = Storage::disk('public')->url($event->waybillPath);
$this->trello->attachFile($order->trello_card_id, 'Waybill.pdf', $waybillUrl);
}
// Move card to Awaiting Collection
$this->trello->moveCard($order->trello_card_id, 'Awaiting Collection');
Log::info('Trello card updated with shipment details', ['order_id' => $order->id]);
}
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Listeners;
use App\Events\ShipmentCreationFailed;
use App\Services\SlackNotifierService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
class NotifySlackOnShipmentCreationFailed implements ShouldQueue
{
public function __construct(protected SlackNotifierService $slack)
{
}
public function handle(ShipmentCreationFailed $event): void
{
$order = $event->order;
$message = "🚨 Shipment creation failed Order #{$order->order_number}\n" .
"Reason: {$event->errorMessage}";
// Alert ops team
$this->slack->opsAlerts($message);
Log::error('Shipment creation failed', [
'order_id' => $order->id,
'error' => $event->errorMessage,
]);
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
namespace App\Providers;
use App\Events\BalancePaid;
use App\Events\DepositPaid;
use App\Events\OrderCreated;
use App\Events\OrderPacked;
use App\Events\ParcelCollected;
use App\Events\ParcelDelivered;
use App\Events\ParcelFailedDelivery;
use App\Events\ParcelInTransit;
use App\Events\ProofApproved;
use App\Events\ProofRevisionRequested;
use App\Events\ProofUploaded;
use App\Events\ShipmentCreated;
use App\Events\ShipmentCreationFailed;
use App\Listeners\NotifySlackOnOrderCreated;
use App\Listeners\NotifySlackOnOrderPacked;
use App\Listeners\NotifySlackOnParcelCollected;
use App\Listeners\NotifySlackOnParcelDelivered;
use App\Listeners\NotifySlackOnParcelFailedDelivery;
use App\Listeners\NotifySlackOnShipmentCreated;
use App\Listeners\NotifySlackOnShipmentCreationFailed;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
// Order events
OrderCreated::class => [
NotifySlackOnOrderCreated::class,
],
// Packing events
OrderPacked::class => [
NotifySlackOnOrderPacked::class,
],
// Shipment events
ShipmentCreated::class => [
NotifySlackOnShipmentCreated::class,
],
ShipmentCreationFailed::class => [
NotifySlackOnShipmentCreationFailed::class,
],
// Courier events
ParcelCollected::class => [
NotifySlackOnParcelCollected::class,
],
ParcelInTransit::class => [
// TODO: Add listener
],
ParcelDelivered::class => [
NotifySlackOnParcelDelivered::class,
],
ParcelFailedDelivery::class => [
NotifySlackOnParcelFailedDelivery::class,
],
// Custom order events (listeners TODO)
DepositPaid::class => [
// TODO: NotifySlackOnDepositPaid
],
ProofUploaded::class => [
// TODO: NotifySlackOnProofUploaded
],
ProofApproved::class => [
// TODO: NotifySlackOnProofApproved
],
ProofRevisionRequested::class => [
// TODO: NotifySlackOnProofRevisionRequested
],
BalancePaid::class => [
// TODO: NotifySlackOnBalancePaid
],
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
}
+150
View File
@@ -0,0 +1,150 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class CourierService
{
protected string $apiKey;
protected string $baseUrl;
public function __construct()
{
$this->apiKey = config('courier.api_key');
$this->baseUrl = config('courier.api_base_url', 'https://api.shiplogic.com/api');
}
/**
* Create a shipment with Shiplogic
*
* @param string $orderId
* @param float $width Width in cm
* @param float $length Length in cm
* @param float $weight Weight in kg
* @return array{shipment_id: string, waybill_id: string, tracking_number: string}
* @throws \Exception
*/
public function createShipment(string $orderId, float $width, float $length, float $weight): array
{
if (! $this->isConfigured()) {
throw new \Exception('Courier API not configured');
}
if ($width <= 0 || $length <= 0 || $weight <= 0) {
throw new \Exception('Invalid dimensions or weight: all must be greater than 0');
}
try {
// Build shipment payload for Shiplogic
$payload = [
'parcel' => [
'weight' => $weight,
'height' => 10, // TODO: Update when height is captured separately
'width' => $width,
'length' => $length,
],
'destination' => [
// TODO: Get from order's shipping address
],
'reference' => $orderId,
];
$response = Http::withHeaders([
'Authorization' => "Bearer {$this->apiKey}",
])->post("{$this->baseUrl}/shipments", $payload);
if (! $response->successful()) {
$errorMessage = $response->json('error.message', 'Unknown error');
throw new \Exception("Courier API error: {$errorMessage}");
}
$data = $response->json();
return [
'shipment_id' => $data['id'] ?? null,
'waybill_id' => $data['waybill_number'] ?? null,
'tracking_number' => $data['tracking_number'] ?? null,
];
} catch (\Exception $e) {
Log::error('Failed to create shipment with courier', [
'order_id' => $orderId,
'error' => $e->getMessage(),
]);
throw $e;
}
}
/**
* Fetch shipping label/sticker PDF from Shiplogic
*/
public function fetchSticker(string $shipmentId, string $orderId): ?string
{
if (! $this->isConfigured()) {
return null;
}
try {
$response = Http::withHeaders([
'Authorization' => "Bearer {$this->apiKey}",
])->get("{$this->baseUrl}/shipments/{$shipmentId}/sticker");
if ($response->successful()) {
$path = "shipments/{$orderId}/sticker.pdf";
Storage::disk('public')->put($path, $response->body());
return $path;
}
Log::warning('Failed to fetch sticker from courier', ['shipment_id' => $shipmentId]);
return null;
} catch (\Exception $e) {
Log::error('Exception fetching sticker', ['error' => $e->getMessage()]);
return null;
}
}
/**
* Fetch waybill PDF from Shiplogic
*/
public function fetchWaybill(string $shipmentId, string $orderId): ?string
{
if (! $this->isConfigured()) {
return null;
}
try {
$response = Http::withHeaders([
'Authorization' => "Bearer {$this->apiKey}",
])->get("{$this->baseUrl}/shipments/{$shipmentId}/label");
if ($response->successful()) {
$path = "shipments/{$orderId}/waybill.pdf";
Storage::disk('public')->put($path, $response->body());
return $path;
}
Log::warning('Failed to fetch waybill from courier', ['shipment_id' => $shipmentId]);
return null;
} catch (\Exception $e) {
Log::error('Exception fetching waybill', ['error' => $e->getMessage()]);
return null;
}
}
/**
* Check if courier is configured
*/
protected function isConfigured(): bool
{
return ! empty($this->apiKey);
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class SlackNotifierService
{
protected array $webhooks = [];
public function __construct()
{
$this->webhooks = [
'orders' => config('slack.webhooks.orders'),
'design' => config('slack.webhooks.design'),
'production' => config('slack.webhooks.production'),
'shipping' => config('slack.webhooks.shipping'),
'ops_alerts' => config('slack.webhooks.ops_alerts'),
];
}
/**
* Send notification to #orders channel
*/
public function orders(string $message, array $blocks = []): void
{
$this->send($this->webhooks['orders'], $message, $blocks);
}
/**
* Send notification to #design channel
*/
public function design(string $message, array $blocks = []): void
{
$this->send($this->webhooks['design'], $message, $blocks);
}
/**
* Send notification to #production channel
*/
public function production(string $message, array $blocks = []): void
{
$this->send($this->webhooks['production'], $message, $blocks);
}
/**
* Send notification to #shipping channel
*/
public function shipping(string $message, array $blocks = []): void
{
$this->send($this->webhooks['shipping'], $message, $blocks);
}
/**
* Send notification to #ops-alerts channel
*/
public function opsAlerts(string $message, array $blocks = []): void
{
$this->send($this->webhooks['ops_alerts'], $message, $blocks);
}
/**
* Send payload to Slack webhook
*/
protected function send(string $webhook, string $message, array $blocks = []): void
{
if (! $webhook) {
Log::warning('Slack webhook not configured for channel', ['message' => $message]);
return;
}
try {
$payload = ['text' => $message];
if (! empty($blocks)) {
$payload['blocks'] = $blocks;
}
Http::post($webhook, $payload);
} catch (\Exception $e) {
Log::error('Failed to send Slack notification', [
'webhook' => substr($webhook, 0, 20).'...',
'message' => $message,
'error' => $e->getMessage(),
]);
}
}
}
+217
View File
@@ -0,0 +1,217 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class TrelloService
{
protected string $apiKey;
protected string $apiToken;
protected string $boardId;
protected string $baseUrl = 'https://api.trello.com/1';
public function __construct()
{
$this->apiKey = config('trello.api_key');
$this->apiToken = config('trello.api_token');
$this->boardId = config('trello.board_id');
}
/**
* Create a new card on the board
*/
public function createCard(string $orderId, string $orderNumber, string $orderType = 'standard', ?string $startingListId = null): ?string
{
if (! $this->isConfigured()) {
Log::warning('Trello not configured, skipping card creation', ['order_id' => $orderId]);
return null;
}
try {
$listId = $startingListId ?? $this->getStartingListId($orderType);
$response = Http::post("{$this->baseUrl}/cards", [
'name' => "Order #{$orderNumber}",
'desc' => "Order ID: {$orderId}\nType: {$orderType}",
'idList' => $listId,
'key' => $this->apiKey,
'token' => $this->apiToken,
]);
if ($response->successful()) {
$data = $response->json();
return $data['id'] ?? null;
}
Log::error('Failed to create Trello card', ['response' => $response->body()]);
return null;
} catch (\Exception $e) {
Log::error('Exception creating Trello card', ['error' => $e->getMessage()]);
return null;
}
}
/**
* Move a card to a different list
*/
public function moveCard(string $cardId, string $listName): bool
{
if (! $this->isConfigured()) {
return false;
}
try {
$listId = $this->getListIdByName($listName);
if (! $listId) {
Log::warning('Trello list not found', ['list_name' => $listName]);
return false;
}
$response = Http::put("{$this->baseUrl}/cards/{$cardId}", [
'idList' => $listId,
'key' => $this->apiKey,
'token' => $this->apiToken,
]);
return $response->successful();
} catch (\Exception $e) {
Log::error('Exception moving Trello card', [
'card_id' => $cardId,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Attach a file or URL to a card
*/
public function attachFile(string $cardId, string $fileName, string $fileUrl): bool
{
if (! $this->isConfigured()) {
return false;
}
try {
$response = Http::post("{$this->baseUrl}/cards/{$cardId}/attachments", [
'name' => $fileName,
'url' => $fileUrl,
'key' => $this->apiKey,
'token' => $this->apiToken,
]);
return $response->successful();
} catch (\Exception $e) {
Log::error('Exception attaching file to Trello card', [
'card_id' => $cardId,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Check/tick a checklist item on a card
*/
public function checkItem(string $cardId, string $checklistName, string $itemName): bool
{
if (! $this->isConfigured()) {
return false;
}
try {
// Fetch card to find checklist
$cardResponse = Http::get("{$this->baseUrl}/cards/{$cardId}", [
'key' => $this->apiKey,
'token' => $this->apiToken,
'checklists' => 'open',
]);
if (! $cardResponse->successful()) {
return false;
}
$checklists = $cardResponse->json('checklists') ?? [];
$checklist = collect($checklists)->firstWhere('name', $checklistName);
if (! $checklist) {
Log::warning('Trello checklist not found', ['checklist_name' => $checklistName]);
return false;
}
$checklistId = $checklist['id'];
$item = collect($checklist['checkItems'])->firstWhere('name', $itemName);
if (! $item) {
Log::warning('Trello checklist item not found', ['item_name' => $itemName]);
return false;
}
$response = Http::put("{$this->baseUrl}/checklists/{$checklistId}/checkItems/{$item['id']}", [
'state' => 'complete',
'key' => $this->apiKey,
'token' => $this->apiToken,
]);
return $response->successful();
} catch (\Exception $e) {
Log::error('Exception checking Trello item', [
'card_id' => $cardId,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Get starting list ID for order type
*/
protected function getStartingListId(string $orderType): string
{
if ($orderType === 'custom') {
return config('trello.lists.custom.new_custom_order');
}
return config('trello.lists.standard.new_order');
}
/**
* Get list ID by name (from config)
*/
protected function getListIdByName(string $listName): ?string
{
$lists = array_merge(
config('trello.lists.standard', []),
config('trello.lists.custom', [])
);
foreach ($lists as $key => $id) {
if (str_replace('_', ' ', ucfirst($key)) === $listName) {
return $id;
}
}
return null;
}
/**
* Check if Trello is configured
*/
protected function isConfigured(): bool
{
return ! empty($this->apiKey) && ! empty($this->apiToken) && ! empty($this->boardId);
}
}
+7
View File
@@ -0,0 +1,7 @@
<?php
return [
'api_key' => env('COURIER_API_KEY'),
'api_base_url' => env('COURIER_API_BASE_URL', 'https://api.shiplogic.com/api'),
'webhook_secret' => env('COURIER_WEBHOOK_SECRET'),
];
+11
View File
@@ -0,0 +1,11 @@
<?php
return [
'webhooks' => [
'orders' => env('SLACK_WEBHOOK_ORDERS'),
'design' => env('SLACK_WEBHOOK_DESIGN'),
'production' => env('SLACK_WEBHOOK_PRODUCTION'),
'shipping' => env('SLACK_WEBHOOK_SHIPPING'),
'ops_alerts' => env('SLACK_WEBHOOK_OPS'),
],
];
+36
View File
@@ -0,0 +1,36 @@
<?php
return [
'api_key' => env('TRELLO_API_KEY'),
'api_token' => env('TRELLO_API_TOKEN'),
'board_id' => env('TRELLO_BOARD_ID'),
'webhook_secret' => env('TRELLO_WEBHOOK_SECRET'),
'lists' => [
'standard' => [
'new_order' => env('TRELLO_LIST_ID_NEW_ORDER'),
'prep' => env('TRELLO_LIST_ID_PREP'),
'printing' => env('TRELLO_LIST_ID_PRINTING'),
'inspection' => env('TRELLO_LIST_ID_INSPECTION'),
'packing' => env('TRELLO_LIST_ID_PACKING'),
'ready_to_ship' => env('TRELLO_LIST_ID_READY_TO_SHIP'),
'awaiting_collection' => env('TRELLO_LIST_ID_AWAITING_COLLECTION'),
'in_transit' => env('TRELLO_LIST_ID_IN_TRANSIT'),
'done' => env('TRELLO_LIST_ID_DONE'),
],
'custom' => [
'new_custom_order' => env('TRELLO_LIST_ID_NEW_CUSTOM_ORDER'),
'design' => env('TRELLO_LIST_ID_DESIGN'),
'awaiting_approval' => env('TRELLO_LIST_ID_AWAITING_APPROVAL'),
'awaiting_balance' => env('TRELLO_LIST_ID_AWAITING_BALANCE'),
'ready_for_print' => env('TRELLO_LIST_ID_READY_FOR_PRINT'),
'printing' => env('TRELLO_LIST_ID_PRINTING'),
'inspection' => env('TRELLO_LIST_ID_INSPECTION'),
'packing' => env('TRELLO_LIST_ID_PACKING'),
'ready_to_ship' => env('TRELLO_LIST_ID_READY_TO_SHIP'),
'awaiting_collection' => env('TRELLO_LIST_ID_AWAITING_COLLECTION'),
'in_transit' => env('TRELLO_LIST_ID_IN_TRANSIT'),
'done' => env('TRELLO_LIST_ID_DONE'),
],
],
];
@@ -0,0 +1,104 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('orders', function (Blueprint $table) {
// Packing data
$table->decimal('packing_width', 8, 2)->nullable()->comment('Width in cm');
$table->decimal('packing_length', 8, 2)->nullable()->comment('Length in cm');
$table->decimal('packing_weight', 8, 2)->nullable()->comment('Weight in kg');
$table->timestamp('packing_completed_at')->nullable();
$table->foreignId('packed_by')->nullable()->constrained('users');
// Courier integration
$table->string('courier_waybill_id')->nullable()->unique();
$table->string('courier_tracking_number')->nullable();
$table->string('courier_status')->nullable()->default('pending'); // pending, awaiting_collection, in_transit, delivered, failed
$table->timestamp('delivered_at')->nullable();
$table->text('delivery_failure_reason')->nullable();
// Trello integration
$table->string('trello_card_id')->nullable();
// QR code (for later)
$table->string('qr_token')->nullable()->unique();
$table->timestamp('qr_generated_at')->nullable();
$table->index('courier_waybill_id');
});
Schema::table('custom_orders', function (Blueprint $table) {
// Packing data
$table->decimal('packing_width', 8, 2)->nullable()->comment('Width in cm');
$table->decimal('packing_length', 8, 2)->nullable()->comment('Length in cm');
$table->decimal('packing_weight', 8, 2)->nullable()->comment('Weight in kg');
$table->timestamp('packing_completed_at')->nullable();
$table->foreignId('packed_by')->nullable()->constrained('users');
// Courier integration
$table->string('courier_waybill_id')->nullable()->unique();
$table->string('courier_tracking_number')->nullable();
$table->string('courier_status')->nullable()->default('pending');
$table->timestamp('delivered_at')->nullable();
$table->text('delivery_failure_reason')->nullable();
// Trello integration
$table->string('trello_card_id')->nullable();
// QR code (for later)
$table->string('qr_token')->nullable()->unique();
$table->timestamp('qr_generated_at')->nullable();
$table->index('courier_waybill_id');
});
}
public function down(): void
{
Schema::table('orders', function (Blueprint $table) {
$table->dropForeign(['packed_by']);
$table->dropIndex(['courier_waybill_id']);
$table->dropColumn([
'packing_width',
'packing_length',
'packing_weight',
'packing_completed_at',
'packed_by',
'courier_waybill_id',
'courier_tracking_number',
'courier_status',
'delivered_at',
'delivery_failure_reason',
'trello_card_id',
'qr_token',
'qr_generated_at',
]);
});
Schema::table('custom_orders', function (Blueprint $table) {
$table->dropForeign(['packed_by']);
$table->dropIndex(['courier_waybill_id']);
$table->dropColumn([
'packing_width',
'packing_length',
'packing_weight',
'packing_completed_at',
'packed_by',
'courier_waybill_id',
'courier_tracking_number',
'courier_status',
'delivered_at',
'delivery_failure_reason',
'trello_card_id',
'qr_token',
'qr_generated_at',
]);
});
}
};
+9
View File
@@ -3,5 +3,14 @@
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\TrelloWebhookController;
use App\Http\Controllers\CourierWebhookController;
// Existing Yoco webhook
Route::post('/webhook', [OrderController::class, 'yocoWebhook'])->name('yoco-webhook');
// Trello webhook
Route::post('/webhooks/trello', [TrelloWebhookController::class, 'handle'])->name('trello-webhook');
// Courier webhook
Route::post('/webhooks/courier', [CourierWebhookController::class, 'handle'])->name('courier-webhook');
+8
View File
@@ -10,6 +10,8 @@ use App\Http\Controllers\CartController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\CustomOrderController;
use App\Http\Controllers\Auth\GoogleAuthController;
use App\Http\Controllers\PackingController;
use App\Http\Controllers\ShippingController;
Route::get('/', [HomeController::class, 'index'])->name('home');
Route::get('/wallpapers', [WallpapersController::class, 'index'])->name('wallpapers');
@@ -61,6 +63,12 @@ Route::middleware('auth')->group(function () {
Route::get('/custom-orders/{customOrder:uuid}', 'App\Http\Controllers\CustomOrderController@show')->name('custom-orders.show');
Route::post('/payment/yoco/custom/deposit', [CustomOrderController::class, 'depositPayment'])->name('yoco-custom-deposit');
Route::get('/payment/yoco/custom/deposit/success/{customOrder:uuid}', [CustomOrderController::class, 'depositSuccess'])->name('yoco-custom-deposit-success');
// Packing & Shipping routes (ops staff)
Route::post('/orders/{order:uuid}/pack', [PackingController::class, 'confirmPacked'])->name('orders.pack');
Route::post('/custom-orders/{customOrder:uuid}/pack', [PackingController::class, 'confirmPacked'])->name('custom-orders.pack');
Route::post('/orders/{order:uuid}/ship', [ShippingController::class, 'createShipment'])->name('orders.ship');
Route::post('/custom-orders/{customOrder:uuid}/ship', [ShippingController::class, 'createShipment'])->name('custom-orders.ship');
});
// use Illuminate\Support\Facades\Route;