Move stock between two warehouses
Ruby · Rails · advanced · modification
Adds stock transfers between warehouses. The routes gain `POST /api/stock_transfers`, and `Api::StockTransfersController#create` reads the parameters with `params.expect`, looks up the source and destination stock levels for the SKU among the signed-in user's own warehouses (404 otherwise) and calls the new `StockTransfer#perform!`. `perform!` validates the quantity (a whole number from 1 to 1,000,000; a string must be digits only, since the `numericality` check alone accepts a leading sign) and that the warehouses differ, then, in one transaction, reloads both stock levels with `lock!` in id order, checks the source's quantity, saves the transfer, updates both quantities and writes one movement per side. The controller answers 409 when the source has too little stock and 422 with the validation messages. Includes the migration for `stock_transfers` (with a positive-quantity check) and the `stock_transfer_id` reference on `stock_movements`, the new model, the association on `StockMovement`, model tests in `stock_transfer_test.rb` and endpoint tests in `stock_transfers_controller_test.rb`.
Ruby 4.0, Rails 8.1 API endpoints. The app runs on SQLite in development, test and production (Rails 8's default setup: one server, the database file on a persistent volume, WAL journal mode), with the generated `database.yml` (`timeout: 5000`, so a writer waits up to 5 s for the database's write lock). SQLite has no row locks: on Rails 8.1.4 an Active Record transaction on SQLite begins with `BEGIN immediate TRANSACTION`, which takes the database's single write lock, and `lock!`/`with_lock` reload the record with a plain `SELECT` (no `FOR UPDATE`); both observed in the SQL log on 8.1.4. `Api::BaseController` (existing, unchanged) inherits `ActionController::API`, reads `Authorization: Bearer <token>` and sets `Current.user` (an `ActiveSupport::CurrentAttributes` attribute), answering 401 otherwise. `Account has_many :users, :warehouses`; `Warehouse has_many :stock_levels`; a `stock_levels` row (`warehouse_id`, `sku`, `quantity` integer `NOT NULL` with a `quantity >= 0` check constraint, unique on `[warehouse_id, sku]`) exists for every SKU a warehouse stocks, created by the existing catalogue sync with quantity 0, and `stock_movements` (`stock_level_id`, `change` integer `NOT NULL`) is the ledger. `StockLevel` (existing, unchanged) defines `class InsufficientStock < StandardError` and `has_many :movements, class_name: "StockMovement"`, and the goods-receipt and picking jobs (existing, unchanged) change quantities only through its `adjust!(change)`, which runs `with_lock { raise InsufficientStock if quantity + change < 0; update!(quantity: quantity + change); movements.create!(change: change) }`; an account has at most a few hundred stock levels, and quantities stay below 100,000,000 per stock level. Transfers are a few hundred a day; each Puma thread has its own database connection (pool size equals the thread count). `ActiveRecord::RecordNotFound` answers Rails' default 404 and `ActionController::ParameterMissing` Rails' default 400. Every user of an account may move its stock (roles are out of scope). Tests are Minitest with inline records. The transfer form itself ships separately in the warehouse app.
Requirements
- `POST /api/stock_transfers` (new) with `{"stock_transfer": {"sku", "from_warehouse_id", "to_warehouse_id", "quantity"}}` lets any signed-in user move units of one SKU between two of their account's warehouses. On success the source's `quantity` goes down and the destination's goes up by exactly `quantity`, a `stock_transfers` row records who moved how many units from which stock level to which, each side gets one `stock_movements` row linked to the transfer (`-quantity` for the source, `+quantity` for the destination), and the response is 201 with the transfer and both new quantities.
- `quantity` must be an integer from 1 to 1,000,000 (a JSON integer or a string of ASCII digits only; `1.5`, `5.0` and `"+5"` are not accepted) and the two warehouses must differ, otherwise 422 with the validation messages. A warehouse that is not the account's, or that has no stock level for the SKU, answers 404; a request without `stock_transfer` answers 400. None of these changes anything.
- The stock rule: a stock level's `quantity` is never below zero and always equals the sum of its movements' `change`. A transfer of exactly the quantity on hand empties the source; a transfer of more answers 409 `Not enough stock in the source warehouse.` and changes nothing. The check uses the quantity on hand when the transfer is applied, not a value read earlier in the request: transfers and the existing goods-receipt and picking jobs (`StockLevel#adjust!`) touch the same stock levels at the same time, and the rule holds however they interleave.
- A transfer's quantity changes, its `stock_transfers` row and its two movements are saved together or not at all.
- Two transfers in opposite directions between the same two warehouses at the same time (A to B and B to A) both complete when the stock allows; neither fails because of the other.
- Unchanged: every `/api` request needs a valid bearer token (401 otherwise), and `GET /api/stock_levels` keeps its behaviour.
Files touched
- config/routes.rb
- db/migrate/20261103090000_create_stock_transfers.rb
- app/models/stock_transfer.rb
- app/models/stock_movement.rb
- app/controllers/api/stock_transfers_controller.rb
- test/models/stock_transfer_test.rb
- test/controllers/api/stock_transfers_controller_test.rb