## 1. Functional overview

The coffee functionality adds a quality workflow around physical purchase and sale contracts. It is designed to keep the commercial contract, the sample lifecycle, lab results and cupping decisions connected without forcing non-coffee contracts to use any coffee-specific fields.

The workflow is built around these objects:

Object | Purpose | Where users usually access it
--- | --- | ---
`purchase.line` / `sale.line` | Stores the expected coffee profile and target quality thresholds. | Purchase or Sale line, tab Coffee Quality.
`coffee.sample` | Tracks a physical or logical sample linked to a contract line. | From the line tab, or menu Coffee / Samples.
`coffee.lab.analysis` | Tracks a laboratory analysis requested for a sample. | From a sample, or menu Coffee / Lab Analyses.
`coffee.cupping.session` | Groups samples into a tasting session and generates blind cups. | Menu Coffee / Cupping Sessions.
`coffee.cupping.result` | Stores one cupper's evaluation for one cup. | Inside a cup generated by a cupping session.
`coffee.cupping.result.line` | Stores one scored criterion within a cupping result. | Inside a result, in the Criteria list.

The coffee process is advisory by design. It calculates quality status, recommended decisions and warnings, but the user remains responsible for approving, rejecting or requesting another cup.

## 2. Activating coffee mode

Coffee features are optional. They are hidden until the trade configuration enables them.

1. Open the trade configuration.
2. Go to the trade options area.
3. Enable `Active coffee compatibility`.
4. Save the configuration.

Once enabled, the following menus are available under Purchase and Sale:

Coffee / Samples Coffee / Lab Analyses Coffee / Cupping Sessions Coffee / Cupping Criteria

If the option is disabled, coffee menus and the Coffee Quality page on purchase and sale lines are removed from the UI. Existing data remains in the database, but it is not shown to users.

## 3. Coffee Quality tab on purchase and sale lines

The Coffee Quality tab on a trade line stores the expected quality profile for the coffee and the thresholds used to evaluate samples.

Area | Main fields | How it is used
--- | --- | ---
Quality summary | `Coffee quality`, `Coffee origin`, `Coffee type`, `Coffee process` | Identifies the coffee and displays the aggregated quality state of linked samples.
Coffee identity | `Variety`, `Crop year`, `Screen size` | Completes the commercial and physical description of the product.
Quality targets | `Moisture max %`, `Defects max`, `Cup score min` | Defines the thresholds used by lab analysis and sample quality evaluation.
Coffee samples | One2Many list of linked samples | Creates or reviews all samples linked to the trade line.

The line's `Attributes Name` can display the coffee attributes in a compact way, for example origin, type, process, variety, crop, screen, moisture, defects and cup score.

## 4. Packing and market data on trade lines

The trade line also contains coffee operational fields in the general tab. These fields are not part of the sample workflow, but they are useful for physical quantity tracking and market hedging.

Field | Meaning | Operational effect
--- | --- | ---
`Packages` | Number of bags, sacks or packages. | Copied to the virtual lot as `lot_qt` when the line is validated.
`Package unit` | UoM used to describe the package, for example Bag60 or Bag90. | Copied to the virtual lot as `lot_unit`.
`Packing description` | Free text used for readable contract or logistics descriptions. | Informational only.
`Market reference` | Price curve used as the market reference. | Used by pricing, valuation and auto-hedging rules.
`Market price` / `Market delta` | Market entry data used for pricing or hedge generation. | May be copied to a generated derivative entry price.

The default virtual lot is created when the line is validated. The package values are synchronized after creation and are also refreshed if the packing values are later changed and the line is saved again.

## 5. Coffee samples

A coffee sample can be created from the Coffee Quality tab of a purchase or sale line, or from the menu Coffee / Samples. Creating it from a line is preferred because the direction and line link are filled automatically.

### Sample identity

Field | Description
--- | ---
`Reference` | Internal or external sample reference.
`Direction` | Purchase or Sale. It is inferred when the sample is created from a trade line.
`Sample Type` | Offer, Pre-shipment, Shipment, Arrival, Stock, Customer or Retained sample.
`Purchase Line` / `Sale Line` | The contract line the sample belongs to.
`Lot` | Optional physical or virtual lot reference.
`Product`, `Party`, `Origin`, `Coffee type` | Computed from the linked trade line and used for sample review and cupping.

### Storage and lifecycle

