Packing slips for the warehouse
Ruby · Rails · beginner · modification
The warehouse wants to print packing slips straight from the order screen. `app/models/packing_slip.rb` (new) is a small view model that turns an order into the slip's fields: order number, ship-to name, customer number and the line items. `app/controllers/packing_slips_controller.rb` (new) loads the order from the current shop's orders, with its customer and line items preloaded, and renders the slip as JSON. `config/routes.rb` nests a singular `packing_slip` resource under orders. `test/models/packing_slip_test.rb` (new) builds an order with two line items and checks the slip's fields and line order.
Ruby 4.0, Rails 8.1 API app (`ActionController::API`), Minitest; SQLite in development and test, PostgreSQL 16 in production (nothing in this PR depends on which). Existing and unchanged: `ApplicationController` authenticates every request with `authenticate_with_http_token`, matching the token against `shops.api_token`, sets `Current.shop` (an `ActiveSupport::CurrentAttributes`) and answers 401 otherwise. `OrdersController` serves `index` and `show`. Models: `Shop has_many :customers, :orders`; `Customer belongs_to :shop` with `number` NOT NULL and unique per shop; `Order belongs_to :shop`, `belongs_to :customer, optional: true` (`orders.customer_id` is a nullable foreign key, NULL for guest checkout), `has_many :line_items, -> { order(:id) }`, with `number` and `ship_name` NOT NULL; `LineItem` has `sku`, `name` NOT NULL and an integer `quantity` NOT NULL and above 0. Checkout (unchanged) only ever links an order to a customer of the same shop, and an order has 1 to 200 line items. `ActiveRecord::RecordNotFound` answers 404 through Rails' default exception handling.
Requirements
- `GET /orders/:order_id/packing_slip` returns the packing slip of one of the signed-in shop's orders as JSON: `order_number`, `ship_to` (the order's `ship_name`), `customer_number` and `lines`, one entry per line item in the order the items were added, each with `sku`, `name` and `quantity`. Warehouse staff print it and pack the parcel from it.
- `customer_number` is the `number` of the customer account that placed the order. Guest checkout orders have no customer account (`orders.customer_id` is NULL) and print `Guest` as their customer number.
- An order id that does not exist, or that belongs to another shop, answers 404.
- Unchanged: every request is authenticated by the existing `ApplicationController` (401 without a valid shop token), and in production an unhandled exception is logged and answered with Rails' generic 500 response.
Files touched
- config/routes.rb
- app/controllers/packing_slips_controller.rb
- app/models/packing_slip.rb
- test/models/packing_slip_test.rb