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:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user