post('/order/items', function () { // Require the user to be logged in global $response; $this->requirePermission('add_order_items'); // Get the user object $user = (new authentication())->get_user(); // Check if the request was successful if ($user) { // Check if the required fields are set $data = json_decode(file_get_contents('php://input'), true); if (!isset($data['order_id'])) { $response->error('Order ID is required', 400); } if (!isset($data['product_id'])) { $response->error('Product ID is required', 400); } if (!isset($data['quantity'])) { $response->error('Quantity is required', 400); } $related_item_id = null; // Check if the related_item_id is set if (self::isParametersSet(['related_item_id'])) { // Check if the related_item_id is null, if so continue if ($data['related_item_id'] !== null) { // Check if the related_item_id is a number if (!is_numeric($data['related_item_id'])) { $response->error('Related item ID must be a number', 400); } $related_item_id = (int)$data['related_item_id']; } } $notes = null; // Check if the notes is set if (self::isParametersSet(['notes'])) { // Check if the notes is null, if so continue if (self::getParameter('notes') !== null) { // Check if the notes is a string if (!is_string(self::getParameter('notes'))) { $response->error('Notes must be a string', 400); } $notes = (string)self::getParameter('notes'); } } $price = null; // Check if the price is set if (self::isParametersSet(['price'])) { // Check if the price is null, if so continue if (self::getParameter('price') !== null) { // Check if the price is a number if (!is_numeric(self::getParameter('price'))) { $response->error('Price must be a number', 400); } $price = (int)self::getParameter('price'); } } $order = (new orders_o())->getOrderById((int)$data['order_id']); if (!$order->exists()) { $response->error('Order not found', 404); } // Check if the user has access to the department self::requireDepartmentAccess((string)(int)$order->department_id->value()); $orderPaymentLock = $this->acquireOrderPaymentLock((int)$order->id); $product = (new products_o())->getProductById((int)$data['product_id']); if (!$product->exists()) { $response->error('Product not found', 404); } $customerRuleViolation = (new customer_product_rule_service()) ->firstViolationForOrderItem((int)$data['order_id'], (int)$data['product_id'], $related_item_id); if ($customerRuleViolation !== null) { (new logs_o())->add( 'order_items', 'global', 1, $user->id, 'ORDER_ITEM_RESTRICTED_BY_CUSTOMER_RULE', 'Blocked product ' . (int)$data['product_id'] . ' on order ' . (int)$data['order_id'] . ' by rule ' . $customerRuleViolation['rule'] ); $response->error([ 'code' => $customerRuleViolation['code'], 'message' => $customerRuleViolation['message'], 'product_id' => $customerRuleViolation['product_id'], 'rules' => $customerRuleViolation['rules'], 'collections' => $customerRuleViolation['collections'], ], 400); } // Validation order for audited products: // 1. If reason_code is present, run reason validation first (most specific messages). // 2. If the product requires an order-item note and notes are provided but // empty/whitespace, return "Notes is required" (the legacy message). Other products // may carry an empty notes field without rejecting the request. // 3. Otherwise run reason validation (covers missing reason_code on affected products). $reasonFields = ['reason_code' => null, 'reason_label_snapshot' => null, 'reason_comment' => null]; $reasonCodeProvided = array_key_exists('reason_code', (array)$data) || array_key_exists('order_item_reason_code', (array)$data); $productRequiresOrderItemNote = $product->requiresOrderItemNote(); if ($reasonCodeProvided) { try { $reasonFields = \classes\order_item_reason_policy::validateForProduct((int)$data['product_id'], $data); } catch (\InvalidArgumentException $e) { $response->error($e->getMessage(), 400); } } elseif ( $productRequiresOrderItemNote && array_key_exists('notes', (array)$data) && trim((string)($data['notes'] ?? '')) === '' ) { $response->error('Notes is required for this product', 400); } else { try { $reasonFields = \classes\order_item_reason_policy::validateForProduct((int)$data['product_id'], $data); } catch (\InvalidArgumentException $e) { $response->error($e->getMessage(), 400); } } // Add the order item to the order This is done individually, to make the notes to the individual order items possible $order_items = (new order_items_o()); // Add the order item to the order $order_items->addItemToOrder((int)$data['order_id'], (int)$data['product_id'], (int)$user->id, (int)$data['quantity'], $related_item_id, $notes, $price, $reasonFields['reason_code'], $reasonFields['reason_label_snapshot'], $reasonFields['reason_comment']); // Return the list of departments $response->success( $order_items->getItemAsArray() ); } else { // Log the incident (new logs_o())->add('departments', 'global', 1, 0, 'ADD_ORDER_ITEMS', 'No user found, or invalid session'); // Return an error $response->error('Invalid session', 400); } }, [ 'add_order_items' => 'Add order items' ] ); $this->get('/order/items', function () { // Require the user to be logged in global $response; // Check if the user is requesting their own order items $isCustomerAccess = ($this->hasPermission('user') && !($this->hasPermission('list_order_items'))); $user = (new authentication())->get_user(); if ($isCustomerAccess) { $hasPermission = $this->hasPermission('list_own_order_items'); $hasAttribute = $user->showPricesOnBookingPage(); // Check if the user has the attribute to show prices on the booking page if (!$hasPermission && !$hasAttribute) { $response->forbidden(['list_own_order_items', 'list_order_items']); } } else { $this->requirePermission('list_order_items'); } // Check if the request was successful if ($user) { // Get the post data $data = $_GET; // Check if the required fields are set if (!(int)$data['order_id']) { $response->error('Order ID is required', 400); } // Check if the order_id is a valid number if (!is_numeric($data['order_id'])) { $response->error('Order ID must be a number', 400); } // Check if the order exists if (!(new orders_o())->getOrderById((int)$data['order_id'])->exists()) { $response->error('Order not found', 404); } $order = (new orders_o())->getOrderById((int)$data['order_id']); // If the user is requesting their own order items, check if the order belongs to them if ($isCustomerAccess && !$order->isOwnOrder((int)$user->customer_number->value())) { $response->error('Order does not belong to the user', 400); }; // Apply the departments unique pricing $orderItems = $order->getOrderItems($order->id); $orderItems = $order->applyDepartmentPrices($orderItems, $order->department_id->value()); // Return the list of departments $response->success( $orderItems ); } else { // Log the incident (new logs_o())->add('departments', 'global', 1, 0, 'LIST_ORDER_ITEMS', 'No user found, or invalid session'); // Return an error $response->error('Invalid session', 400); } }, [ 'list_order_items' => 'List all order items' ] ); $this->delete('/order/items', function () { // Require the user to be logged in global $response, $db; $this->requirePermission('delete_order_items'); // Get the user object $user = (new authentication())->get_user(); // Check if the request was successful if ($user) { // Get the order item id from the query string or request body $itemIdRaw = $this->fromRequest('id'); if ($itemIdRaw === null || $itemIdRaw === '') { $response->error('Order Item ID is required', 400); } $data = ['id' => $itemIdRaw]; // Look up the order item to check department access $itemId = (int)$data['id']; $stmt = $db->prepare('SELECT oi.order_id FROM order_items oi WHERE oi.id = ? LIMIT 1'); if ($stmt === false) { (new logs_o())->add('order_items', 'global', 1, 0, 'DELETE_ORDER_ITEMS', 'Database error while preparing department access check query'); $response->error('Database error while checking department access', 500); } $stmt->bind_param('i', $itemId); $stmt->execute(); $orderItemRow = $stmt->get_result()->fetch_assoc(); $stmt->close(); if ($orderItemRow !== null) { $orderForAccess = (new orders_o())->getOrderById((int)$orderItemRow['order_id']); if (!$orderForAccess->exists()) { $response->error('Order not found', 404); } self::requireDepartmentAccess((string)(int)$orderForAccess->department_id->value()); $orderPaymentLock = $this->acquireOrderPaymentLock((int)$orderForAccess->id); } else { $response->error('Order item not found', 404); } // Delete the order item (new order_items_o())->removeOrderItem((int)$data['id']); // Return the list of departments $response->success( ['message' => 'Order item deleted'] ); } else { // Log the incident (new logs_o())->add('departments', 'global', 1, 0, 'DELETE_ORDER_ITEMS', 'No user found, or invalid session'); // Return an error $response->error('Invalid session', 400); } }, [ 'delete_order_items' => 'Delete order items' ] ); $this->put('/order/items', function () { // Require the user to be logged in global $response, $db; $this->requirePermission('edit_order_items'); // Get the user object $user = (new authentication())->get_user(); // Check if the request was successful if ($user) { // Get the post data $data = json_decode(file_get_contents('php://input'), true); // Check if the required fields are set if (!isset($data['id'])) { $response->error('Order Item ID is required', 400); } if (!isset($data['price'])) { $response->error('Price is required', 400); } if (!isset($data['notes'])) { $response->error('Notes is required', 400); } if (!isset($data['reference'])) { $response->error('Reference is required', 400); } if (!isset($data['quantity'])) { $response->error('Quantity is required', 400); } $orderItemId = (int)$data['id']; $orderItem = (new order_items_o())->getOrderItemById($orderItemId); if (!$orderItem->exists()) { $response->error('Order item not found', 404); } $orderItemContextResult = $db->query( "SELECT oi.order_id, oi.product_id, p.name AS product_name, p.requires_note AS product_requires_note FROM order_items oi LEFT JOIN products p ON p.id = oi.product_id WHERE oi.id = {$orderItemId} LIMIT 1" ); $orderItemContext = $orderItemContextResult ? $orderItemContextResult->fetch_assoc() : null; if ($orderItemContext === null) { $response->error('Order item not found', 404); } if ($orderItemContext['product_id'] === null || $orderItemContext['product_name'] === null) { $response->error('Product not found', 404); } // Validate audit reason policy for affected products BEFORE the notes check, // so a missing reason_comment yields the more specific message when both apply. $reasonFields = ['reason_code' => null, 'reason_label_snapshot' => null, 'reason_comment' => null]; try { $reasonFields = \classes\order_item_reason_policy::validateForProduct((int)$orderItemContext['product_id'], $data); } catch (\InvalidArgumentException $e) { $response->error($e->getMessage(), 400); } if (products_o::productDataRequiresOrderItemNote([ 'id' => (int)$orderItemContext['product_id'], 'name' => (string)$orderItemContext['product_name'], 'requires_note' => (bool)$orderItemContext['product_requires_note'], ]) && trim((string)$data['notes']) === '') { $response->error('Notes is required for this product', 400); } $order = (new orders_o())->getOrderById((int)$orderItemContext['order_id']); if (!$order->exists()) { $response->error('Order not found', 404); } // Check if the user has access to the department self::requireDepartmentAccess((string)(int)$order->department_id->value()); $canAccessAllOrderItems = $this->hasPermission('list_order_items'); if (!$canAccessAllOrderItems && !$order->isOwnOrder((int)$user->customer_number->value())) { $response->error('Order item does not belong to the user', 403); } $orderPaymentLock = $this->acquireOrderPaymentLock((int)$order->id); // Update the order item (new order_items_o())->updateOrderItem((int)$data['id'], (int)$data['price'], (string)$data['notes'], (string)$data['reference'], (int)$data['quantity'], $reasonFields['reason_code'], $reasonFields['reason_label_snapshot'], $reasonFields['reason_comment']); // Log the incident (new logs_o())->add('departments', 'global', 1, $user->id, 'EDIT_ORDER_ITEMS', 'Changed order item: ' . $data['id']); // Return the list of departments $response->success( ['message' => 'Order item updated'] ); } else { // Log the incident (new logs_o())->add('departments', 'global', 1, 0, 'EDIT_ORDER_ITEMS', 'No user found, or invalid session'); // Return an error $response->error('Invalid session', 400); } }, [ 'edit_order_items' => 'Edit order items' ] ); } private function acquireOrderPaymentLock(int $orderId): order_payment_lock { global $response; $lock = order_payment_lock::tryAcquireOrderMutation($orderId); if ($lock === null) { $response->error([ 'message' => 'The order is currently being changed or paid. Try again.', 'code' => 'order_payment_locked', ], 409); } return $lock; } }