# Request Order

Technical reference for the `RequestOrder` model in Care EMR. One model holds both kinds of order: the [purchase order](https://docs.ohc.network/concepts/supply/purchase-order.md) and the [stock request](https://docs.ohc.network/concepts/supply/supply-request.md).

A `RequestOrder` groups requested items and carries the routing: a required destination location, an optional origin location and an optional supplier organization. Each requested item is a `SupplyRequest` row, described in [Supply Request](https://docs.ohc.network/references/supply/supply-request.md).

The origin decides the kind of order. An order without an origin is a purchase order to an outside supplier. An order with an origin is a stock request to another location of the same facility.

The supplier field is informational: no backend rule ties it to either kind, and the permissions are the same for both kinds.

**Source:**

* Model: [`care/emr/models/supply_request.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/supply_request.py)
* Specs: [`care/emr/resources/inventory/supply_request/request_order.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/inventory/supply_request/request_order.py)
* Viewset: [`care/emr/api/viewsets/inventory/request_order.py`](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/inventory/request_order.py)
* Permissions: [`care/security/permissions/supply_request.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/permissions/supply_request.py) · authorization [`care/security/authorization/supply_request.py`](https://github.com/ohcnetwork/care/blob/develop/care/security/authorization/supply_request.py)

The Django model is the storage layer. `status`, `priority`, `intent`, `reason` and `category` are plain `CharField`s there. The allowed values, the validation and the read and write schemas are in the Pydantic resource specs.

## Models

| Model | Purpose |
| - | - |
| `RequestOrder` | A purchase order or a stock request: the routing and coding of one order |
| `SupplyRequest` | One requested item of an order. Documented in [Supply Request](https://docs.ohc.network/references/supply/supply-request.md) |

`RequestOrder` extends [`EMRBaseModel`](https://docs.ohc.network/references/foundation/base-model.md). That page describes the inherited fields.

## `RequestOrder` fields

| Field | Type | Notes |
| - | - | - |
| `name` | `CharField(255)` | Required on create and on update |
| `status` | `CharField(255)` | Spec-bound to `SupplyRequestOrderStatusOptions`. Required on create and on update. See "Status rules" |
| `note` | `TextField`, nullable | Optional (`str \| None`) |
| `tags` | `ArrayField(IntegerField)`, default `list` | An array of integers, not a relation. Rendered to tag objects on read by `SingleFacilityTagManager` |
| `tags_data` | `JSONField`, default `{}` | Not in the request order specs |
| `priority` | `CharField(255)` | Spec-bound to `SupplyRequestPriorityOptions`. Required |
| `intent` | `CharField(255)` | Spec-bound to `SupplyRequestIntentOptions`. Required |
| `reason` | `CharField(255)` | Spec-bound to `SupplyRequestReason`. Required |
| `category` | `CharField(255)` | Spec-bound to `SupplyRequestCategoryOptions`. Required |
| `supplier` | `FK → Organization`, nullable, `CASCADE` | Optional on create. If given, it must be an organization of type `product_supplier`. Not in the update body, so it cannot change after create |
| `origin` | `FK → FacilityLocation`, nullable, `CASCADE`, `related_name="origin_request_orders"` | The location asked to supply. Optional on create; its presence makes the order a stock request. Must differ from the destination and be in the same facility. Cannot change after create |
| `destination` | `FK → FacilityLocation`, `CASCADE`, `related_name="destination_request_orders"` | The receiving location. Required on create. Cannot change after create |

The API accepts an order with neither a supplier nor an origin, and an order with both.

The read schema also returns `created_date`, `modified_date`, `created_by` and `updated_by`.

## Enum values

Each enum is a `str, Enum` in `request_order.py` and binds to the `RequestOrder` field of the same meaning. The labels are the ones Care's frontend shows.

### `SupplyRequestOrderStatusOptions` values

| Value | Label | Notes |
| - | - | - |
| `draft` | Draft | Care's frontend creates every order with this status |
| `pending` | Pending | |
| `in_progress` | — | Not in the status list of Care's frontend |
| `completed` | Completed | No backend rule: the order can move back to `draft`, `pending` or `in_progress`. New requested items are refused |
| `abandoned` | Abandoned | Final for status changes. The move to it sets every requested item to `cancelled` |
| `entered_in_error` | Entered in Error | Final for status changes. The move to it sets every requested item to `entered_in_error` |

`SUPPLY_REQUEST_ORDER_COMPLETED_STATUSES` (`abandoned`, `entered_in_error`, `completed`) is defined in the spec file, but no code uses it. It enforces nothing.

### `SupplyRequestIntentOptions` values

| Value | Label |
| - | - |
| `proposal` | Proposal |
| `plan` | Plan |
| `directive` | Directive |
| `order` | Order |
| `original_order` | Original Order |
| `reflex_order` | Reflex Order |
| `filler_order` | Filler Order |
| `instance_order` | Instance Order |

### `SupplyRequestCategoryOptions` values

| Value | Label |
| - | - |
| `central` | Central |
| `nonstock` | Non Stock |

### `SupplyRequestPriorityOptions` values

| Value | Label |
| - | - |
| `routine` | Routine |
| `urgent` | Urgent |
| `asap` | ASAP |
| `stat` | STAT |

### `SupplyRequestReason` values

| Value | Label |
| - | - |
| `patient_care` | Patient Care |
| `ward_stock` | Ward Stock |

Care's frontend order form starts with intent `order`, category `nonstock`, priority `routine` and reason `ward_stock`.

## Related models

| Relation | Notes |
| - | - |
| `SupplyRequest.order → RequestOrder` | The requested items of the order. See [Supply Request](https://docs.ohc.network/references/supply/supply-request.md) |
| `supplier → Organization` | An organization of type `product_supplier`. See "Supplier organizations" |
| `origin`, `destination → FacilityLocation` | See [Location](https://docs.ohc.network/references/facility/location.md) |
| `DeliveryOrder` | No field links a delivery order to a request order. A delivered item can point at one requested item, so the link exists only per item |

`GET /api/v1/supply_request/request_orders/?delivery_order={id}` lists, up to 100, the request orders that the items of a delivery order point at.

## Resource specs (API schema)

| Spec class | Used for | Fields and behaviour |
| - | - | - |
| `BaseSupplyRequestOrderSpec` | Shared base, and the update body (`pydantic_update_model`) | `id` (optional), `status`, `name`, `note` (optional), `intent`, `category`, `priority`, `reason`. It has no `supplier`, `origin` or `destination` |
| `SupplyRequestOrderWriteSpec` | Create (`pydantic_model`) | Base fields plus `supplier: UUID4 \| None`, `origin: UUID4 \| None` and `destination: UUID4`. Checks the supplier type and that the origin differs from the destination |
| `SupplyRequestOrderReadSpec` | Read | Base fields plus `supplier` (`OrganizationReadSpec`), `origin` and `destination` (location objects), `tags` (rendered by `SingleFacilityTagManager`), `created_date`, `modified_date`, `created_by`, `updated_by` |

### Validation

* Create and update both require `status`, `name`, `intent`, `category`, `priority` and `reason`. `note` is optional. The deployment configuration does not change this.
* Create requires `destination`. `supplier` and `origin` are optional.
* A `supplier` that is not of type `product_supplier` fails with "Supplier organization must be of type product\_supplier, got: `<type>`".
* An `origin` equal to the `destination` fails with "Origin and destination locations must be different."
* An `origin` in another facility than the `destination` fails with HTTP 403 and "Origin and destination must be in the same facility".
* Create accepts any of the six statuses. Only delivery orders are limited to `draft` or `pending` on create.
* The update body has no `supplier`, `origin` or `destination`. Pydantic ignores extra fields, so a changed value in an update is dropped without an error.

### Status rules

`RequestOrderViewSet.perform_update` runs these rules. They came with the Care 3.1 release features commit (`3af5d2804`).

* The update locks the order row with `select_for_update`. A second update waits; it does not fail with 423.
* If the order is `abandoned` or `entered_in_error`, any status change fails with "Request order already abandoned or entered in error".
* A move to `abandoned` sets every requested item of the order to `cancelled`. A move to `entered_in_error` sets every item to `entered_in_error`. Every item changes, whatever its status, `completed` items included.
* The rules run only when the status changes. An `abandoned` or `entered_in_error` order still accepts updates that keep its status, such as a new name or note. The backend's own test does this on purpose.
* `completed` has no rule. A `completed` order can move back to `draft`, `pending` or `in_progress`. An order that is not `abandoned` or `entered_in_error` can move to `completed` from any status, with its items in any state or with no items. Completing changes nothing else.
* Requested items cannot be added to an order that is `completed`, `abandoned` or `entered_in_error`. See [Supply Request](https://docs.ohc.network/references/supply/supply-request.md).
* Deliveries never change a request order or its items. The cascade above is the only writer of item status outside a direct edit.

### Tags

* Create saves the `tags` of the request body. Later changes go through `set_tags` and `remove_tags`, which run the order's update check.
* Applying a tag needs "Can Apply Tag Config to Resources". A tag that is already on the order fails with "Tag already set".
* Request order tags use the tag resource type `supply_request_order`. A tag of another resource type fails with "Tag resource does not match resource type". Tags are applied inside the create transaction, so the whole create fails.
* Care's frontend sends the tags with the create request, and changes them later with `set_tags` and `remove_tags`.

## API integration notes

### Endpoints

`RequestOrderViewSet` serves purchase orders and stock requests at `/api/v1/facility/{facility}/order/request/`.

| Action | Request | Notes |
| - | - | - |
| create | `POST …/order/request/` | `SupplyRequestOrderWriteSpec`, plus optional `tags`. Care's frontend sends status `draft` |
| list | `GET …/order/request/` | See "Filters" and "Authorization" |
| retrieve | `GET …/order/request/{id}/` | |
| update | `PUT …/order/request/{id}/` | `BaseSupplyRequestOrderSpec`. Care's frontend edit form sends the form values and the current status |
| upsert | `POST …/order/request/upsert/` | At most `MAX_DATAPOINTS_PER_UPSERT` items (default 100). Items with an `id` go through the normal update. If one item fails, nothing is saved |
| tags | `POST …/order/request/{id}/set_tags/`, `POST …/order/request/{id}/remove_tags/` | See "Tags" |

The API has no delete for request orders.

### Filters

| Parameter | Behaviour |
| - | - |
| `origin` | Orders from that origin location. Needs the read permission at it |
| `destination` | Orders to that destination location. Needs the read permission at it |
| `include_children` | With `true`, the list also takes orders whose origin or destination is a location below the given one |
| `origin_isnull` | `true` gives purchase orders, `false` gives stock requests. Care's frontend uses `true` for Purchase Orders and `false` for Requests Raised |
| `status` | One or more statuses, comma-separated |
| `date_after`, `date_before` | A range on the created date |
| `priority`, `supplier`, `intent`, `category`, `reason`, `created_by` | Match on that field |
| `tags`, `tags_behavior` | Tag filter; `tags_behavior` is `any` or `all` |

The list sorts by created date or modified date.

### Authorization

| Permission | Slug | Default roles |
| - | - | - |
| "Can Create Supply Request on Facility" | `can_write_supply_request` | Facility Admin, Staff, Doctor, Nurse |
| "Can Read Supply Request" | `can_read_supply_request` | Facility Admin, Administrator, Staff, Doctor, Nurse, Volunteer, Pharmacist |

Both checks need the permission in one of the location's organizations. These are the departments linked to the location with their parent departments, the parent location's organizations, and the facility's root organization "Administration". A sub-department below a linked department does not count.

| Action | Care checks | Refusal |
| - | - | - |
| create | "Can Create Supply Request on Facility" at the destination. The origin is not checked | "Cannot write supply requests" |
| update, every status change, `set_tags`, `remove_tags` | "Can Create Supply Request on Facility" at the destination only. A user who holds it only at the origin cannot change the status | |
| retrieve | "Can Read Supply Request" at the origin or at the destination. The order is looked up across all facilities; the check on its own locations still applies | "Cannot read request orders" |
| list with `origin` or `destination` | "Can Read Supply Request" at each location given | "Cannot list supply requests" |
| list without `origin` and without `destination` | No permission check and no facility filter. Any signed-in user gets every request order of every facility. A backend test calls this intended | |
| `GET /api/v1/supply_request/request_orders/` | Needs `delivery_order`, and "Can Read Supply Request" at that delivery order's origin or destination | "delivery\_order is required" |

* By default, "Can Apply Tag Config to Resources" is held by Facility Admin, Staff, Doctor, Nurse and Pharmacist.
* The role lists are defaults. Only a superuser can create or change roles.
* The permission files also name an Admin role. Role sync leaves that role with the responsibility-organization context only, so the tables leave it out.

### Supplier organizations

* A supplier is an organization of type `product_supplier`.
* Care's frontend lists suppliers with `GET /api/v1/organization/?org_type=product_supplier&name=<search>`.
* The organization list has no permission gate, and it always includes supplier organizations for a user who is not a superuser.
* A superuser adds supplier organizations. A top-level organization needs a superuser, and by default no facility role can create organizations.

### Errors

| Message | Cause |
| - | - |
| "Supplier organization must be of type product\_supplier, got: `<type>`" | The `supplier` is not of type `product_supplier` |
| "Origin and destination locations must be different." | `origin` equals `destination` |
| "Origin and destination must be in the same facility" | HTTP 403. The `origin` is in another facility |
| "Request order already abandoned or entered in error" | A status change on an `abandoned` or `entered_in_error` order |
| "Cannot write supply requests" | Create without "Can Create Supply Request on Facility" at the destination |
| "Cannot read request orders" | Retrieve without "Can Read Supply Request" at the origin or destination |
| "Cannot list supply requests" | List with `origin` or `destination` without "Can Read Supply Request" there |
| "Tag already set" | The tag is already on the order |
| "Tag resource does not match resource type" | The tag is not configured for `supply_request_order` |
| "No datapoints provided", "Too many datapoints provided" | An upsert with no items, or with more than `MAX_DATAPOINTS_PER_UPSERT` items |

## Related

* Concept: [Purchase Order](https://docs.ohc.network/concepts/supply/purchase-order.md)
* Concept: [Stock Request](https://docs.ohc.network/concepts/supply/supply-request.md)
* Reference: [Supply Request](https://docs.ohc.network/references/supply/supply-request.md)
* Reference: [Supply Delivery](https://docs.ohc.network/references/supply/supply-delivery.md)
* Reference: [Inventory Item](https://docs.ohc.network/references/supply/inventory-item.md)
* Reference: [Product Knowledge](https://docs.ohc.network/references/definitions/product-knowledge.md)
* Reference: [Location](https://docs.ohc.network/references/facility/location.md)
* Reference: [Organization](https://docs.ohc.network/references/access-governance/organization.md)
* Reference: [Tag Config](https://docs.ohc.network/references/platform/tag-config.md)
* Reference: [EMR base model](https://docs.ohc.network/references/foundation/base-model.md)
* Source: [supply\_request.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/models/supply_request.py)
* Spec: [request\_order.py on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/resources/inventory/supply_request/request_order.py)
* Viewset: [request\_order.py viewset on GitHub](https://github.com/ohcnetwork/care/blob/develop/care/emr/api/viewsets/inventory/request_order.py)