Field | Description
--- | ---
`Requested Date` | Defaults to today when a sample is created.
`Received Date` | Filled when the sample is received, or manually entered if needed.
`Shelf life (days)` | Defaults to 90 days.
`Expiry Date` | Calculated from requested or received date plus shelf life when not manually set.
`Quantity`, `Unit`, `Sample location` | Used to track the physical sample stored in the office, lab or warehouse.

### Sample workflow

Sample buttons are displayed depending on the current state. The typical workflow is:

Requested Received Sent to lab Under review Approved / Rejected Expired Archived

Button | Available from | Effect
--- | --- | ---
`Receive` | Requested | Moves the sample to received and fills `Received Date` if it is empty.
`Send to lab` | Received | Moves the sample to sent to lab and creates a lab analysis if a lab is selected.
`Review` | Received or sent to lab | Moves the sample to quality review.
`Evaluate quality` | Received, sent to lab or under review | Computes the recommended decision from lab and cupping data.
`Approve` / `Reject` | Under review, or other reviewable states depending on the button visibility | Records the final decision and decision date.
`Expire` | Active states | Forces the sample into expired state.
`Archive` | Approved, rejected or expired | Moves the sample out of active follow-up.

A sample is considered "expiring soon" when its expiry date is within the next 14 days. Expired samples continue to affect the line's coffee quality status until they are handled.

## 6. Laboratory analyses

A lab analysis records the external or internal laboratory control of a sample. It can be created from a sample or from the global lab analyses menu.

### Creating a lab analysis from a sample

1. Open the sample.
2. Enable `Delegated to lab` if needed.
3. Select a `Lab` and optionally a `Lab Due Date`.
4. Click `Send to lab`.

The system creates a new active lab analysis only if the sample does not already have an active one.

### Lab analysis workflow

State | Meaning | Common action
--- | --- | ---
Draft | The request is being prepared. | Fill lab, due date and requested date.
Sent | The sample has been sent to the lab. | Wait for the report.
Received | The lab report has been received. | Enter moisture, defects, cup score and summary.
Accepted | The lab result is accepted. | Use it for sample evaluation.
Rejected | The lab result is rejected or invalid. | Request another analysis if needed.

The computed field `Compliant` compares the lab values against the target thresholds on the linked purchase or sale line:

- `Moisture %` must be less than or equal to `Moisture max %`.
- `Defects count` must be less than or equal to `Defects max`.
- `Cup score` must be greater than or equal to `Cup score min`.

## 7. Cupping sessions

A cupping session is a tasting event. It groups samples, prepares blind cups and lets cuppers enter one or more results per cup.

### Before creating a session: define criteria

Go to Coffee / Cupping Criteria and create the scoring criteria used by cuppers. Each criterion can have:

- a sequence used for display order;
- a name;
- a criterion type, if used by your local process;
- a maximum score;
- a flag telling whether the score must be subtracted from the total.

Subtractive criteria are useful for defects or penalties. When a result total is calculated, normal criteria add to the total and subtractive criteria reduce it.

### Creating the session

1. Open Coffee / Cupping Sessions.
2. Create a new session.
3. Fill `Name`, `Date`, `Responsible` and `Location`.
4. Check `Cup capacity`. The default is 24.
5. Check `Cups per sample`. The default is 3.
6. Add samples to the `Samples` list.

A session line is a link between one session and one sample. The line also stores the sample's cupping decision: pending, approved, re-cup or rejected.

### Adding a sample from a sample record

You can also open a coffee sample and go to the Cupping sessions tab. When you add a row there, the sample is already known, but you must choose the session. This creates the same session/sample link as adding the sample from the cupping session screen.

### The session workflow

State | Button | What happens
--- | --- | ---
Draft | `Prepare` | Checks capacity, sorts samples and creates missing cups with blind codes.
Prepared | `Start` | Moves the session to in progress. Cuppers can enter results.
In progress | `Done` | Marks the tasting session as completed.
Draft, Prepared or In progress | `Cancel` | Cancels the session.
Cancelled | `Draft` | Reopens the session in draft state.

### What Prepare does

`Prepare` is the important operational step. The system:

- calculates the requested number of cups from each session line;
- blocks the preparation if the total exceeds `Cup capacity`;
- sorts samples by coffee type, origin, reference and id;
- assigns the sequence on each session/sample line;
- creates any missing cups;
- generates blind codes such as `S01-C1`, `S01-C2`, `S02-C1`.

The default tasting order proposes arabicas first, blends and other coffees next, and robustas at the end.

If you change the number of cups per sample after preparation, running Prepare again creates only the missing cups. Existing cups are not deleted.

### Blind information

Cuppers see operational tasting information such as origin and coffee type. They do not need to see the full purchase/sale contract, supplier or customer information during the tasting.

## 8. Cupping results and criteria scoring

Once cups exist, users enter tasting results inside each cup.

### Data hierarchy

1. A `Cupping Session` contains session/sample lines.
2. Each session/sample line contains generated `Cups`.
3. Each cup can contain one or more `Results`.
4. Each result contains scored `Criteria` lines.

### Entering a result

1. Open a cupping session.
2. Open the relevant sample line.
3. Open the relevant cup.
4. Add a result.
5. Select the `Cupper`.
6. Enter the date if it differs from today.
7. Add criteria lines and enter scores.
8. Add notes if needed.

The field `Total score` is computed from the result lines. It is empty until at least one criterion has a score.

### Criteria lines

Field | Meaning
--- | ---
`Criterion` | The scoring criterion configured in Coffee / Cupping Criteria.
`Score` | The numeric score entered by the cupper.
`Defect found` | Marks the criterion as identifying a defect.
`Notes` | Free tasting notes for this criterion.

### Score consolidation

Scores are consolidated upwards:

- Result total = sum of its criteria, with subtractive criteria deducted.
- Cup average = average of result totals entered for that cup.
- Session/sample average = average of all result totals across the line's cups.
- Sample cupping average = average of the cupping results linked to the sample.

A criteria line requires a criterion. If the Add button appears to do nothing, check that the Criteria list is configured with both tree and form views and that cupping criteria exist.

## 9. Quality status and recommended decisions

Quality status is computed from direct sample values, lab analysis values and cupping information. The system compares available values with the thresholds stored on the purchase or sale line.

Indicator | Calculation / logic
--- | ---
`Quality status` | Pass, warning, fail or pending depending on available checks and cupping decisions.
`Recommended decision` | Pass recommends approve, fail recommends reject, warning recommends re-cup, otherwise pending.
`Lab analysis status` | Shows the status of the latest active lab analysis.
`Cupping score` | Uses the average cupping result when available.

Cupping session line decisions have a direct impact:

- If a linked cupping line is marked `rejected`, the sample quality can fail.
- If a linked cupping line is marked `re_cup`, the sample quality can become warning.
- If the values are compliant and no warning/rejection exists, the recommended decision can be approve.

On purchase and sale lines, the computed coffee quality summarizes all linked samples. Rejected, expired or warning samples are therefore visible directly on the contract line.

## 10. Recommended daily routine

1. Review Coffee / Samples / Expiring soon.
2. Review Coffee / Samples / Pending.
3. Check lab analyses waiting for reports.
4. Create or prepare upcoming cupping sessions.
5. After cupping, enter result criteria and session/sample decisions.
6. After lab or cupping data is entered, use `Evaluate quality` on the sample.
7. Approve, reject or request a re-cup according to the quality process.
8. Archive completed samples when they no longer need active follow-up.

A simple full flow is: create sample from the trade line, receive it, send it to the lab and/or add it to a cupping session, enter results, evaluate quality, then approve or reject.

## 11. Troubleshooting and common questions

### The Coffee Quality tab is not visible

Check that `Active coffee compatibility` is enabled in trade configuration and that the view has been reloaded after saving.

### The Add button does nothing in a One2Many list

This usually means that the child record has another required parent field that is not known from the current screen. Examples:

- From a sample, adding a cupping session line requires selecting the `Session`.
- From a result, adding a criteria line requires selecting the `Criterion`.

The current views provide form popups for these cases. If the popup does not appear, reload the client after updating the module views.

### No cups are created

Cups are created by the `Prepare` button on the cupping session. Check that the session has sample lines and that the requested number of cups does not exceed the session capacity.

### A sample remains pending

The system can only recommend a decision when it has enough data to compare against the trade line thresholds. Check moisture, defects, cupping score and lab analysis status.

### The result total does not match the simple sum

Some criteria may be configured as subtractive. In that case their score is deducted from the total instead of added.

### Prepare blocks the session

The total requested cups are above `Cup capacity`. Increase capacity, reduce `Cups per sample`, or remove some samples.