Project-A / Project-S - Import / Export - Configuring Comment Types (color, im/ex, charges in comment)

A. Problem Statement / Objective Instructions, either from Customs regarding certain importers, or from customers on how shipments are to be cleared must be adhered to at all times. B. Feature Benefit Hypothesis Visibility of these instructions and notes assists users in various stages of completing a declaration - from quickly identifying goods and rating shipments, correctly and appropriately applying concessions and exemptions to observing payment limits. C. Business Process The system must have the ability to configure specific comment types to bold red fonts for better notability on the Remarks pop up. The current BOS shipment comment type triggered via CUS-CMMT in local lookup is to differentiate based on all volume or just import / export. If admin insert CUS-CMMT for all volume, then BOS comment will be triggered regardless. If admin insert CUS-CMMT for specific import / export, then BOS comment will be triggered for specific import / export only When there are any billable commodity charges, show the Declaration Total Value, Declaration Insurance and Declaration Freight in local currency code in a single row under BOS comment type eg Declaration Value 1020.29 AUD, INS 1.24 AUD, FRT 31.48 AUD If there are more than one declaration in a shipment, add the values of each declaration and combine them as a summed up value Declaration 1 - Declaration Value 1000.00 AUD, INS 1.00 AUD, FRT 31.00 AUD Declaration 2 - Declaration Value 20.29 AUD, INS 0.24 AUD, FRT 0.48 AUD BOS will show - Declaration Value 1020.29 AUD, INS 1.24 AUD, FRT 31.48 AUD Allow the admin to configure the trigger point(s) for when the declaration / shipment estimated / final BOS comments should be added. By default, for Project-A, these triggers should be: Declaration Estimated Values: On RAT Hold Reason PFB Declaration Final Values: On CUS = CLR or On CUS = CMP Shipment Estimated Commodity Charges: On RAT Hold Reason PFB Shipment Final Commodity Charges: On CUS = CLR or On CUS = CMP By default, for Project-S, these triggers should be: Declaration Estimated Values: On RAT Hold Reason PFB Declaration Final Values: On Shipment Status 04 Shipment Estimated Commodity Charges: On RAT Hold Reason PFB Shipment Final Commodity Charges: On Shipment Status 04 Allow admin to configure to turn this feature on / off D. Business Value This functionality assists in brokerage’s communication practices of country emphasizing instructions and important customer requests to ABCC staff for compile purposes. E. Scope In Scope Comment Type Configuration Shipment estimated Shipment final commodity comments BOS Comments that indicate the charges at commodity line level Charges must be displayed up to a precision of two decimal places.

Input documents:

title: SBSS Platform Knowledge Document
content: # SBSS Platform Knowledge Document

## 1. PLATFORM OVERVIEW

**SBSS (Brokerage Operations Support System)** is a comprehensive customs brokerage and cargo management platform used by Carrier Co for processing international shipments, regulatory compliance, and customs declarations across multiple countries.

---

## 2. CORE SYSTEMS & INTEGRATIONS

### 2.1 External Systems

| System | Description | Integration Type |
|--------|-------------|------------------|
| **TPS (Trade Processing System)** | Customs Border Force customs system | Electronic messaging (EDI) |
| **TCS (Host Management System)** | Carrier Co internal host system | Bidirectional data synchronization |
| **Full Turbo** | User interface/query system | Data display and reporting |

### 2.2 System Boundaries

- **SBSS** handles brokerage operations, data validation, status management, and message generation
- **TPS** processes customs declarations and returns authorization responses
- **TCS** manages shipment tracking and provides foundational shipment data

---

## 3. DATA MODEL ARCHITECTURE

### 3.1 Core Entity Hierarchy

```
Master Waybill (MAWB)
├── Shipment (HAWB/House Waybill)
│   ├── Declaration
│   ├── Flow
│   └── Commodity
├── Reference Numbers
└── Brokerage Status
```

### 3.2 Master Waybill Module

**Purpose:** Consolidation-level container for multiple shipments moving under a single manifest

**Key Components:**
- **Number:** Unique Master Waybill identifier (11 numeric characters)
- **Transport Type:** Mode of transport (A = Air, S = Sea)
- **Origin/Destination:** Country and port codes
- **Brokerage Status:** BCR (Brokerage Cargo Report) status tracking

**Reference Numbers (Master Waybill > Miscellaneous > Reference Numbers):**

| Code | Description | Format | Source |
|------|-------------|--------|--------|
| URN | Sender Reference (Unique Reference Number) | an..35 | System-generated |
| CRN | Consolidation Reference Number | 9 alphanumeric | TPS response |
| IRN | Interchange Control Reference Number | Varies | System-generated |
| ICR | Inbound Interchange Control Number | Varies | TPS message |
| MTE | Mode of Transport | A or S | User/System |
| CRT | Cargo Report Type | C/S | User input |
| TPN | Total Number of Packages | Numeric | System-calculated |
| ECN | Number of Empty Containers | Numeric | System-calculated/User |
| TCN | Total Number of Containers | Numeric | System-calculated |
| SRV | Sender Reference Version | Sequential | System-generated |
| MTI | Message Type Identifier | CUSCAR | System-assigned |
| HSD | Header Level Status Description | Text | TPS response |
| FAI | Shipment Numbers Fail Validation | List | System-generated |
| ERR | Header Level Error Description | Text | TPS response |

### 3.3 Shipment Module

**Purpose:** Individual consignment or house bill level data

**Key Components:**
- **Shipment ID:** Unique identifier
- **Tracking Number:** Package tracking reference
- **Master Waybill Number:** Links to parent MAWB
- **Movement:** Origin, destination, export/import details
- **Summary:** Weights, dimensions, descriptions, parties

**Reference Numbers (Shipment > Summary > Reference Numbers):**

| Code | Description | Format | Source |
|------|-------------|--------|--------|
| SEQ | Sequence Number (Line Number) | 001-9999 | System-generated |
| CAN | Customs Authority Number | 9 alphanumeric | TPS/User |
| TRS | Transhipment Number | 9 alphanumeric | TPS/User |
| MWB/MBL | Master Waybill Number | 11 numeric | System-assigned |
| NOC | Number of Containers | Numeric | User/System |
| TNOP | Total Number of Packages | Numeric | User input |
| NOEC | Number of Empty Containers | Numeric | User input |
| TNOC | Total Number of Containers | Numeric | User input |
| CCAN | Contingency Customs Authority Number | 9 alphanumeric | User input |
| NCRI | Nil Cargo Report Indicator | Yes/No | System default |
| ESMRDATE | MSG-ESMR Processing Date | MM/DD/YYYY | System-generated |

**Customer Supplied References:**

| Code | Description | Purpose |
|------|-------------|---------|
| ESMRSD | MSG-ESM Response Status Description | Stores line-level status and description from TPS |
| ESMRED | MSG-ESM Response Error Description | Stores error codes and descriptions from TPS |

### 3.4 Declaration Module

**Purpose:** Customs declaration-specific data linked to shipments

**Structure:** Declaration > Customs > Reference Numbers

| Code | Description | Parent Type | Source |
|------|-------------|-------------|--------|
| DSQ | Declaration Sequence Number | DE | Copy of SEQ |
| CCN | Customs Clearance Number | DE | TPS |
| EDEC/EXCD | Export Declaration Exemption Code | DE | User selection |
| EAC | Export Authority Code | DE | Country prefix |
| MCRN | MAWB CRN (concatenated) | DE | System-generated |

**Exemption Codes (EXCD/EDEC):**

| Code | Description | Use Case |
|------|-------------|----------|
| EXLV | Goods value ≤ AUD 2000 | Low-value consignments (default) |
| EXPE | Unaccompanied Personal Effects | Personal shipments |
| EXDC | Australian Domestic Cargo | Domestic movements |
| EXDD | Military Goods (Australian Government) | Defense shipments |
| EXML | Mail or Diplomatic Bags | Postal/diplomatic |
| EXSP | Australian Spares | Spare parts |
| EXTI | Carnet/Tryptique Temporary Imports | Temporary imports |
| EXCC | Contingency Customs Authority Number | Special authority cases |

### 3.5 Flow Module

**Purpose:** Processing workflow and routing information

**Reference Numbers (Shipment > Flow > Reference Numbers):**

| Code | Description | Purpose |
|------|-------------|---------|
| MWB | Master Waybill Number | Links shipment to MAWB |
| BCRSNT | BCR Sent | Indicates manifest submitted |
| BCRCLR | BCR Clear | Indicates clearance received |
| BCRERR | BCR Error | Indicates error status |

---

## 4. BROKERAGE STATUS MANAGEMENT

### 4.1 Status Types

**BCR (Brokerage Cargo Report) - Master Waybill Level:**

| Status Code | Description | Meaning |
|-------------|-------------|---------|
| RDY | Ready for Submission | Data validated, ready for manual submission trigger |
| RFC | Ready for Customs | Trigger point for original message submission |
| AMD | Ready for Amendment | Trigger point for amendment message |
| WID | Withdrawal Submission | Trigger point for withdrawal message |
| SNT | Sent to Customs | Message successfully transmitted |
| CLR | Clear | Authority to deal granted by customs |
| ERR | Error | Validation issues or permit requirements |
| REJ | Rejected | Submission rejected by customs |
| RVK | Revoked | Authority revoked by customs |
| FAI | Validation Fail | Failed internal SBSS validation |
| SYN | Syntax Error | Interchange syntax error from CONTRL |

**MAN (Manifest) - Shipment Level:**

| Status Code | Description | Meaning |
|-------------|-------------|---------|
| NEW | New | Initial state |
| RDY | Ready | Ready for manifest inclusion |
| PAS | Validation Pass | Passed line-level validation |
| FAI | Validation Fail | Failed line-level validation |
| SNT | Manifest Sent | Included in submitted manifest |
| CLR | Clear | Line cleared by customs |
| ERR | Error | Line-level error from customs |
| REJ | Rejected | Line rejected by customs |
| NST | Not Sent | Not included in submission |
| VLD | Validated | Data validated |
| INT | Intervention | Requires customs intervention |
| CMP | Completed | Processing completed |
| STR | Stored | Stored for later processing |

**CUS (Customs Declaration) - Shipment Level:**

| Status Code | Description | Trigger Condition |
|-------------|-------------|-------------------|
| CLR | Clear | Declaration cleared |
| AAC | Approved Authority Code | Pre-approval granted |

**CT (Clearance Type) - Shipment Level:**

| Code | Description |
|------|-------------|
| ABK | Airway Bill |
| DEM | Demurrage |
| FML | Formal Entry |
| LND | Land |
| TRS | Transhipment |

### 4.2 Status Flow Rules

**Shipment-Level Prerequisites for MSG-ESM Inclusion:**
1. Export Country = AU
2. CUS status = CLR or AAC
3. CCN (Customs Clearance Number) available
4. CT ∈ {ABK, DEM, FML, LND, TRS}
5. MAN status = PAS
6. SEQ number assigned

**Master-Level Prerequisites for MSG-ESM Submission:**
1. BCR status = RFC (Original) or AMD (Amendment) or WID (Withdrawal)
2. Transport Type = A or S
3. All mandatory header data present
4. At least one shipment passes validation (for Original/Amendment)

---

## 5. MESSAGING FRAMEWORK

### 5.1 Message Types

**Outbound Messages (SBSS → TPS):**

| Message Code | Name | Purpose | Function Codes |
|--------------|------|---------|----------------|
| MSG-ESM | Export Sub Manifest | Submit cargo manifest | 9 (Original), 5 (Replace), 50 (Withdrawal) |
| CUSCAR | Customs Cargo Report | Standard EDI format | Same as MSG-ESM |
| ICONTRL | Interchange Control | Acknowledgment response | Various |

**Inbound Messages (TPS → SBSS):**

| Message Code | Name | Purpose |
|--------------|------|---------|
| MSG-ESMR | MSG-ESM Response | Manifest processing results |
| CONTRL | Control Message | Syntax validation results |

### 5.2 Message Structure Standards

**EDI Format:** UN/EDIFACT D.99B

**Standard Segments:**
- **UNH/UNT:** Message header/trailer
- **UNB/UNZ:** Interchange header/trailer
- **BGM:** Beginning of message (function code, reference, version)
- **RFF:** Reference numbers
- **DTM:** Date/time
- **LOC:** Location information
- **NAD:** Name and address
- **TDT:** Transport details
- **GIS:** General indicator
- **CNT:** Control totals
- **CNI:** Consignment information
- **GID:** Goods item details
- **FTX:** Free text

### 5.3 Interchange Control

**ICRN (Interchange Control Reference Number):**
- **Format:** URN + incremental sequence
- **Purpose:** Unique identifier for each message interchange
- **Scope:** Stored in IRN (outbound) and ICR (inbound)
- **Generation:** Automatic on message creation
- **Incrementation:** +1 for each new interchange on same Master

**Sender Reference Version (SRV):**
- **Format:** Sequential number (001, 002, 003...)
- **Purpose:** Version control for messages on same URN
- **Rules:**
  - Original message (Function Code 9): Starts at 001
  - Each subsequent message: Increment by 1
  - Validation: MSG-ESMR must match current SRV

---

## 6. VALIDATION FRAMEWORK

### 6.1 Validation Layers

**Layer 1: Format Validation**
- Data type compliance (numeric, alphanumeric, date)
- Length restrictions
- Character set validation
- Code list membership

**Layer 2: Mandatory Data Validation**
- Required fields present
- Non-zero values where specified
- Conditional mandatory logic

**Layer 3: Business Rules Validation**
- Cross-field dependencies
- Cargo type restrictions
- Transport mode compatibility
- Exemption code logic

**Layer 4: TPS Specification Compliance**
- Segment structure
- Element positioning
- Cardinality rules
- Code value validity

### 6.2 Validation Timing

| Validation Point | Scope | Action on Failure |
|------------------|-------|-------------------|
| MAN status → RDY | Line (Shipment) | MAN status → FAI, Add to Comments FAI |
| BCR status → RFC/AMD/WID | Header (Master) | BCR status → FAI, Log to Brokerage Events |
| Message trigger | Full message | Block submission, maintain FAI status |

### 6.3 Error Handling

**Shipment-Level Errors:**
- **Storage:** Shipment > Comments > FAI (Type = FAI)
- **Format:** One error per line in comment text
- **Example:** "Customs Authority Number is Mandatory when 'Customs Authority Number' is not supplied. Please check Shipment Reference Number CAN."

**Master-Level Errors:**
- **Storage:** Master Waybill > Miscellaneous > Brokerage Events
- **Format:** Concatenated error descriptions
- **Example:** "Mode of Transport is Mandatory. Please check Transport Type."

**TPS Response Errors:**
- **Header Errors:** Location 0000, stored in Master Waybill > Miscellaneous > Brokerage Events
- **Line Errors:** Location matches SEQ, stored in ESMRED Customer Supplied Reference

---

## 7. REFERENCE NUMBER ARCHITECTURE

### 7.1 System-Generated References

**URN (Unique Reference Number):**
- **Level:** Master Waybill
- **Format:** an..35 (e.g., "AU314288")
- **Generation:** Automatic on first MSG-ESM Original
- **Mutability:** Immutable after generation
- **Purpose:** Primary identifier for consolidation across all messages

**SEQ (Sequence Number):**
- **Level:** Shipment (also copied to Declaration DSQ)
- **Format:** 001-9999
- **Generation:** Auto-increment on MAWB assignment
- **Rules:**
  - First shipment on MAWB = 001
  - Each additional shipment = +1
  - Alphabetical order by HAWB
  - Immutable once assigned
  - Retained even if MAWB unassigned
  - History tracked for reassignments

**ICRN Components:**
- **IRN:** Outbound interchange reference (URN + sequence)
- **ICR:** Inbound interchange reference (from TPS message)

**CRN (Consolidation Reference Number):**
- **Level:** Master Waybill
- **Format:** 9 alphanumeric (e.g., "AE793F636")
- **Source:** TPS response (MSG-ESMR)
- **Purpose:** Official customs reference for consolidation
- **Persistence:** Remains unchanged through amendments/withdrawals

**MCRN (MAWB CRN Concatenated):**
- **Level:** Declaration
- **Format:** 11N + space + hyphen + space + 9AN = 23 characters total
- **Example:** "12345678901 - AE793F636"
- **Purpose:** TCS synchronization of MAWB-CRN relationship
- **Trigger:** CIM status change (C, I, M) or CRN update

### 7.2 Reference Number Parent Types

| Code | Description | Scope |
|------|-------------|-------|
| MW | Master Waybill | Consolidation-level references |
| SH | Shipment | House-level references |
| DE | Declaration | Customs declaration references |
| CUREF | Customer Reference | Customer-supplied metadata |

---

## 8. USER PROFILE & PARTY MANAGEMENT

### 8.1 User Profile References

**DIC (Declarant Identification Code):**
- **Location:** SBSS user Profile > References > DIC
- **Purpose:** Identifies responsible party for customs reporting
- **Propagation:** Copied to Shipment Reference RPCID
- **Usage:** Included in UDB (Underbond) requests to TCS

**RPCID (OEM Client ID):**
- **Location:** Shipment > Summary > Reference Numbers > RPCID
- **Source:** User Profile DIC
- **Update Trigger:** Any change to DIC value
- **Downstream:** Sent to BSIS via Entry Packet schema

### 8.2 Party Identification

**TIN (Australian Business Number):**
- **Format:** 11 numeric digits
- **Extended Format:** 14 characters with CAC (ABC) code
- **Acceptable Formats:**
  - 65165836671
  - 65 165 836 671
  - 65 165 836 671 001
  - 65 165 836 671/001
  - 65165836671 001
  - 65165836671/001
  - 65165836671001
- **Normalization:** System removes spaces and special characters
- **CAC Handling:** System strips CAC portion if present, keeps first 11 digits

**OEM Client ID (Client Customs Identifier):**
- **Purpose:** Alternative to TIN for individuals
- **Format:** Alphanumeric
- **Client Type:** IND (Individual) requires Gender field

**Party Roles:**
- **Shipper/Consignor:** Address 01 (AU Exporter)
- **Consignee:** Address 02 (Overseas Receiver)
- **Reporting Party:** TIN linked to digital certificate

---

## 9. TRANSPORT & MOVEMENT

### 9.1 Transport Modes

| Code | Description | TPS Value | Container Logic |
|------|-------------|-----------|-----------------|
| A | Air | 6 | Containers = 0 |
| S | Sea | 11 | Containers > 0 allowed |

**Default Logic:**
- Master Waybill with Origin Country = AU → Transport Type defaults to "A"

### 9.2 Location Codes

**Format:** ISO Country Code (2 char) + Port Code (3 char) = 5 characters
- **Example:** AUSYD (Australia, Sydney)

**Common Ports:**
- AUSYD - Sydney, Australia
- AUMEL - Melbourne, Australia
- AUBNE - Brisbane, Australia

### 9.3 Cargo Report Types

| Code | Description | Container Requirements |
|------|-------------|------------------------|
| C | Consolidation (Sub-Manifest) | Empty containers = 0 |
| S | Slot Charter | Empty containers allowed |

**Default:** C (Consolidation Sub-Manifest)

---

## 10. REPORTING & VISIBILITY

### 10.1 Standard Reports

**Export Consolidation Sub Manifest Validation Report:**

**Purpose:** Pre-submission validation and discrepancy identification

**Filters:**
- Departure Date (range: From/To)
- Port of Departure
- CAN
- MAWB

**Columns:**
- Line No (SEQ)
- Line Type (EXCD/CAN/TRS)
- CAN/TRS Number
- Number of Packages
- Shipment ID
- Tracking Number
- Goods Owner & Party ID
- Goods Description
- Country/Region of Destination
- Clearance Type (CT)
- MAN Status
- CAN Status
- CAN (CRN)
- MAWB
- Flight/Voyage Number
- Port of Departure
- Departure Date
- Weight (Gross, with unit)
- Volume (Dim Weight, with unit)

### 10.2 TCS Response Report

**Purpose:** Track and display response processing from TPS

**Scope:** MSG-ESMR message content visualization

---

## 11. WORKFLOW & HOLDS

### 11.1 Exception Handling

**Configurable Holds:**
- **SR (Split Reason):** Cargo split detected
- **DN (Dynamic Hold):** Configurable via local lookup for split exceptions

**Hold Triggers:**
- CIM Status = M (Master Change)
- CIM Status = I (Incomplete Shipment)
- Validation failures
- Customs response errors

### 11.2 Mass Update Operations

**Typical Workflow:**
1. Search shipments: Export Country = AU, CCN available, CUS = CLR/AAC, same MWB
2. Multi-select applicable shipments
3. Bulk status change: MAN → RDY
4. System validates each shipment
5. Passed shipments: MAN → PAS
6. Failed shipments: MAN → FAI with error details

---

## 12. EVENTS & AUDIT TRAIL

### 12.1 Event Logging

**Shipment Brokerage Events:**
- MAN status changes
- Validation results
- TPS response processing
- Reference number updates

**Master Waybill Brokerage Events:**
- BCR status changes
- Header-level errors
- Message submission records
- CRN assignment

**Declaration Events:**
- Reference number creation
- Status transitions
- Amendment history

### 12.2 Comment Types

| Type | Parent | Purpose |
|------|--------|---------|
| FAI | SH | MSG-ESM Data Validation Failure details |
| Standard | SH | General shipment comments |

---

## 13. DATA CALCULATION & AUTOMATION

### 13.1 Automatic Calculations

**Total Number of Packages (TPN):**
- **Source:** Sum of all Line Section CNT+11 values
- **Trigger:** MSG-ESM message generation
- **Storage:** Master Waybill > Reference Numbers > TPN

**Total Number of Containers (TCN):**
- **Logic:**
  - If Transport Type = A: TCN = 0
  - If Transport Type = S: TCN = Sum of all Line Section CNT+36 values
- **Storage:** Master Waybill > Reference Numbers > TCN

**Number of Empty Containers (ECN):**
- **Logic:**
  - If Transport Type = A: ECN = 0
  - If Cargo Report Type = C: ECN = 0
  - Otherwise: User-entered or calculated
- **Storage:** Master Waybill > Reference Numbers > ECN

**Number of Containers (NOC) - Shipment Level:**
- **Default:** 0 when Mode of Transport = Air (MTE = 6)
- **Storage:** Shipment > Reference Numbers > NOC

### 13.2 Nil Cargo Indicator

**NCRI (Nil Cargo Report Indicator):**
- **Default Value:** "No"
- **Trigger:** Shipment opened with Export Country = AU
- **Location:** Shipment > Reference Numbers > NCRI
- **Values:**
  - "Yes" = Cargo is carried
  - "No" = No cargo is carried (default)

---

## 14. ADMINISTRATIVE CONFIGURATION

### 14.1 SBSS Admin Tables

**Primary Configuration Tables:**
- Brokerage Status Value
- Reference Number Type (MW/SH/DE)
- Custom Code Type
- Custom Code Value
- Comment Type
- Shipment Reference Number Type

### 14.2 Script-Based Setup

**Standard Pattern:**
1. Define codes and descriptions
2. Assign parent types
3. Set quick searchable flags
4. Define default values where applicable
5. Execute via database script
6. Verify via SBSS UI

---

## 15. INTEGRATION PATTERNS

### 15.1 TCS Integration

**Inbound (TCS → SBSS):**
- MAWB assignment messages
- Shipment tracking updates
- CIM status notifications

**Outbound (SBSS → TCS):**
- Entry Packet (EP) messages
- UDB (Underbond) request updates
- CRN and status synchronization via MCRN

### 15.2 TPS Integration

**Message Exchange:**
- SBSS generates MSG-ESM with URN + Version
- TPS validates and returns MSG-ESMR with CRN
- TPS may send unsolicited messages (OU1, idle messages)
- CONTRL messages for syntax errors

**Response Processing:**
- Match inbound message to outbound via IRN/ICR
- Validate SRV matches expected version
- Process header and line-level statuses
- Store CRN and status descriptions
- Update shipment and master statuses

---

## 16. COUNTRY-SPECIFIC RULES

### 16.1 Australia (AU)

**Regulatory Authority:** Customs Border Force (CBF)

**Key Requirements:**
- Export manifests mandatory for all cargo removal
- Electronic submission via TPS only
- Consolidators must report before export
- 30-day export deadline (auto-revocation after)
- TIN or OEM Client ID required for party identification

**Export Clearance Types:**
- ABK (Airway Bill)
- DEM (Demurrage)
- FML (Formal Entry)
- LND (Land)
- TRS (Transhipment)

**Special Handling:**
- Personal effects (EXPE)
- Low-value goods ≤ AUD 2000 (EXLV)
- Contingency procedures (EXCC with CCAN)

---

## 17. TECHNICAL SPECIFICATIONS

### 17.1 Data Formats

| Format Code | Description | Example |
|-------------|-------------|---------|
| an | Alphanumeric | ABC123 |
| n | Numeric | 12345 |
| a | Alphabetic | ABCD |
| ..35 | Variable up to 35 | Variable length string |
| 9 | Fixed 9 | 123456789 |
| 11 | Fixed 11 | 12345678901 |
| MM/DD/YYYY | Date | 12/31/2024 |
| 102 (CCYYMMDD) | Date format code | 20241231 |

### 17.2 Cardinality Rules

- **M:** Mandatory (Must = 1)
- **C:** Conditional (0 or 1 depending on conditions)
- **Max.Use:** Maximum repetitions allowed
- **X:** Excluded (Must not be included)

---

## 18. GLOSSARY OF TERMS

| Term | Definition |
|------|------------|
| **Consolidation** | Multiple shipments grouped under single master waybill |
| **Consolidator** | Entity responsible for grouping and manifesting cargo |
| **Authority to Deal** | Customs clearance to proceed with cargo |
| **Reporting Party** | Entity lodging manifest with customs |
| **Establishment Code** | Depot ID where cargo under customs control |
| **Line** | Individual shipment entry on manifest |
| **Header** | Consolidation-level data on manifest |
| **Original** | First submission of manifest |
| **Amendment** | Change to previously submitted manifest |
| **Withdrawal** | Cancellation of manifest before export |
| **Revocation** | Customs cancellation of authority (auto after 30 days) |
| **Impediment** | Customs hold or requirement blocking clearance |
| **Exemption** | Category of goods not requiring full declaration |

---

## 19. VERSION CONTROL

**Document Type:** Platform Knowledge Document
**Platform:** SBSS (Brokerage Operations Support System)
**Domain:** Australian Export Cargo Reporting
**Feature Reference:** 6603297 (Project-A Export BCR)
**Last Updated:** Based on 29 completed user stories
**Status:** Living document - update as platform evolves

---

title: Customs Brokerage Process Flow
content: # SBSS Export Cargo Reporting Process Flow

## PROCESS OVERVIEW

**Process Name:** Export Cargo Manifest Submission and Response Processing
**Regulatory Context:** Customs Border Force TPS Compliance
**Scope:** Consolidator cargo reporting for air and sea export

---

## PROCESS ACTORS

| Actor | Role | Responsibilities |
|-------|------|-----------------|
| **SBSS System** | Automation Platform | Data validation, message generation, status management |
| **SBSS user** | Operations Personnel | Data entry, status triggers, exception handling |
| **TPS (CBF)** | Customs Authority | Manifest validation, clearance authorization |
| **TCS** | Host System | Shipment tracking, MAWB assignment |
| **Shipper/Exporter** | Customer | Goods owner, export authority |

---

## HIGH-LEVEL PROCESS FLOW

```
1. Shipment Ingestion → 2. MAWB Assignment → 3. Data Preparation → 
4. Validation → 5. Manifest Submission → 6. Response Processing → 
7. Status Updates → 8. Exception Handling → 9. Amendment/Withdrawal
```

---

## PHASE 1: SHIPMENT INGESTION & INITIALIZATION

### 1.1 Shipment Creation

**Trigger:** New export shipment downloaded to SBSS

**Automatic Actions:**
1. System checks Export Country field
2. **If Export Country = "AU":**
   - Add Shipment Reference Number NCRI (Nil Cargo Report Indicator)
   - Set NCRI default value = "No"
   - Set Mode of Transport default = "A" (Air)
3. Shipment enters workflow

**Prerequisites:**
- Shipper information complete
- Destination country identified
- Goods description present

**Output State:**
- Shipment created in SBSS
- Default references initialized
- Ready for customs clearance processing

### 1.2 Customs Clearance

**User Actions:**
1. Process customs declaration (separate from cargo reporting)
2. Obtain Customs Clearance Number (CCN)
3. Set Clearance Type (CT) to one of: ABK, DEM, FML, LND, or TRS

**System Actions:**
1. Store CCN in Declaration > Customs > Reference Numbers > CCN
2. Update CUS status based on clearance result
3. **Valid CUS statuses for manifest eligibility:**
   - CLR (Clear)
   - AAC (Approved Authority Code)

**Decision Point:** Is shipment cleared for export?
- **YES → Proceed to MAWB Assignment**
- **NO → Hold in pre-clearance workflow**

---

## PHASE 2: MASTER WAYBILL ASSIGNMENT

### 2.1 MAWB Assignment from TCS

**Trigger:** TCS sends MAWB assignment message

**Automatic Actions:**
1. System receives MAWB number (11 numeric characters)
2. Store in Shipment > Master Waybill > Number
3. Store in Shipment > Summary > Reference Numbers > MWB (Flow level)
4. **Generate SEQ (Sequence Number):**
   - Check existing shipments on same MAWB
   - Sort all HAWBs alphabetically
   - Assign incremental sequence starting from 001
   - First shipment = 001, second = 002, etc.
   - Store in Shipment > Summary > Reference Numbers > SEQ
   - **Copy SEQ to Declaration > Customs > Reference Numbers > DSQ**
   - Mark SEQ as immutable

**Business Rules:**
- SEQ never changes once assigned
- SEQ retained even if MAWB is unassigned later
- History of MAWB assignments tracked
- SEQ determines line order in manifest

**Output State:**
- Shipment linked to Master Waybill
- Sequence number assigned
- Ready for manifest preparation

### 2.2 Master Waybill Initialization

**Automatic Actions:**
1. **If Master Waybill is new:**
   - Create Master Waybill record
   - Set Origin Country = AU (from shipments)
   - Set default Transport Type = "A" (Air)
   - Initialize Brokerage Status > BCR
2. **Add default references:**
   - NRI (Nil Cargo Report Indicator) at Master level
   - Set default Cargo Report Type (CRT) = "C" (Consolidation)

**User Actions (if needed):**
1. Verify Transport Type (A = Air, S = Sea)
2. Confirm Port of Departure
3. Set Departure Date
4. Review consolidation details

---

## PHASE 3: DATA PREPARATION

### 3.1 Exemption Code Assignment

**User Actions:**
1. Determine if shipment requires full declaration
2. **If exempt, select exemption code:**

| Scenario | Code | Reference Location |
|----------|------|-------------------|
| Goods value ≤ AUD 2000 | EXLV | Declaration > Customs > Ref Numbers > EDEC |
| Personal effects | EXPE | Declaration > Customs > Ref Numbers > EDEC |
| Domestic cargo | EXDC | Declaration > Customs > Ref Numbers > EDEC |
| Military goods | EXDD | Declaration > Customs > Ref Numbers > EDEC |
| Mail/diplomatic | EXML | Declaration > Customs > Ref Numbers > EDEC |
| Spare parts | EXSP | Declaration > Customs > Ref Numbers > EDEC |
| Temporary imports | EXTI | Declaration > Customs > Ref Numbers > EDEC |
| Contingency | EXCC | Declaration > Customs > Ref Numbers > EDEC |

3. **If EXCC selected:**
   - Must also provide CCAN (Contingency Customs Authority Number)
   - Store in Shipment > Reference Numbers > CCAN

**System Actions:**
1. Validate exemption code selection
2. Determine mandatory field requirements based on code
3. **Special requirements for EXPE and EXLV:**
   - Owner Name or Owner Party ID (TIN/OEM Client ID) mandatory
   - Goods Description mandatory
   - Country of Destination mandatory

### 3.2 CAN/TRS Number Handling

**Decision Logic:**

```
IF Clearance Type = TRS (Transhipment):
    IF CAN is empty AND TRS number exists:
        Use TRS number as CAN in manifest
    ELSE IF CAN exists:
        Use CAN number
    ELSE:
        Flag validation error
ELSE:
    Use CAN number (mandatory)
```

**User Actions:**
1. Ensure either CAN or TRS is present for transhipments
2. Verify CAN for non-transhipment clearances

**Storage:**
- CAN: Shipment > Reference Numbers > CAN
- TRS: Shipment > Reference Numbers > TRS

### 3.3 Party Information Preparation

**Owner/Shipper Details:**

**User Actions:**
1. Verify Shipper Name in Declaration > Customer > Shipper > Name
2. Ensure TIN or OEM Client ID present:
   - **TIN:** Shipper > Profile > Comments > TIN
   - **OEM Client ID:** Shipper > Profile > Comments > OID

**System Actions:**
1. **Format TIN:**
   - Remove all spaces
   - Remove special characters (/, -, etc.)
   - If CAC code present (positions 12-14), strip it
   - Keep first 11 numeric digits only
   - Examples:
     - "65 165 836 671 001" → "65165836671"
     - "65165836671/001" → "65165836671"

2. **Validate Party ID:**
   - If OEM Client ID with Client Type = IND (Individual):
     - Gender field becomes mandatory
     - Validation fails if Gender missing

### 3.4 Container & Package Information

**User Actions (if applicable):**
1. Enter Number of Packages
2. For sea shipments, enter Number of Containers
3. Store in:
   - Packages: Shipment > Summary > Number of Packages
   - Containers: Shipment > Reference Numbers > NOC

**System Auto-Calculations:**
1. **If Mode of Transport = Air (MTE = 6):**
   - Automatically set NOC = 0
2. Prepare for header-level totalization

---

## PHASE 4: PRE-SUBMISSION VALIDATION

### 4.1 Manual Status Trigger

**User Workflow:**
1. Navigate to SBSS > Mass Update
2. **Apply search filters:**
   - Export Country = AU
   - Declaration Reference CCN is available
   - CUS status = CLR or AAC
   - Same Master Waybill Number (MBL/MWB)
3. Review search results
4. **Multi-select applicable shipments**
5. **Bulk action: Change MAN status to RDY**

**System Response:**
- Status change logged in Shipment Brokerage Events
- Triggers Line Section validation

### 4.2 Line Section Validation (Shipment Level)

**Trigger:** MAN status changed to RDY

**Validation Checks:**

**Mandatory Data Validation:**
- [ ] SEQ number present
- [ ] CAN or TRS present (if CT = TRS)
- [ ] Number of Packages > 0
- [ ] HAWB number present
- [ ] Owner Name or Owner Party ID present (if EXPE/EXLV)
- [ ] Goods Description present (if EXPE/EXLV)
- [ ] Country of Destination present

**Conditional Data Validation:**
- [ ] If EXCC: CCAN must be present
- [ ] If EXPE or EXLV: Owner details mandatory
- [ ] If Transport Mode = Air: NOC must = 0
- [ ] If TIN: Format must be 11 numeric digits

**Format Validation:**
- [ ] SEQ: 001-9999
- [ ] CAN/TRS: 9 alphanumeric
- [ ] TIN: 11 numeric (after normalization)
- [ ] Owner Name: ≤ 35 characters
- [ ] Goods Description: within character limit

**Validation Outcome:**

**IF ALL CHECKS PASS:**
1. Set MAN status = PAS (Validation Pass)
2. Log success in Shipment Brokerage Events
3. Shipment eligible for manifest inclusion

**IF ANY CHECK FAILS:**
1. Set MAN status = FAI (Validation Fail)
2. Create Comment Type FAI
3. Add detailed error messages to Comments > FAI:
   - One error per line
   - Include field name and location
   - Example: "Customs Authority Number is Mandatory when 'Customs Authority Number' is not supplied. Please check Shipment Reference Number CAN."
4. **Trigger warning popup** to user with error details
5. Shipment excluded from manifest submission

**User Response to FAI:**
1. Review errors in Comments > FAI
2. Correct data issues
3. Change MAN status back to RDY to re-trigger validation
4. Repeat until MAN status = PAS

### 4.3 Report-Based Review (Optional)

**User Workflow:**
1. Navigate to Reports > Export Consolidation Sub Manifest Validation Report
2. **Apply filters:**
   - Departure Date range
   - Port of Departure
   - Specific CAN or MAWB
3. Review report columns for discrepancies
4. Correct any issues identified
5. Re-run validation via MAN status change

---

## PHASE 5: MANIFEST GENERATION & SUBMISSION

### 5.1 Header Section Preparation

**User Action:**
1. Navigate to Master Waybill > Brokerage Status > BCR
2. **Change BCR status to RFC (Ready for Customs)**

**System Actions - URN Generation:**
1. **Check if URN exists:**
   - Master Waybill > Miscellaneous > Reference Numbers > URN
2. **If URN does not exist:**
   - Generate unique reference (format: AU######, e.g., "AU314288")
   - Store in URN field
   - Lock field to prevent user modification
3. **If URN exists:**
   - Use existing URN (for amendments)

**System Actions - Reference Initialization:**
1. **Initialize Sender Reference Version (SRV):**
   - If first Original message: SRV = 001
   - If subsequent message: Increment existing SRV by 1
   - Store in Master Waybill > Reference Numbers > SRV

2. **Generate Interchange Control Reference:**
   - Combine URN + incremental sequence
   - Store as IRN (Interchange Control Reference Number)
   - Will be used as 0020 in UNB/UNZ segments

3. **Store Message Type:**
   - Set MTI = "CUSCAR"
   - Master Waybill > Reference Numbers > MTI

### 5.2 Header Section Validation (Master Level)

**Trigger:** BCR status = RFC (or AMD/WID for amendments)

**Validation Checks:**

**Mandatory Header Data:**
- [ ] URN present
- [ ] Mode of Transport = A or S
- [ ] Departure Date present
- [ ] Port of Departure present
- [ ] Cargo Report Type present

**Conditional Header Data:**
- [ ] If Transport Type = A: ECN must = 0
- [ ] If Cargo Report Type = C: ECN must = 0
- [ ] All associated shipments have MAN status = PAS

**Calculated Values:**
1. **Total Number of Packages (TPN):**
   - Sum all Shipment > Number of Packages
   - Store in Master Waybill > Reference Numbers > TPN
   - **Special Rule:** If all packages = 0 and Transport = A, TPN may be 0

2. **Total Number of Containers (TCN):**
   - If Transport Type = A: TCN = 0
   - If Transport Type = S: Sum all Shipment > NOC values
   - Store in Master Waybill > Reference Numbers > TCN

3. **Number of Empty Containers (ECN):**
   - If Transport Type = A: ECN = 0
   - If Cargo Report Type = C: ECN = 0
   - Otherwise: User-entered or default 0
   - Store in Master Waybill > Reference Numbers > ECN

**Validation Outcome:**

**IF ALL CHECKS PASS:**
1. Proceed to message generation
2. BCR remains at RFC temporarily

**IF ANY CHECK FAILS:**
1. Set BCR status = FAI (Validation Fail)
2. Log detailed errors to Master Waybill > Brokerage Events:
   - Example: "Mode of Transport is Mandatory. Please check Transport Type."
   - Example: "Number of Empty Containers must be = 0 when Mode of Transport is Air. Please check Reference Number ECN."
3. **Check associated shipments:**
   - If all shipments have MAN = FAI:
     - Add error: "MSG-ESM data validation fail for all shipments associated with this Master Waybill, please check."
4. Block message submission

**User Response to FAI:**
1. Review errors in Brokerage Events
2. Correct Master-level data issues
3. Address any shipment-level validation failures
4. Change BCR status back to RFC to re-trigger validation

### 5.3 MSG-ESM Message Generation

**Trigger:** Header validation passes with BCR = RFC

**Message Assembly Process:**

**Step 1: Header Section Construction**

**UNH Segment (Message Header):**
- Message Reference Number: Sequential
- Message Type: CUSCAR:D:99B:UN

**BGM Segment (Beginning of Message):**
- Document Name Code: 87 (Cargo manifest)
- Document Identifier Code: "MSG-ESM"
- Sender Reference: URN value
- Sender Reference Version: SRV value (e.g., "001")
- Message Function Code: **9** (Original)

**LOC+107 Segment:** (Excluded based on specification)

**RFF+AIZ Segment:** (Only for Function Code ≠ 9)
- Not included in Original message
- Will be added in Amendment/Withdrawal messages with CRN

**TDT Segment (Transport Details):**
- Transport Stage Qualifier: 20
- Mode of Transport:
  - If Master > Transport Type = "A": Insert "6"
  - If Master > Transport Type = "S": Insert "11"

**DTM Segment (Date/Time):**
- Date/Time Qualifier: 136 (Departure Date)
- Date: Master Waybill > Departure Date
- Format: CCYYMMDD (102)

**GIS Segments (General Indicators):**
- **GIS+109 (Slot Charter Indicator):** Skip if Cargo Report Type = C
- **GIS+121 (Nil Cargo Indicator):**
  - Processing Indicator: Master > Reference Numbers > NRI
  - Map "Yes" → "C", "No" → leave blank or specific code

**CNT Segments (Control Totals):**
- **CNT+11 (Total Packages):** TPN value (skip if TPN = 0)
- **CNT+30 (Empty Containers):** ECN value (skip if ECN = 0)
- **CNT+36 (Total Containers):** TCN value (skip if TCN = 0)

**Step 2: Line Section Construction**

**For each shipment where:**
- Master Waybill > Number matches message Master
- MAN status = PAS
- SEQ number exists

**Build Line Section:**

**CNI Segment (Consignment Information):**
- Consolidation Item Number: SEQ value (formatted as 0001, 0002, etc.)

**CNT+11 (Number of Packages):**
- Package Count: Shipment > Number of Packages
- Skip if value = 0

**CNT+36 (Number of Containers):**
- Container Count: Shipment > Reference Numbers > NOC
- Skip if value = 0

**RFF+AHV (Contingency CAN):**
- Only if EDEC = EXCC
- Reference: Shipment > Reference Numbers > CCAN

**RFF+TL (Exemption Code):**
- Only if CAN not supplied
- Reference: Declaration > Customs > Reference Numbers > EDEC

**RFF+TN (Customs Authority Number):**
- Reference: Shipment > Reference Numbers > CAN
- **Special Logic:** If CT = TRS and CAN empty, use TRS value

**RFF+HWB (House Waybill):**
- Reference: Shipment > HAWB number

**LOC+28 (Country of Destination):**
- Only if EDEC = EXPE or EXLV
- Location: Shipment > Movement > Destination > Country

**NAD+GO (Goods Owner):**
- **Party ID (3039):**
  - Shipper > Profile > Comments > TIN (formatted, 11 digits)
  - OR Shipper > Profile > Comments > OID
  - Code Qualifier: 95
  - Mandatory if EXPE/EXLV and Owner Name not provided
- **Party Name (3036):**
  - Declaration > Customer > Shipper > Name
  - Max 35 characters
  - Mandatory if EXPE/EXLV and Party ID not provided

**GID Segment (Goods Item):**
- Only if EDEC = EXPE or EXLV
- Goods Item Number: 1

**FTX+AAA (Goods Description):**
- Only if EDEC = EXPE or EXLV
- Free Text: Shipment > Summary > Description

**Step 3: Message Trailer**

**UNT Segment:**
- Segment Count: Total segments in message
- Message Reference: Matches UNH

### 5.4 Message Transmission

**Pre-Transmission Actions:**
1. Wrap message in UNB/UNZ interchange envelope:
   - Interchange Control Reference: IRN value
   - Sender/Receiver identification
2. Format according to UN/EDIFACT D.99B standard
3. Perform final syntax validation

**Transmission:**
1. Send MSG-ESM message to TPS via secure channel
2. Receive transmission acknowledgment (not customs response)

**Post-Transmission Actions:**

**Automatic Status Updates:**
1. **Master Waybill Level:**
   - Change BCR status: RFC → SNT (Sent to Customs)
   - Log event in Brokerage Events
   - Record transmission timestamp

2. **Shipment Level:**
   - For all shipments included in message:
     - Change MAN status: PAS → SNT (Manifest Sent)
     - Log event in Shipment Brokerage Events

3. **Flow Level:**
   - Check Shipment > Flow > Reference Numbers > MWB
   - If MWB matches Master Waybill > Number:
     - Add Reference Number BCRSNT to flow
     - Indicates "BCR Sent" status

**User Notification:**
- System displays confirmation of successful submission
- User can view sent message details in Master Waybill events

---

## PHASE 6: RESPONSE PROCESSING

### 6.1 MSG-ESMR Message Receipt

**Trigger:** TPS returns MSG-ESMR (Export Sub Manifest Response)

**Initial Processing:**

**Step 1: Message Identification**
1. Extract from RFF+ABO segment:
   - 1154 - Sender Reference: Map to Master Waybill > URN
2. Extract from RFF+AFM segment:
   - 1154 - Message Function Code: Identify transaction type
3. **Validate Sender Reference Version:**
   - Extract 4000 from RFF+ABO
   - Compare with Master Waybill > Reference Numbers > SRV
   - **If mismatch:** Skip MSG-ESMR processing (version conflict)
   - **If match:** Proceed with processing

**Step 2: ICR Processing**
1. Extract 0020 - Interchange Control Reference from UNB segment
2. Store in Master Waybill > Reference Numbers > ICR
3. Use for future ICONTRL acknowledgments

### 6.2 Consolidation Reference Assignment

**CRN Processing:**

**Extract from RFF+AIZ segment:**
- 1154 - Consolidation Reference Number (9 alphanumeric)
- Example: "AE793F636"

**Storage Actions:**
1. **Master Waybill Level:**
   - Store in Master Waybill > Reference Numbers > CRN
   - CRN becomes permanent identifier for consolidation
   - Will not change even through amendments/withdrawals

2. **Shipment Level:**
   - For all shipments in response (identified by SEQ):
     - Store CRN in Shipment > Declaration > Customs > Ref Numbers > CRN

3. **MCRN Concatenation (for TCS):**
   - Format: MAWB Number + " - " + CRN
   - Example: "12345678901 - AE793F636"
   - Store in Declaration > Customs > Reference Numbers > MCRN
   - **Triggers for MCRN update:**
     - CIM status = C (Complete)
     - CIM status = I (Incomplete)
     - CIM status = M (Master Change)
     - Any change to CRN value
   - Purpose: TCS synchronization via Entry Packet message

### 6.3 Header-Level Status Processing

**Extract from FTX+AHN segment (Header Section):**
- 4440 - Status Type
- 4440 - Status Description

**Status Type Values & Actions:**

**CLEAR:**
1. Update Master Waybill > Brokerage Status > BCR = CLR
2. Store full status in Master Waybill > Brokerage Events:
   - "CLEAR: THE GOODS COVERED BY THE DOCUMENT ARE AUTHORISED FOR EXPORT AND MAY BE DEALT WITH."
3. Authority to deal granted
4. Consolidation approved for export

**ERROR:**
1. Update Master Waybill > Brokerage Status > BCR = ERR
2. Store full status with sub-type:
   - "ERROR - VALIDATION: ..."
   - "ERROR - SUSPENDED: ..."
   - "ERROR - EMBARGOED: ..."
   - "ERROR - EXPIRED: ..."
3. Review required before goods can be dealt with
4. May indicate permit requirements or data issues

**REJECTED:**
1. Update Master Waybill > Brokerage Status > BCR = REJ
2. Store full status in Brokerage Events
3. Submission rejected by TPS
4. Re-submission or correction required

**REVOKED:**
1. Update Master Waybill > Brokerage Status > BCR = RVK
2. Store full status in Brokerage Events
3. Authority to deal revoked by customs
4. Often occurs automatically after 30 days if not exported
5. Cannot be reinstated; must withdraw and resubmit

**PROCESSING:**
1. Update Master Waybill > Brokerage Status > BCR = SNT (remains)
2. TPS validation ongoing
3. Await final status update

**WITHDRAWN:**
1. Update Master Waybill > Brokerage Status > BCR = WID
2. Consolidator successfully withdrew manifest
3. Terminal status; cannot be changed

### 6.4 Line-Level Status Processing

**Extract from CST segment:**
- 1496 - Line Number: Maps to SEQ

**For each line in response:**

**Step 1: Identify Shipment**
1. Extract Line Number (e.g., "0017")
2. Convert to SEQ format (e.g., 17)
3. Map to Shipment with matching:
   - Shipment > Declaration > Customs > Ref Numbers > SEQ
   - AND Shipment > Master Waybill > Number = response Master

**Step 2: Process FTX+AHN (Line Section)**
- 4440 - Line Status Type
- 4440 - Line Status Description

**Line Status Actions:**

**CLEAR:**
1. Update Shipment > Brokerage Status > MAN = CLR
2. Store status details:
   - ESMRSD > Number: "CLEAR"
   - ESMRSD > Comment: Full status description
3. **Flow-level update:**
   - Check Shipment > Flow > Reference Numbers > MWB
   - If MWB = Master Waybill > Number:
     - Add Reference Number BCRCLR to flow
   - Indicates clearance at flow level

**ERROR:**
1. Update Shipment > Brokerage Status > MAN = ERR
2. Store status details:
   - ESMRSD > Number: "ERROR"
   - ESMRSD > Comment: Full status description including sub-type
3. **Flow-level update:**
   - Check Shipment > Flow > Reference Numbers > MWB
   - If MWB = Master Waybill > Number:
     - Add Reference Number BCRERR to flow
4. May require intervention or additional documentation

**REJECTED (Header-Level Impact):**
- If Header Status Type = REJECTED:
  - Update MAN status of ALL associated shipments to REJ
  - Entire manifest rejected; affects all lines

### 6.5 Error Detail Processing

**Segment Group 4: ERP-ERC-FTX**

**Purpose:** Detailed error information with location and description

**Step 1: Determine Error Location**

**Extract from ERP segment:**
- 1054 - Error Location (format: L0 = Header, L0001-L9999 = Line)

**Error Location Logic:**

**IF Error Location = 0000 (Header Level):**
1. Extract 9321 - Error Identifier from ERC segment
2. Extract 4440 - Error Description from FTX+AAO segment
3. Store in Master Waybill > Brokerage Events:
   - Full error details including identifier and description
4. **Impact on associated shipments:**
   - Map Master Waybill > Number to all Shipment > Master Waybill > Number
   - If Header Status Type = REJECTED:
     - Update all associated shipments: MAN = REJ
5. Example errors:
   - "Total number of packages does not match sum of line packages"
   - "Departure date is in the past"
   - "Invalid port code"

**IF Error Location = 0001-9999 (Line Level):**
1. Map Error Location to SEQ:
   - Error Location "0178" → SEQ 178
2. Extract 9321 - Error Identifier from ERC segment
3. Extract 4440 - Error Description from FTX+AAO segment
4. Store in identified shipment:
   - ESMRED > Number: Error Identifier
   - ESMRED > Comment: Full error description
5. Example errors:
   - "Owner TIN format invalid"
   - "Goods description missing for exemption code EXPE"
   - "Number of packages must be greater than zero"

**Step 2: Display in Remark Popup**

**User Experience:**
1. When user opens shipment with ESMRSD or ESMRED values:
   - System displays remark popup automatically
2. Popup contents:
   - **ESMRSD:** Status description from TPS
   - **ESMRED:** Error descriptions (may be multiple)
3. User can view details without navigating to reference fields

### 6.6 MSG-ESMR Date Recording

**Automatic Action:**
1. Upon MSG-ESMR processing completion:
   - Record current system date
   - Store in Shipment > Reference Numbers > ESMRDATE > Effective Date
   - Format: MM/DD/YYYY
2. **Applies to:**
   - All shipments associated with responding Master Waybill
   - Regardless of whether line details included in MSG-ESMR
   - Even if shipment not in manifest (for tracking purposes)

### 6.7 Syntax Error Handling (CONTRL Message)

**Trigger:** TPS sends CONTRL message indicating syntax errors

**Processing Logic:**

**Step 1: Identify Impacted Message**
1. Extract from UCI segment:
   - 0020 - Interchange Control Reference (Inbound)
   - 0083 - Interchange Action Code
2. Map 0020 to Master Waybill > Reference Numbers > IRN
3. Extract from UCM segment:
   - 0065 - Message Type Identifier
   - 0083 - Message Action Code

**Step 2: Check for Rejection**
- **If 0083 (UCI or UCM) = 4 (Rejected):**
  - Syntax error detected
  - Message not processed by TPS

**Step 3: Validate Message Match**
- Compare UCM > 0065 with Master Waybill > Reference Numbers > MTI
- **If both = "CUSCAR":**
  - Confirmed MSG-ESM syntax error
  - Proceed with error recording

**Step 4: Update Status**
1. Set Master Waybill > Brokerage Status > BCR = SYN
2. Log status change in Brokerage Events

**Step 5: Record Error Details**

**Interchange Syntax Errors (UCI segment):**
- Extract 0085 - Interchange Syntax Error Code
- Map to error description using Control Message Syntax Error Codes
- Store in Master Waybill > Reference Numbers > ISE

**Message Syntax Errors (UCM segment):**
- Extract 0085 - Message Syntax Error Code
- Map to error description
- Store in Master Waybill > Reference Numbers > MSE
- Example Code 18: "Notification that an error has been identified, but the nature of the error is not reported."

**Segment Syntax Errors (UCS segment):**
- Extract 0085 - Message Segment Syntax Error Code
- Map to error description
- Store in Master Waybill > Reference Numbers > SSE

**Data Element Syntax Errors (UCD segment):**
- Extract 0085 - Message Data Element Syntax Error Code
- Map to error description
- Store in Master Waybill > Reference Numbers > DSE

**User Actions Required:**
1. Review syntax errors in Reference Numbers
2. Identify root cause (format, structure, invalid code)
3. Correct data in SBSS
4. Re-submit manifest with corrected data

---

## PHASE 7: POST-CLEARANCE ACTIONS

### 7.1 Success Scenario (CLEAR Status)

**Conditions:**
- Header Status = CLEAR
- All Line Statuses = CLEAR
- CRN assigned

**System State:**
- Master Waybill > BCR = CLR
- All Shipments > MAN = CLR
- Flow-level BCRCLR reference added
- CRN stored at Master and Shipment levels
- MCRN concatenated for TCS

**Business Outcome:**
- Goods authorized for export
- Consolidation may proceed
- Carrier can load cargo
- Export documentation complete

**User Actions:**
1. Verify clearance in Full Turbo
2. Coordinate cargo release with warehouse
3. Provide documentation to carrier
4. Monitor departure date compliance (30-day window)

### 7.2 Error Scenario (ERROR Status)

**Conditions:**
- Header Status = ERROR (with sub-type)
- OR one or more Line Statuses = ERROR
- CRN may or may not be assigned

**System State:**
- Master Waybill > BCR = ERR or Shipment > MAN = ERR
- Error details in ESMRED and/or Brokerage Events
- Flow-level BCRERR reference may be added
- Remark popup displays on shipment open

**Error Types & Responses:**

**ERROR - VALIDATION:**
- **Cause:** Data validation failure at TPS
- **Action:** Review error details, correct data, submit amendment

**ERROR - SUSPENDED:**
- **Cause:** Customs hold or investigation
- **Action:** Contact customs, provide additional documentation

**ERROR - EMBARGOED:**
- **Cause:** Export restrictions or prohibitions
- **Action:** Verify commodity codes, obtain special permits

**ERROR - EXPIRED:**
- **Cause:** CAN or permit expired
- **Action:** Obtain new CAN/permit, update in SBSS, submit amendment

**User Workflow:**
1. Open shipment in SBSS
2. Review remark popup with error details
3. Check ESMRED > Comment for specific instructions
4. Correct underlying issue
5. Proceed to Amendment process (Phase 9)

### 7.3 Rejected Scenario (REJECTED Status)

**Conditions:**
- Header Status = REJECTED
- All Line Statuses updated to REJ
- Submission not accepted by TPS

**System State:**
- Master Waybill > BCR = REJ
- All Shipments > MAN = REJ
- Error details in Brokerage Events
- No CRN assigned (or previous CRN retained)

**Common Rejection Causes:**
- Invalid Sender Reference
- Duplicate submission
- Unauthorized reporting party
- Critical data missing or malformed
- System-level TPS error

**User Actions:**
1. Review rejection reason in Brokerage Events
2. Identify root cause
3. **Determine resolution path:**
   - **If correctable:** Fix data, re-submit as new Original
   - **If duplicate:** Verify CRN from previous submission
   - **If authorization issue:** Contact CBF, verify credentials
4. Do not proceed to Amendment (no CRN to amend)

### 7.4 Revoked Scenario (REVOKED Status)

**Conditions:**
- Header Status = REVOKED
- Typically occurs automatically 30 days after intended departure date
- OR customs manually revokes authority

**System State:**
- Master Waybill > BCR = RVK
- All Shipments > MAN = unchanged or updated
- Status description indicates revocation reason

**User Actions:**
1. Verify goods have not been exported
2. **Determine next steps:**
   - **If goods still available:** Proceed to Withdrawal, then resubmit new manifest
   - **If already exported:** Contact customs for resolution
3. Cannot amend revoked manifest; must start new submission

**Legal Note:** Dealing with goods after revocation may constitute customs offense

---

## PHASE 8: EXCEPTION HANDLING

### 8.1 Validation Failures

**Shipment-Level Failures:**

**Trigger:** MAN status = FAI after validation

**User Workflow:**
1. Navigate to shipment in SBSS
2. Review Comments > Type FAI
3. Identify missing or incorrect data:
   - Each error listed separately
   - Includes field name and location
4. **Correction process:**
   - Update incorrect fields
   - Add missing mandatory data
   - Reformat data if needed (e.g., TIN)
5. Change MAN status: FAI → RDY
6. Re-trigger validation
7. **If passes:** MAN → PAS, ready for inclusion
8. **If fails again:** Review new error details, repeat

**Master-Level Failures:**

**Trigger:** BCR status = FAI after validation

**User Workflow:**
1. Navigate to Master Waybill in SBSS
2. Review Brokerage Events for error details
3. Identify header-level issues:
   - Mode of Transport invalid
   - Container counts incorrect
   - All shipments failed validation
4. **Correction process:**
   - Fix Master Waybill data (Transport Type, Reference Numbers)
   - Address shipment-level failures first
   - Ensure at least one shipment has MAN = PAS
5. Change BCR status: FAI → RFC
6. Re-trigger validation
7. **If passes:** Message submits automatically
8. **If fails again:** Review new error details, repeat

### 8.2 Cargo Split Exceptions

**Trigger:** TCS indicates cargo split

**CIM Status Values:**
- **M:** Master Change (shipment moving to different MAWB)
- **I:** Incomplete Shipment (not all packages on same master)

**System Actions:**
1. Receive CIM status update from TCS
2. Add exception reasons to shipment:
   - **SR:** Split Reason (hardcoded)
   - **DN:** Dynamic Hold (configurable via local lookup)
3. Place shipment on workflow hold

**User Workflow:**
1. Receive notification of exception hold
2. Review shipment details and CIM status
3. **Determine action:**
   - **If Master Change (M):**
     - Wait for new MAWB assignment
     - SEQ will be regenerated on new master
     - Previous MAWB history retained
   - **If Incomplete (I):**
     - Coordinate with warehouse for package consolidation
     - May require manifest amendment
4. **Once resolved:**
   - Remove hold
   - Update MAN status as needed
   - Include in amended manifest if applicable

### 8.3 Missing Data Scenarios

**TIN/OEM Client ID Missing:**

**Symptom:** Validation fails on NAD+GO segment

**Resolution:**
1. Contact shipper for TIN or OEM Client ID
2. Update Shipper > Profile > Comments > TIN or OID
3. Verify format compliance
4. Re-trigger validation

**Gender Missing (for Individuals):**

**Symptom:** "Gender is mandatory for individual" error

**Resolution:**
1. Confirm Client Type = IND in shipper profile
2. Add Gender field data
3. Re-trigger MSG-CLR message (for OEM Client ID registration)
4. Then proceed with manifest validation

**Departure Date Past:**

**Symptom:** Header-level ERROR - EXPIRED status

**Resolution:**
1. Update Master Waybill > Departure Date to future date
2. Verify goods have not already been exported
3. Submit Amendment with corrected date

---

## PHASE 9: AMENDMENT PROCESS

### 9.1 Amendment Prerequisites

**Conditions Required:**
- Original manifest submitted (BCR was SNT)
- MSG-ESMR received with CRN assigned
- Goods not yet exported
- Master not in REVOKED or WITHDRAWN status

**Common Amendment Scenarios:**
1. Add shipments to existing manifest
2. Remove shipments from manifest
3. Correct data errors (dates, quantities, descriptions)
4. Update party information

### 9.2 Data Preparation for Amendment

**Adding Shipments:**
1. Ensure new shipments meet eligibility criteria:
   - Export Country = AU
   - CUS status = CLR or AAC
   - CCN available
   - CT in approved list
2. Assign to same Master Waybill
3. System generates SEQ numbers:
   - Continue sequential numbering from existing manifest
   - Example: If last SEQ was 017, new shipment = 018
4. Set MAN status = RDY
5. Validate (MAN → PAS)

**Removing Shipments:**
1. Identify shipments to exclude
2. Options:
   - **Option A:** Unassign MAWB (Shipment > Master Waybill > Number)
     - SEQ remains but shipment excluded from amendment
     - History retained
   - **Option B:** Change MAN status to exclude
3. System excludes from amendment message
4. **Note:** Line numbers in manifest do NOT re-sequence

**Correcting Data:**
1. Update incorrect fields in shipments or master
2. Trigger validation
3. Ensure MAN = PAS for corrected shipments

### 9.3 Amendment Submission

**User Action:**
1. Navigate to Master Waybill > Brokerage Status > BCR
2. **Change BCR status to AMD (Ready for Amendment)**

**System Actions:**

**Validation:**
1. Run header-level validation
2. Verify all shipments included have MAN = PAS
3. **If validation fails:**
   - BCR → FAI
   - Log errors, block submission
4. **If validation passes:**
   - Proceed to message generation

**Message Generation:**

**Differences from Original:**
1. **BGM Segment:**
   - Message Function Code: **5** (Replace, not 9 Original)
   - Sender Reference: Same URN
   - Sender Reference Version: Increment SRV by 1 (e.g., 002)
2. **RFF+AIZ Segment:**
   - NOW INCLUDED (unlike Original)
   - Consolidation Reference Number: CRN from original response
3. **Line Section:**
   - Include only shipments with MAN = PAS
   - Use existing SEQ numbers (unchanged)
   - New shipments have new SEQ numbers
   - Removed shipments simply absent (line numbers not re-used)

**Header References:**
1. IRN increments (new interchange)
2. SRV increments (e.g., 001 → 002)
3. Same URN (links to original)
4. CRN included in RFF+AIZ

**Transmission:**
1. Message sent to TPS
2. **Post-transmission:**
   - BCR: AMD → SNT
   - MAN (new/changed shipments): PAS → SNT
   - Flow-level BCRSNT updated

### 9.4 Amendment Response Processing

**MSG-ESMR Receipt:**
1. System matches by URN and validates SRV = 002
2. Processes header and line statuses
3. **CRN remains unchanged** (same as original)

**Possible Outcomes:**

**SUCCESS - All CLEAR:**
- Header Status = CLEAR
- All Line Statuses = CLEAR
- BCR → CLR
- MAN → CLR for included shipments

**PARTIAL ERROR:**
- Header Status = CLEAR
- Some Line Statuses = ERROR
- BCR → CLR (overall consolidation approved)
- MAN → ERR for specific shipments (address individually)

**HEADER ERROR:**
- Header Status = ERROR
- BCR → ERR
- Review error in Brokerage Events
- May require another amendment

**REJECTED:**
- Header Status = REJECTED
- BCR → REJ
- Review rejection reason
- Determine if re-amendment possible or if new original needed

### 9.5 Multiple Amendments

**Process:**
1. Each amendment increments SRV
2. Example sequence:
   - Original: SRV = 001, Function Code = 9
   - Amendment 1: SRV = 002, Function Code = 5
   - Amendment 2: SRV = 003, Function Code = 5
   - Amendment 3: SRV = 004, Function Code = 5
3. Always include latest CRN in RFF+AIZ
4. IRN increments for each interchange

**Tracking:**
- All versions logged in Brokerage Events
- SRV in Master Waybill > Reference Numbers tracks current version
- Each MSG-ESMR matched to specific version

---

## PHASE 10: WITHDRAWAL PROCESS

### 10.1 Withdrawal Conditions

**When to Withdraw:**
- Goods will not be exported as manifested
- Consolidation cancelled before departure
- Major errors requiring complete resubmission
- Shipper cancellation
- Cargo diverted to different routing

**Prerequisites:**
- Original manifest submitted (CRN assigned)
- Goods not yet exported
- Manifest not already REVOKED

**Legal Requirement:** Once manifest withdrawn, status cannot be changed; must submit new manifest if goods later exported.

### 10.2 Withdrawal Submission

**User Action:**
1. Navigate to Master Waybill > Brokerage Status > BCR
2. **Change BCR status to WID (Withdrawal Submission)**

**System Actions:**

**Validation:**
1. Verify CRN exists (cannot withdraw un-submitted manifest)
2. Check current status is not REVOKED or WITHDRAWN
3. **If validation fails:**
   - BCR → FAI
   - Log error
4. **If validation passes:**
   - Proceed to message generation

**Message Generation:**

**Key Characteristics:**
1. **BGM Segment:**
   - Message Function Code: **50** (Withdrawal, not 9 or 5)
   - Sender Reference: Same URN
   - Sender Reference Version: Increment SRV by 1
2. **RFF+AIZ Segment:**
   - INCLUDED
   - Consolidation Reference Number: CRN
3. **Line Section:**
   - **NOT INCLUDED** (withdrawal applies to entire consolidation)
   - No CNI, RFF, NAD, or other line segments

**Header Content:**
- All header segments included as in Original/Amendment
- Purpose: Identify which consolidation to withdraw
- No shipment details needed

**Transmission:**
1. Message sent to TPS
2. **Post-transmission:**
   - BCR: WID → SNT (temporarily)
   - Await MSG-ESMR confirmation

### 10.3 Withdrawal Response Processing

**MSG-ESMR Receipt:**
1. System matches by URN and validates SRV
2. Processes header status only (no line section in response)

**Possible Outcomes:**

**SUCCESS:**
- Header Status = WITHDRAWN
- BCR → WID (confirmed)
- All associated shipments: MAN status may be updated
- **Terminal state:** Cannot amend or change

**ERROR:**
- Header Status = ERROR (e.g., already exported)
- BCR → ERR
- Review error description
- May not be able to withdraw

**REJECTED:**
- Header Status = REJECTED
- BCR → REJ
- Review rejection reason
- Contact customs if needed

### 10.4 Post-Withdrawal Actions

**If Goods Still Need to Export:**
1. Prepare new manifest with new consolidation
2. Will receive new CRN
3. Cannot reference previous withdrawn CRN

**Record Keeping:**
1. Withdrawn manifest history retained in SBSS
2. CRN remains in Reference Numbers (historical)
3. Brokerage Events log complete withdrawal process

---

## PHASE 11: MONITORING & REPORTING

### 11.1 Status Monitoring

**Dashboard Views:**
1. **By Master Waybill:**
   - BCR status
   - CRN assignment
   - Departure date
   - Number of associated shipments
   - Overall clearance status
2. **By Shipment:**
   - MAN status
   - SEQ assignment
   - CAN/TRS numbers
   - Inclusion in manifest
   - Individual clearance status

**Full Turbo Queries:**
1. Export shipments by status
2. Pending manifests (BCR = RDY/RFC)
3. Cleared shipments (MAN = CLR)
4. Error shipments (MAN = ERR)
5. Validation failures (MAN/BCR = FAI)

### 11.2 Validation Reports

**Export Consolidation Sub Manifest Validation Report:**

**Use Cases:**
1. Pre-submission review
2. Identify missing data
3. Verify exemption codes
4. Confirm party information
5. Check container/package counts

**Workflow:**
1. Run report with filters
2. Export to spreadsheet
3. Review discrepancies
4. Correct issues in SBSS
5. Re-run report to confirm

### 11.3 Compliance Monitoring

**30-Day Export Window:**
1. Monitor Departure Date on cleared manifests
2. Alert if approaching 30 days post-CRN
3. Coordinate with operations for timely export
4. If exceeded, expect REVOKED status from TPS

**Audit Trail:**
1. All Brokerage Events logged
2. Status change history retained
3. Message versions tracked (SRV)
4. MSG-ESMR processing dates recorded
5. Complete compliance documentation

---

## PROCESS VARIATIONS

### Variation 1: Transhipment (CT = TRS)

**Key Differences:**
1. TRS number used instead of CAN (if CAN not available)
2. Goods already in customs system
3. May have different exemption code logic
4. Movement between Australian ports or to/from vessel

**Process Adjustments:**
1. Ensure TRS number captured in Reference Numbers
2. System uses TRS in RFF+TN segment if CAN empty
3. Validation checks for TRS presence when CT = TRS

### Variation 2: Sea Export (Transport Type = S)

**Key Differences:**
1. Container information required
2. Number of Empty Containers may be > 0
3. Total Number of Containers calculated and included
4. Slot Charter indicator may apply (Cargo Report Type = S)

**Process Adjustments:**
1. User must enter container counts
2. Validation ensures TCN and ECN logical
3. GIS+109 segment may be included in MSG-ESM

### Variation 3: High-Value/Controlled Goods

**Key Differences:**
1. EDN (Export Declaration Number) required
2. Full declaration lodged separately
3. Exemption codes not applicable
4. Permit requirements may apply

**Process Adjustments:**
1. User submits EDN separately (not covered in cargo reporting)
2. EDN linked to manifest if available
3. TPS automatically associates EDN to CRN
4. No exemption code in RFF+TL segment

---

## ERROR REFERENCE GUIDE

### Common Validation Errors

| Error Message | Cause | Resolution |
|---------------|-------|------------|
| "Customs Authority Number is Mandatory" | CAN not in Reference Numbers | Add CAN or TRS, ensure CT correct |
| "Owner Name cannot exceed 35 characters" | Shipper Name too long | Truncate or abbreviate shipper name |
| "Mode of Transport is Mandatory" | Transport Type empty | Set to A or S |
| "Gender is mandatory for individual" | OEM Client ID individual without gender | Add gender field for shipper |
| "Total Number of Packages must be > 0" | All shipment packages = 0 | Verify package counts, add if missing |
| "Number of Empty Containers must be = 0 when Mode of Transport is Air" | ECN > 0 for air | Change ECN to 0 or correct Transport Type |
| "SEQ is not assigned" | MAWB assignment not processed | Verify MAWB assignment from TCS |

### Common TPS Response Errors

| MSG-ESMR Status | Typical Cause | Resolution |
|-------------|---------------|------------|
| ERROR - VALIDATION | Data format or missing field | Review ESMRED details, correct data, amend |
| ERROR - EXPIRED | CAN or permit expired | Obtain new CAN, update, amend |
| ERROR - SUSPENDED | Customs investigation | Contact CBF, provide documentation |
| ERROR - EMBARGOED | Export restrictions | Verify permits, may require special authority |
| REJECTED | Duplicate or unauthorized | Check previous submissions, verify credentials |
| REVOKED | 30-day window exceeded | Cannot amend; withdraw and resubmit if needed |

---

## PROCESS METRICS & KPIs

**Operational Metrics:**
1. **Submission Success Rate:**
   - (SNT manifests / RFC attempts) × 100
   - Target: > 95%
2. **First-Time Clearance Rate:**
   - (CLR on first submission / Total submissions) × 100
   - Target: > 90%
3. **Validation Failure Rate:**
   - (FAI statuses / RDY attempts) × 100
   - Target: < 10%
4. **Amendment Rate:**
   - (Amendment messages / Original messages) × 100
   - Target: < 15%
5. **Average Time to Clear:**
   - Time from SNT to CLR
   - Target: < 4 hours

**Quality Metrics:**
1. Data completeness at submission
2. TIN format compliance
3. Exemption code accuracy
4. Container count accuracy (sea freight)

---

## INTEGRATION TOUCHPOINTS

### SBSS → TCS (Entry Packet)
- **Trigger:** UDB request or CIM status change
- **Data:** RPCID (OEM Client ID), MCRN (concatenated MAWB-CRN)
- **Purpose:** Synchronize customs clearance data back to host system

### TCS → SBSS (MAWB Assignment)
- **Trigger:** Cargo manifesting in TCS
- **Data:** MAWB number, shipment associations
- **Purpose:** Initiate consolidation grouping and SEQ generation

### SBSS → TPS (MSG-ESM Messages)
- **Trigger:** BCR status changes (RFC, AMD, WID)
- **Data:** Complete manifest with header and line details
- **Purpose:** Customs cargo reporting compliance

### TPS → SBSS (MSG-ESMR/CONTRL)
- **Trigger:** TPS processing completion or error
- **Data:** CRN, statuses, error details
- **Purpose:** Clearance authorization and feedback

---

## CONTINGENCY PROCEDURES

### System Outage (SBSS)

**Actions:**
1. Document all pending submissions
2. Use manual workaround if available
3. Track offline using spreadsheet
4. Upon restoration:
   - Bulk status updates via Mass Update
   - Verify all manifests submitted
   - Reconcile CRNs

### System Outage (TPS)

**Actions:**
1. Monitor CBF system status
2. Queue submissions in SBSS (BCR = RFC)
3. Do not change to SNT until confirmation received
4. Upon TPS restoration:
   - Submit queued manifests
   - Monitor response times

### Urgent Export with Validation Failures

**Actions:**
1. Identify critical vs. non-critical errors
2. If critical:
   - Obtain data from shipper urgently
   - Fast-track correction
3. If non-critical but blocking:
   - Contact CBF for manual processing option
   - Use EXCC (contingency) if applicable

---

## BEST PRACTICES

### Data Quality
1. Validate shipper TIN format before download
2. Confirm exemption codes with customer upfront
3. Maintain updated party profiles
4. Regular audits of reference data

### Operational Efficiency
1. Batch process shipments by MAWB
2. Use Mass Update for bulk status changes
3. Run validation reports before submission
4. Monitor 30-day export windows proactively

### Error Prevention
1. Double-check Transport Type before submission
2. Verify container counts for sea freight
3. Ensure SEQ assignment before triggering RFC
4. Review Full Turbo data for completeness

### Communication
1. Clear naming conventions for Master Waybills
2. Document amendment reasons in comments
3. Alert stakeholders of validation failures promptly
4. Maintain customs contact for complex issues

---

## REGULATORY COMPLIANCE

**Customs Border Force Requirements:**
1. All export cargo must be manifested electronically
2. Manifests submitted before cargo removal from Australia
3. Reporting party must hold valid TIN and digital certificate
4. Goods must be exported within 30 days of clearance
5. Amendments required for any changes to cleared manifest
6. Withdrawal required if goods will not be exported
7. Historical records retained for audit purposes

**Carrier Co Responsibilities as Consolidator:**
1. Accurate and complete manifest data
2. Timely submission before departure
3. Amendments for any cargo changes
4. Compliance with CBF exemption code rules
5. Cooperation with customs investigations
6. Maintenance of party identification accuracy

---

## DOCUMENT CONTROL

**Document Type:** Process Flow Document
**Process Name:** Export Cargo Manifest Submission and Response Processing
**Platform:** SBSS (Brokerage Operations Support System)
**Regulatory Context:** Customs Border Force TPS Compliance
**Geographic Scope:** Australia (AU)
**Feature Reference:** 6603297 (Project-A Export BCR Part B-I and II)
**Based On:** 29 completed user stories (Sprint 10.1)
**Status:** Comprehensive operational guide
**Maintenance:** Update as regulations, system capabilities, or processes evolve

---

**END OF PROCESS FLOW DOCUMENT**

title: Project-A / Project-S - Import / Export - Configuring Comment Types (color, im/ex, charges in comment) — Feature Brief
content: # FEATURE BRIEF: CONFIGURABLE COMMENT TYPES FOR DECLARATION CHARGES AND INSTRUCTIONS

## 1. EXECUTIVE SUMMARY

This feature enhances the SBSS platform's comment management system to provide improved visibility of critical instructions and financial information during customs clearance processing. The implementation introduces configurable comment types that can be differentiated by import/export direction, automatically display declaration and commodity charge totals at configurable trigger points, and present critical information in highlighted formats for user attention.

## 2. BUSINESS PROBLEM

### 2.1 Current State Challenges

**Instruction Visibility:** Critical instructions from customs authorities regarding specific importers and customer-specific clearance requirements must be strictly adhered to throughout the clearance process. Currently, these instructions may not be sufficiently prominent for users to notice and act upon consistently.

**Charge Visibility:** Users require immediate visibility of estimated and final charges (declaration values, insurance, freight, commodity-level duties and taxes) at various stages of processing - from initial rating through final clearance. This information aids in:
- Quickly identifying goods and rating shipments
- Correctly applying concessions and exemptions
- Observing customer payment limits
- Verifying charge accuracy before finalization

**Direction-Specific Comments:** The existing comment auto-triggering mechanism (activated via rating hold reasons) does not differentiate between import and export shipments, limiting the ability to provide direction-specific guidance.

### 2.2 Impact on Operations

Without enhanced comment visibility and charge presentation:
- Users may overlook critical customs or customer instructions
- Rating errors may occur due to lack of immediate charge visibility
- Payment limit violations may not be detected until later processing stages
- Import-specific instructions may inadvertently appear on export shipments (and vice versa)
- Users must navigate multiple screens to aggregate charge information

## 3. BUSINESS OBJECTIVES

### 3.1 Primary Goals

1. **Enhanced Instruction Visibility:** Ensure critical instructions are immediately noticeable through visual formatting (bold red fonts) on remark popups
2. **Automated Charge Presentation:** Provide automatic, consolidated charge summaries at configurable business process trigger points
3. **Direction-Specific Comments:** Enable separate comment configurations for import versus export shipments
4. **Operational Efficiency:** Reduce time spent aggregating charge information across multiple declarations
5. **Compliance Support:** Ensure all relevant instructions and charge information are visible during decision-making processes

### 3.2 Success Metrics

- Reduction in payment limit violations detected at later stages
- Decrease in rating corrections required post-clearance
- Improved user satisfaction with charge visibility
- Reduced time to complete rating and clearance activities
- Increased compliance with special customer instructions

## 4. FEATURE SCOPE

### 4.1 In Scope

**Comment Type Configuration:**
- Configuration of comment types with visual formatting attributes (bold, red font)
- Separation of comment auto-triggering by import/export direction
- Maintenance of existing comment auto-trigger functionality

**Declaration Charge Comments:**
- Automatic creation/update of consolidated declaration value comments
- Display of Declaration Total, Insurance (INS), and Freight (FRT) adjustments
- Support for both estimated and final value stages
- Summation across multiple declarations within a shipment

**Commodity-Level Charge Comments:**
- Rolling accumulation of commodity-line charge totals by type
- Automatic creation of consolidated commodity charge comments
- Support for both estimated and final charge stages
- Configurable charge type inclusion (GST, DUTY, WET, EXC, LCT, etc.)

**Trigger Point Configuration:**
- Configurable triggers for estimated value comments (default: RAT Hold Reason PFB)
- Configurable triggers for final value comments (default: CUS status CLR/CMP for Project-A, Shipment Status 04 for Project-S)
- Administrative enable/disable capability for entire feature

**Country-Specific Implementation:**
- Project-A: Declaration values from first declaration only
- Project-S: Combined declaration values across all declarations
- Separate default trigger configurations per country

**Decimal Precision:**
- Standardization of charge amount precision to two decimal places
- Application to all commodity charges and value fields

### 4.2 Out of Scope

- Manual editing of auto-generated charge comments
- Historical recalculation of charges for existing shipments
- Integration of charge comments with external invoicing systems
- Custom formatting options beyond bold red font
- User-level override of trigger points (remains admin-configurable only)

## 5. BUSINESS PROCESS INTEGRATION

### 5.1 Rating Process Enhancement

**Current Process:**
1. Shipment arrives for rating
2. User assigns rating hold reason (e.g., PFB - Pending Further Breakdown)
3. User manually reviews declaration charges across multiple screens
4. User performs rating activities

**Enhanced Process:**
1. Shipment arrives for rating
2. User assigns rating hold reason (e.g., PFB)
3. **System automatically creates/updates estimated charge comments**
4. **User views consolidated charge summary in remark popup**
5. User performs rating activities with immediate charge visibility

### 5.2 Clearance Process Enhancement

**Current Process:**
1. Shipment rated and submitted to customs
2. Customs status changes to CLR (Clear) or CMP (Complete)
3. User manually verifies final charges if needed
4. Clearance processing continues

**Enhanced Process:**
1. Shipment rated and submitted to customs
2. Customs status changes to CLR/CMP (Project-A) or Shipment Status 04 (Project-S)
3. **System automatically creates final charge comments**
4. **User views consolidated final charges in remark popup**
5. Clearance processing continues with charge verification support

### 5.3 Import vs. Export Differentiation

**Current Process:**
- Rating hold reasons trigger same comments regardless of direction
- Users must determine relevance of instructions

**Enhanced Process:**
- System identifies shipment as import or export
- System searches direction-specific lookup table (CUSCMT-I or CUSCMT-X)
- System falls back to generic lookup table (CUS-CMMT) if direction-specific not configured
- Direction-appropriate comments automatically added

## 6. BUSINESS VALUE

### 6.1 Operational Benefits

**Reduced Processing Time:**
- Eliminates manual aggregation of declaration charges
- Reduces navigation between multiple declaration screens
- Immediate visibility of critical information

**Improved Accuracy:**
- Ensures users see current charge totals before making rating decisions
- Reduces errors from manual calculation or oversight
- Provides clear distinction between estimated and final charges

**Enhanced Communication:**
- Standardizes presentation of charges across all users
- Emphasizes critical customer instructions through visual formatting
- Ensures ABCC staff see relevant instructions during compile activities

### 6.2 Compliance Benefits

**Customer Instruction Adherence:**
- Bold red formatting ensures instructions are not overlooked
- Direction-specific comments reduce confusion
- Clear documentation of special handling requirements

**Regulatory Compliance:**
- Accurate charge presentation supports customs declaration accuracy
- Audit trail of estimated vs. final charges
- Standardized decimal precision meets regulatory requirements

### 6.3 Financial Benefits

**Payment Limit Monitoring:**
- Immediate visibility of total charges enables proactive payment limit checks
- Reduces payment disputes from late-discovery of limit violations
- Supports customer communication regarding charge approvals

**Revenue Protection:**
- Ensures all billable charges are visible and accounted for
- Reduces revenue leakage from overlooked charges
- Supports accurate invoicing through clear charge documentation

## 7. COUNTRY-SPECIFIC REQUIREMENTS

### 7.1 Project-A (Australia)

**Declaration Charge Scope:**
- Uses first declaration only for value/insurance/freight calculations
- Rationale: Aligns with Australian customs processing model

**Default Triggers:**
- Estimated Declaration Values: RAT Hold Reason PFB
- Final Declaration Values: CUS = CLR or CUS = CMP
- Estimated Commodity Charges: RAT Hold Reason PFB
- Final Commodity Charges: CUS = CLR or CUS = CMP

**Currency Display:** AUD (Australian Dollars)

### 7.2 Project-S (Singapore)

**Declaration Charge Scope:**
- Combines all declarations for total value/insurance/freight calculations
- Rationale: Supports Singapore's multi-declaration shipment model

**Default Triggers:**
- Estimated Declaration Values: RAT Hold Reason PFB
- Final Declaration Values: Shipment Status 04
- Estimated Commodity Charges: RAT Hold Reason PFB
- Final Commodity Charges: Shipment Status 04

**Currency Display:** SGD (Singapore Dollars)

## 8. CONFIGURATION CAPABILITIES

### 8.1 Administrative Controls

**Feature Enable/Disable:**
- Global toggle to activate/deactivate all charge comment functionality
- Allows phased rollout or temporary suspension if needed

**Trigger Point Configuration:**
- Admin-definable trigger conditions for each comment type
- Separate configuration for estimated vs. final charges
- Separate configuration for declaration vs. commodity charges

**Charge Type Selection:**
- Admin-configurable list of commodity charge types to include
- Examples: GST, DUTY, WET, EXC, LCT
- Enables country-specific tax type relevance

**Import/Export Differentiation:**
- Optional configuration of direction-specific comment lookups
- Fallback to generic lookup if direction-specific not configured
- Maintains backward compatibility with existing implementations

### 8.2 Visual Formatting

**Bold Red Font Application:**
- Configurable at comment type level
- Applicable to specific comment types requiring emphasis
- Renders in remark popup for immediate user attention

## 9. DATA QUALITY REQUIREMENTS

### 9.1 Decimal Precision

All charge amounts and monetary values must be standardized to two decimal place precision:

**Affected Fields:**
- Commodity > Entry Freight
- Commodity > Discount
- Commodity > Value Adjustment
- Commodity > Unit Value
- Commodity > Statistical Value
- Declaration > Charges > Declaration Total
- Declaration > Charges > Declaration Adjustments (INS, FRT)
- All commodity-line charge types

**Rationale:** Ensures compliance with customs regulations and maintains consistency with financial reporting requirements.

### 9.2 Currency Code Display

All charge comments must include the local currency code:
- Prevents ambiguity in multi-currency environments
- Supports audit and verification activities
- Aligns with customs declaration requirements

## 10. DEPENDENCIES AND CONSTRAINTS

### 10.1 System Dependencies

**Existing Comment Infrastructure:**
- Builds upon existing BOS comment type framework
- Extends existing rating hold reason auto-trigger mechanism
- Leverages existing local lookup table structure

**Declaration and Commodity Data:**
- Requires accurate and up-to-date declaration charge data
- Depends on proper configuration of billable flags on charge types
- Relies on correct currency conversion and calculation

### 10.2 Constraints

**Performance Considerations:**
- Rolling calculation of commodity charges must not degrade system performance
- Comment updates must occur within standard transaction processing time
- Multiple declaration summation should not introduce processing delays

**Data Integrity:**
- Comments must reflect current state of charges
- Updates to billable flags must correctly adjust rolling totals
- Removal of charges must properly decrement totals

## 11. IMPLEMENTATION APPROACH

### 11.1 Phased Rollout

**Phase 1: Core Infrastructure**
- Import/export differentiation for existing comments
- New lookup table types (CUSCMT-I, CUSCMT-X)
- Enable/disable configuration

**Phase 2: Declaration Charges**
- Estimated declaration value comments
- Final declaration value comments
- Country-specific calculation logic

**Phase 3: Commodity Charges**
- Rolling total tracking mechanism
- Estimated commodity charge comments
- Final commodity charge comments

**Phase 4: Data Quality**
- Decimal precision standardization
- Visual formatting application
- Testing and validation

### 11.2 Testing Strategy

**Configuration Testing:**
- Verify import/export differentiation
- Validate trigger point customization
- Confirm enable/disable functionality

**Calculation Testing:**
- Verify single-declaration calculations (Project-A)
- Verify multi-declaration summation (Project-S)
- Validate rolling commodity charge totals
- Test billable flag changes and impact

**Integration Testing:**
- Confirm comment creation at configured triggers
- Validate comment updates vs. new comment creation
- Verify currency code display
- Test decimal precision across all fields

**Country-Specific Testing:**
- Project-A: First declaration logic, AUD display
- Project-S: Combined declaration logic, SGD display
- Validate default trigger configurations

## 12. TRAINING AND DOCUMENTATION

### 12.1 User Training Requirements

**Operational Users:**
- Understanding of enhanced remark popup content
- Recognition of bold red formatted critical instructions
- Interpretation of estimated vs. final charge comments
- Awareness of automatic comment creation (no manual action required)

**Administrative Users:**
- Configuration of trigger points
- Setup of import/export specific comment lookups
- Maintenance of charge type inclusion list
- Enable/disable feature controls

### 12.2 Documentation Updates

**User Guides:**
- Updated remark popup screenshots and descriptions
- Explanation of charge comment formats
- Clarification of estimated vs. final charge presentation

**Administrative Guides:**
- Configuration procedures for all lookup tables
- Trigger point customization instructions
- Troubleshooting guidance for comment generation issues

**Process Documentation:**
- Updated rating process flows
- Updated clearance process flows
- Import/export workflow distinctions

## 13. RISKS AND MITIGATION

### 13.1 Identified Risks

| Risk | Impact | Mitigation |
|------|--------|------------|
| Users rely solely on comments instead of source data | High | Training emphasizes comments are summaries; source data remains authoritative |
| Comment proliferation clutters remark popup | Medium | Implement comment lifecycle management; archive old estimated comments when final created |
| Configuration errors lead to incorrect charge displays | High | Comprehensive testing; admin validation tools; clear configuration documentation |
| Performance degradation from rolling calculations | Medium | Optimize calculation logic; implement caching where appropriate |
| Currency conversion errors in multi-declaration scenarios | Medium | Rigorous testing of currency handling; validation against source data |

### 13.2 Rollback Plan

**Feature Disable:**
- Admin can disable entire feature via BCC-ENBL configuration
- Existing comments remain but no new comments auto-generated
- System reverts to pre-enhancement behavior

**Partial Rollback:**
- Individual trigger points can be deconfigured
- Specific charge types can be removed from inclusion list
- Import/export differentiation can revert to generic lookup

## 14. SUCCESS CRITERIA

### 14.1 Functional Acceptance

- [ ] Import shipments trigger direction-specific comments (or fall back to generic)
- [ ] Export shipments trigger direction-specific comments (or fall back to generic)
- [ ] Estimated declaration charge comments created at configured trigger points
- [ ] Final declaration charge comments created at configured trigger points
- [ ] Estimated commodity charge comments created at configured trigger points
- [ ] Final commodity charge comments created at configured trigger points
- [ ] Project-A uses first declaration only for declaration charges
- [ ] Project-S combines all declarations for declaration charges
- [ ] Commodity charge totals accurately reflect billable charge types
- [ ] Billable flag changes correctly update rolling totals
- [ ] All charge amounts display with two decimal place precision
- [ ] Currency codes correctly display in all charge comments
- [ ] Critical instruction comments render in bold red font
- [ ] Feature can be globally enabled/disabled via configuration

### 14.2 Performance Acceptance

- [ ] Comment generation completes within 2 seconds of trigger event
- [ ] Rolling total updates do not degrade charge entry performance
- [ ] Multi-declaration summation completes within 3 seconds
- [ ] No observable impact on remark popup load time

### 14.3 Business Acceptance

- [ ] Users report improved visibility of charge information
- [ ] Users report improved noticeability of critical instructions
- [ ] Rating time per shipment reduced by 10% (target)
- [ ] Payment limit violations detected at earlier stages
- [ ] Admin reports successful configuration of country-specific requirements

---

title: Project-A / Project-S - Import / Export - Configuring Comment Types (color, im/ex, charges in comment) — Technical Specification
content: # TECHNICAL SPECIFICATION: CONFIGURABLE COMMENT TYPES FOR DECLARATION CHARGES AND INSTRUCTIONS

## 1. TECHNICAL OVERVIEW

This specification defines the technical implementation of enhanced comment management in the SBSS platform, including import/export differentiation, automatic charge comment generation, rolling commodity charge calculations, and visual formatting capabilities.

### 1.1 Architecture Context

**Affected Modules:**
- Consolidated Comments (Shipment Comments subsystem)
- Shipment Summary (Customer Supplied References)
- Declaration Charges and Adjustments
- Commodity Charges
- Rating Hold Reason Processing
- Customs Status Processing
- Shipment Status Processing
- Local Lookup Table Management

**Integration Points:**
- Rating Hold Reason assignment workflow
- Customs status transition events
- Shipment status transition events
- Commodity charge creation/modification/deletion events
- Billable flag change events
- Declaration charge calculation engine

### 1.2 Data Model Extensions

**New Reference Types:**
- Shipment > Summary > Customer Supplied References > BCLCTT (BOS Commodity-Line Charge Types Total)

**New Local Lookup Types:**
- CUSCMT-I (Customs Status / Customer Comment - Import)
- CUSCMT-X (Customs Status / Customer Comment - Export)
- BCC-ENBL (BOS Charges Comment - Enable)
- BCC-CLCT (BOS Charges Comment - Commodity-Line Charge Types)
- BCC-DEVT (BOS Charges Comment - Declaration Estimated Values Trigger)
- BCC-DFVT (BOS Charges Comment - Declaration Final Values Trigger)
- BCC-CCET (BOS Charges Comment - Commodity Charges Estimated Trigger)
- BCC-CCFT (BOS Charges Comment - Commodity Charges Final Trigger)

## 2. IMPORT/EXPORT COMMENT DIFFERENTIATION

### 2.1 Direction Detection Logic

**Determination of Shipment Direction:**

```
FUNCTION DetermineShipmentDirection(shipment):
    export_country = shipment.Movement.Export.Country
    import_country = shipment.Movement.Import.Country
    
    IF export_country IS NOT NULL AND export_country != EMPTY:
        IF export_country IN ConfiguredExportCountries:
            RETURN "EXPORT"
    
    IF import_country IS NOT NULL AND import_country != EMPTY:
        IF import_country IN ConfiguredImportCountries:
            RETURN "IMPORT"
    
    RETURN "UNKNOWN"
END FUNCTION
```

**Configured Country Lists:**
- Project-A: Export Country = AU → EXPORT
- Project-A: Import Country = AU → IMPORT
- Project-S: Export Country = SG → EXPORT
- Project-S: Import Country = SG → IMPORT

### 2.2 Comment Lookup Table Selection

**Lookup Table Hierarchy:**

```
FUNCTION SelectCommentLookupType(shipment_direction):
    IF shipment_direction == "IMPORT":
        IF LookupTableExists("CUSCMT-I"):
            RETURN "CUSCMT-I"
        ELSE:
            RETURN "CUS-CMMT"
    
    ELSE IF shipment_direction == "EXPORT":
        IF LookupTableExists("CUSCMT-X"):
            RETURN "CUSCMT-X"
        ELSE:
            RETURN "CUS-CMMT"
    
    ELSE:
        RETURN "CUS-CMMT"
END FUNCTION
```

**Table Existence Check:**
```
FUNCTION LookupTableExists(table_type):
    QUERY Local Lookup Table:
        WHERE Type = table_type
        AND Status = Active
    
    RETURN QueryResultCount > 0
END FUNCTION
```

### 2.3 Comment Auto-Trigger Integration

**Trigger Event: Rating Hold Reason Assignment**

**Original Implementation (Modified):**
```
EVENT OnRatingHoldReasonAssigned(shipment, hold_reason):
    // Determine lookup table based on direction
    direction = DetermineShipmentDirection(shipment)
    lookup_type = SelectCommentLookupType(direction)
    
    // Search for matching lookup codes
    matching_codes = QUERY Local Lookup Table:
        WHERE Type = lookup_type
        AND Code STARTS WITH hold_reason
        AND Status = Active
        ORDER BY Code ASC
    
    IF matching_codes IS EMPTY:
        RETURN // No action required
    
    // Concatenate descriptions
    comment_text = ""
    FOR EACH code IN matching_codes:
        IF comment_text != EMPTY:
            comment_text += " "
        comment_text += code.Description
    
    // Add BOS comment
    ADD Consolidated Comments > Shipment Comments:
        Type = BOS
        Comment = comment_text
        Date = CURRENT_DATE
        User = CURRENT_USER
END EVENT
```

**Example Scenarios:**

**Scenario 1: Import Shipment with CUSCMT-I Configured**
```
INPUT:
    Shipment.Movement.Import.Country = "AU"
    Rating Hold Reason = "IAD"
    
LOOKUP TABLE: CUSCMT-I
    Code: IAD-1, Description: "Import Additional Documents Required"
    Code: IAD-2, Description: "Contact Customer for Invoice"
    
RESULT:
    BOS Comment Created:
        "Import Additional Documents Required Contact Customer for Invoice"
```

**Scenario 2: Export Shipment with CUSCMT-X Not Configured**
```
INPUT:
    Shipment.Movement.Export.Country = "AU"
    Rating Hold Reason = "CER"
    CUSCMT-X Table: Does Not Exist
    
LOOKUP TABLE: CUS-CMMT (Fallback)
    Code: CER-1, Description: "Certificate of Origin Required"
    
RESULT:
    BOS Comment Created:
        "Certificate of Origin Required"
```

**Scenario 3: Import Shipment with No Matching Codes**
```
INPUT:
    Shipment.Movement.Import.Country = "AU"
    Rating Hold Reason = "XXX"
    
LOOKUP TABLE: CUSCMT-I
    No codes starting with "XXX"
    
RESULT:
    No BOS Comment Created
```

### 2.4 Lookup Table Migration

**Data Migration from CUS-CMMT:**

```
MIGRATION SCRIPT:
    // Copy all existing CUS-CMMT codes to new types
    existing_codes = QUERY Local Lookup Table:
        WHERE Type = "CUS-CMMT"
    
    FOR EACH code IN existing_codes:
        // Create CUSCMT-I entry
        INSERT INTO Local Lookup Table:
            Type = "CUSCMT-I"
            Code = code.Code
            Description = code.Description
            Status = code.Status
            [Other Fields] = code.[Other Fields]
        
        // Create CUSCMT-X entry
        INSERT INTO Local Lookup Table:
            Type = "CUSCMT-X"
            Code = code.Code
            Description = code.Description
            Status = code.Status
            [Other Fields] = code.[Other Fields]
    
    // Original CUS-CMMT codes remain for fallback
END SCRIPT
```

## 3. CHARGE COMMENT CONFIGURATION

### 3.1 Feature Enable/Disable Control

**Configuration Check:**

```
FUNCTION IsChargeCommentFeatureEnabled():
    config = QUERY Local Lookup Table:
        WHERE Type = "BCC-ENBL"
        LIMIT 1
    
    IF config IS NULL:
        RETURN FALSE // Feature disabled by default if not configured
    
    RETURN config.Description == "Y"
END FUNCTION
```

**Usage Pattern:**
```
IF IsChargeCommentFeatureEnabled():
    // Execute charge comment logic
ELSE:
    // Skip charge comment processing
END IF
```

### 3.2 Commodity Charge Type Configuration

**Charge Type List Retrieval:**

```
FUNCTION GetConfiguredChargeTypes():
    config = QUERY Local Lookup Table:
        WHERE Type = "BCC-CLCT"
        LIMIT 1
    
    IF config IS NULL:
        RETURN [] // Empty list if not configured
    
    // Description format: "GST,DUTY,WET,EXC,LCT"
    charge_types = SplitString(config.Description, ",")
    
    // Trim whitespace from each type
    FOR EACH type IN charge_types:
        type = Trim(type)
    
    RETURN charge_types
END FUNCTION
```

**Charge Type Inclusion Check:**

```
FUNCTION IsChargeTypeIncluded(charge_type):
    configured_types = GetConfiguredChargeTypes()
    
    RETURN charge_type IN configured_types
END FUNCTION
```

### 3.3 Trigger Point Configuration

**Trigger Point Retrieval Functions:**

```
FUNCTION GetDeclarationEstimatedTrigger():
    config = QUERY Local Lookup Table:
        WHERE Type = "BCC-DEVT"
        LIMIT 1
    
    IF config IS NULL:
        RETURN "RAT_HOLD_PFB" // Default trigger
    
    RETURN config.Description
END FUNCTION

FUNCTION GetDeclarationFinalTrigger():
    config = QUERY Local Lookup Table:
        WHERE Type = "BCC-DFVT"
        LIMIT 1
    
    IF config IS NULL:
        // Country-specific defaults
        IF CURRENT_COUNTRY == "AU":
            RETURN "CUS_CLR,CUS_CMP"
        ELSE IF CURRENT_COUNTRY == "SG":
            RETURN "SHIPMENT_STATUS_04"
    
    RETURN config.Description
END FUNCTION

FUNCTION GetCommodityChargesEstimatedTrigger():
    config = QUERY Local Lookup Table:
        WHERE Type = "BCC-CCET"
        LIMIT 1
    
    IF config IS NULL:
        RETURN "RAT_HOLD_PFB" // Default trigger
    
    RETURN config.Description
END FUNCTION

FUNCTION GetCommodityChargesFinalTrigger():
    config = QUERY Local Lookup Table:
        WHERE Type = "BCC-CCFT"
        LIMIT 1
    
    IF config IS NULL:
        // Country-specific defaults
        IF CURRENT_COUNTRY == "AU":
            RETURN "CUS_CLR,CUS_CMP"
        ELSE IF CURRENT_COUNTRY == "SG":
            RETURN "SHIPMENT_STATUS_04"
    
    RETURN config.Description
END FUNCTION
```

**Trigger Matching Logic:**

```
FUNCTION IsTriggerMatched(trigger_config, event_type, event_value):
    // trigger_config format examples:
    //   "RAT_HOLD_PFB" - Single rating hold reason
    //   "CUS_CLR,CUS_CMP" - Multiple CUS statuses
    //   "SHIPMENT_STATUS_04" - Specific shipment status
    
    IF trigger_config CONTAINS ",":
        // Multiple trigger values
        trigger_values = SplitString(trigger_config, ",")
        FOR EACH trigger IN trigger_values:
            trigger = Trim(trigger)
            IF MatchesSingleTrigger(trigger, event_type, event_value):
                RETURN TRUE
        RETURN FALSE
    ELSE:
        // Single trigger value
        RETURN MatchesSingleTrigger(trigger_config, event_type, event_value)
END FUNCTION

FUNCTION MatchesSingleTrigger(trigger, event_type, event_value):
    IF trigger STARTS WITH "RAT_HOLD_":
        hold_reason = trigger.Replace("RAT_HOLD_", "")
        RETURN event_type == "RATING_HOLD" AND event_value == hold_reason
    
    ELSE IF trigger STARTS WITH "CUS_":
        cus_status = trigger.Replace("CUS_", "")
        RETURN event_type == "CUS_STATUS" AND event_value == cus_status
    
    ELSE IF trigger STARTS WITH "SHIPMENT_STATUS_":
        status = trigger.Replace("SHIPMENT_STATUS_", "")
        RETURN event_type == "SHIPMENT_STATUS" AND event_value == status
    
    RETURN FALSE
END FUNCTION
```

## 4. DECLARATION CHARGE COMMENTS

### 4.1 Declaration Charge Extraction

**Project-A (First Declaration Only):**

```
FUNCTION GetDeclarationCharges_ProjectA(shipment):
    first_declaration = QUERY Declaration:
        WHERE Shipment ID = shipment.ID
        ORDER BY Declaration Sequence ASC
        LIMIT 1
    
    IF first_declaration IS NULL:
        RETURN NULL
    
    RETURN {
        declaration_total: first_declaration.Charges.Declaration_Total,
        insurance: first_declaration.Charges.Declaration_Adjustments.INS,
        freight: first_declaration.Charges.Declaration_Adjustments.FRT,
        currency: first_declaration.Charges.Local_Currency_Code
    }
END FUNCTION
```

**Project-S (All Declarations Combined):**

```
FUNCTION GetDeclarationCharges_ProjectS(shipment):
    declarations = QUERY Declaration:
        WHERE Shipment ID = shipment.ID
        ORDER BY Declaration Sequence ASC
    
    IF declarations IS EMPTY:
        RETURN NULL
    
    total_value = 0
    total_insurance = 0
    total_freight = 0
    currency = NULL
    
    FOR EACH declaration IN declarations:
        total_value += declaration.Charges.Declaration_Total
        total_insurance += declaration.Charges.Declaration_Adjustments.INS
        total_freight += declaration.Charges.Declaration_Adjustments.FRT
        
        IF currency IS NULL:
            currency = declaration.Charges.Local_Currency_Code
    
    RETURN {
        declaration_total: total_value,
        insurance: total_insurance,
        freight: total_freight,
        currency: currency
    }
END FUNCTION
```

**Country-Specific Dispatcher:**

```
FUNCTION GetDeclarationCharges(shipment):
    IF CURRENT_COUNTRY == "AU":
        RETURN GetDeclarationCharges_ProjectA(shipment)
    ELSE IF CURRENT_COUNTRY == "SG":
        RETURN GetDeclarationCharges_ProjectS(shipment)
    ELSE:
        // Default to Project-A behavior
        RETURN GetDeclarationCharges_ProjectA(shipment)
END FUNCTION
```

### 4.2 Declaration Estimated Values Comment

**Comment Creation/Update Logic:**

```
FUNCTION ProcessDeclarationEstimatedComment(shipment, trigger_event):
    // Check feature enabled
    IF NOT IsChargeCommentFeatureEnabled():
        RETURN
    
    // Check trigger match
    trigger_config = GetDeclarationEstimatedTrigger()
    IF NOT IsTriggerMatched(trigger_config, trigger_event.type, trigger_event.value):
        RETURN
    
    // Get charge data
    charges = GetDeclarationCharges(shipment)
    IF charges IS NULL:
        RETURN // No declaration data available
    
    // Format comment text
    comment_text = FormatDeclarationEstimatedComment(charges)
    
    // Check for existing comment
    existing_comment = QUERY Consolidated Comments > Shipment Comments:
        WHERE Shipment ID = shipment.ID
        AND Type = "BOS"
        AND Comment STARTS WITH "DECLARATION ESTIMATED VALUE"
        ORDER BY Date DESC
        LIMIT 1
    
    IF existing_comment IS NOT NULL:
        // Update existing comment
        UPDATE existing_comment:
            Comment = comment_text
            Date = CURRENT_DATE
            User = CURRENT_USER
    ELSE:
        // Add new comment
        INSERT Consolidated Comments > Shipment Comments:
            Shipment ID = shipment.ID
            Type = "BOS"
            Comment = comment_text
            Date = CURRENT_DATE
            User = CURRENT_USER
END FUNCTION
```

**Comment Formatting:**

```
FUNCTION FormatDeclarationEstimatedComment(charges):
    // Format each value to 2 decimal places
    value_str = FormatDecimal(charges.declaration_total, 2)
    insurance_str = FormatDecimal(charges.insurance, 2)
    freight_str = FormatDecimal(charges.freight, 2)
    
    // Build comment string
    comment = "DECLARATION ESTIMATED VALUE " + value_str + " " + charges.currency
    comment += ", INSURANCE " + insurance_str + " " + charges.currency
    comment += ", FREIGHT " + freight_str + " " + charges.currency
    
    RETURN comment
END FUNCTION
```

**Example Output:**
```
"DECLARATION ESTIMATED VALUE 2934.21 AUD, INSURANCE 213.56 AUD, FREIGHT 482.34 AUD"
```

### 4.3 Declaration Final Values Comment

**Comment Creation Logic:**

```
FUNCTION ProcessDeclarationFinalComment(shipment, trigger_event):
    // Check feature enabled
    IF NOT IsChargeCommentFeatureEnabled():
        RETURN
    
    // Check trigger match
    trigger_config = GetDeclarationFinalTrigger()
    IF NOT IsTriggerMatched(trigger_config, trigger_event.type, trigger_event.value):
        RETURN
    
    // Get charge data
    charges = GetDeclarationCharges(shipment)
    IF charges IS NULL:
        RETURN // No declaration data available
    
    // Format comment text
    comment_text = FormatDeclarationFinalComment(charges)
    
    // Always add new comment (never update for final)
    INSERT Consolidated Comments > Shipment Comments:
        Shipment ID = shipment.ID
        Type = "BOS"
        Comment = comment_text
        Date = CURRENT_DATE
        User = CURRENT_USER
END FUNCTION
```

**Comment Formatting:**

```
FUNCTION FormatDeclarationFinalComment(charges):
    // Format each value to 2 decimal places
    value_str = FormatDecimal(charges.declaration_total, 2)
    insurance_str = FormatDecimal(charges.insurance, 2)
    freight_str = FormatDecimal(charges.freight, 2)
    
    // Build comment string
    comment = "DECLARATION FINAL VALUE " + value_str + " " + charges.currency
    comment += ", INSURANCE " + insurance_str + " " + charges.currency
    comment += ", FREIGHT " + freight_str + " " + charges.currency
    
    RETURN comment
END FUNCTION
```

**Example Output:**
```
"DECLARATION FINAL VALUE 3678.45 AUD, INSURANCE 267.89 AUD, FREIGHT 598.12 AUD"
```

### 4.4 Event Integration Points

**Rating Hold Reason Event:**

```
EVENT OnRatingHoldReasonAdded(shipment, hold_reason):
    // Existing comment auto-trigger (modified in Section 2.3)
    ...
    
    // Declaration estimated comment
    trigger_event = {
        type: "RATING_HOLD",
        value: hold_reason
    }
    ProcessDeclarationEstimatedComment(shipment, trigger_event)
END EVENT
```

**CUS Status Change Event:**

```
EVENT OnCUSStatusChanged(shipment, old_status, new_status):
    trigger_event = {
        type: "CUS_STATUS",
        value: new_status
    }
    
    // Declaration final comment
    ProcessDeclarationFinalComment(shipment, trigger_event)
    
    // (Other CUS status processing continues)
END EVENT
```

**Shipment Status Change Event:**

```
EVENT OnShipmentStatusChanged(shipment, old_status, new_status):
    trigger_event = {
        type: "SHIPMENT_STATUS",
        value: new_status
    }
    
    // Declaration final comment
    ProcessDeclarationFinalComment(shipment, trigger_event)
    
    // (Other shipment status processing continues)
END EVENT
```

## 5. COMMODITY CHARGE ROLLING TOTALS

### 5.1 BCLCTT Reference Structure

**Customer Supplied Reference Schema:**

```
REFERENCE TYPE: BCLCTT
    Parent: Shipment > Summary > Customer Supplied References
    Type Code: "BCLCTT"
    Type Description: "BOS Commodity-Line Charge Types Total"
    Number: Not Used
    Comment: Stores rolling totals in format "TYPE1 value1 CURR, TYPE2 value2 CURR, ..."
    Effective Date: Not Used
    Expiration Date: Not Used
```

**Example BCLCTT > Comment Values:**
```
"GST 254.98 AUD"
"GST 254.98 AUD, WET 168.32 AUD"
"GST 254.98 AUD, WET 269.83 AUD, DUTY 421.56 AUD"
```

### 5.2 Charge Type Parsing

**Parse BCLCTT Comment:**

```
FUNCTION ParseBCLCTTComment(comment_text):
    // Returns dictionary of {charge_type: amount}
    IF comment_text IS NULL OR comment_text == "":
        RETURN {}
    
    charge_dict = {}
    
    // Split by comma
    charge_pairs = SplitString(comment_text, ",")
    
    FOR EACH pair IN charge_pairs:
        pair = Trim(pair)
        
        // Expected format: "TYPE amount CURRENCY"
        parts = SplitString(pair, " ")
        
        IF parts.Length >= 3:
            charge_type = parts[0]
            amount = ParseDecimal(parts[1])
            currency = parts[2]
            
            charge_dict[charge_type] = {
                amount: amount,
                currency: currency
            }
    
    RETURN charge_dict
END FUNCTION
```

**Format BCLCTT Comment:**

```
FUNCTION FormatBCLCTTComment(charge_dict):
    // charge_dict format: {charge_type: {amount: value, currency: code}}
    
    IF charge_dict IS EMPTY:
        RETURN ""
    
    comment_parts = []
    
    // Sort by charge type for consistent ordering
    sorted_types = SortKeys(charge_dict)
    
    FOR EACH charge_type IN sorted_types:
        charge_data = charge_dict[charge_type]
        
        // Format: "TYPE amount CURRENCY"
        amount_str = FormatDecimal(charge_data.amount, 2)
        part = charge_type + " " + amount_str + " " + charge_data.currency
        
        comment_parts.Append(part)
    
    // Join with comma and space
    RETURN JoinStrings(comment_parts, ", ")
END FUNCTION
```

### 5.3 Rolling Total Update Logic

**Add Billable Charge:**

```
FUNCTION AddBillableCharge(shipment, charge_type, amount, currency):
    // Check if charge type is configured for inclusion
    IF NOT IsChargeTypeIncluded(charge_type):
        RETURN // Skip this charge type
    
    // Get or create BCLCTT reference
    bclctt = QUERY Shipment > Summary > Customer Supplied References:
        WHERE Shipment ID = shipment.ID
        AND Type = "BCLCTT"
        LIMIT 1
    
    IF bclctt IS NULL:
        // Create new BCLCTT
        bclctt = INSERT Shipment > Summary > Customer Supplied References:
            Shipment ID = shipment.ID
            Type = "BCLCTT"
            Comment = ""
    
    // Parse existing totals
    charge_dict = ParseBCLCTTComment(bclctt.Comment)
    
    // Add or update charge type
    IF charge_type IN charge_dict:
        // Increment existing total
        charge_dict[charge_type].amount += amount
    ELSE:
        // Add new charge type
        charge_dict[charge_type] = {
            amount: amount,
            currency: currency
        }
    
    // Format and update BCLCTT comment
    bclctt.Comment = FormatBCLCTTComment(charge_dict)
    
    UPDATE bclctt
END FUNCTION
```

**Remove Billable Charge:**

```
FUNCTION RemoveBillableCharge(shipment, charge_type, amount):
    // Check if charge type is configured for inclusion
    IF NOT IsChargeTypeIncluded(charge_type):
        RETURN // Skip this charge type
    
    // Get BCLCTT reference
    bclctt = QUERY Shipment > Summary > Customer Supplied References:
        WHERE Shipment ID = shipment.ID
        AND Type = "BCLCTT"
        LIMIT 1
    
    IF bclctt IS NULL:
        RETURN // Nothing to update
    
    // Parse existing totals
    charge_dict = ParseBCLCTTComment(bclctt.Comment)
    
    // Subtract from charge type
    IF charge_type IN charge_dict:
        charge_dict[charge_type].amount -= amount
        
        // Remove charge type if total reaches zero
        IF charge_dict[charge_type].amount <= 0.001: // Account for floating point
            DELETE charge_dict[charge_type]
    
    // Update or remove BCLCTT
    IF charge_dict IS EMPTY:
        DELETE bclctt
    ELSE:
        bclctt.Comment = FormatBCLCTTComment(charge_dict)
        UPDATE bclctt
END FUNCTION
```

### 5.4 Commodity Charge Event Integration

**Commodity Charge Created:**

```
EVENT OnCommodityChargeCreated(commodity, charge):
    IF charge.Billable == TRUE:
        shipment = GetShipmentForCommodity(commodity)
        AddBillableCharge(
            shipment,
            charge.Type,
            charge.Amount,
            shipment.Declaration.Charges.Local_Currency_Code
        )
END EVENT
```

**Commodity Charge Billable Flag Changed:**

```
EVENT OnCommodityChargeBillableFlagChanged(commodity, charge, old_billable, new_billable):
    shipment = GetShipmentForCommodity(commodity)
    
    IF old_billable == FALSE AND new_billable == TRUE:
        // Newly billable - add to total
        AddBillableCharge(
            shipment,
            charge.Type,
            charge.Amount,
            shipment.Declaration.Charges.Local_Currency_Code
        )
    
    ELSE IF old_billable == TRUE AND new_billable == FALSE:
        // No longer billable - subtract from total
        RemoveBillableCharge(
            shipment,
            charge.Type,
            charge.Amount
        )
END EVENT
```

**Commodity Charge Amount Changed:**

```
EVENT OnCommodityChargeAmountChanged(commodity, charge, old_amount, new_amount):
    IF charge.Billable == TRUE:
        shipment = GetShipmentForCommodity(commodity)
        
        // Remove old amount
        RemoveBillableCharge(shipment, charge.Type, old_amount)
        
        // Add new amount
        AddBillableCharge(
            shipment,
            charge.Type,
            new_amount,
            shipment.Declaration.Charges.Local_Currency_Code
        )
END EVENT
```

**Commodity Charge Deleted:**

```
EVENT OnCommodityChargeDeleted(commodity, charge):
    IF charge.Billable == TRUE:
        shipment = GetShipmentForCommodity(commodity)
        RemoveBillableCharge(shipment, charge.Type, charge.Amount)
END EVENT
```

## 6. COMMODITY CHARGE COMMENTS

### 6.1 BCLCTT Extraction

**Get Current Commodity Charges:**

```
FUNCTION GetCommodityCharges(shipment):
    bclctt = QUERY Shipment > Summary > Customer Supplied References:
        WHERE Shipment ID = shipment.ID
        AND Type = "BCLCTT"
        LIMIT 1
    
    IF bclctt IS NULL:
        RETURN NULL
    
    RETURN bclctt.Comment
END FUNCTION
```

### 6.2 Commodity Estimated Charges Comment

**Comment Creation Logic:**

```
FUNCTION ProcessCommodityEstimatedComment(shipment, trigger_event):
    // Check feature enabled
    IF NOT IsChargeCommentFeatureEnabled():
        RETURN
    
    // Check trigger match
    trigger_config = GetCommodityChargesEstimatedTrigger()
    IF NOT IsTriggerMatched(trigger_config, trigger_event.type, trigger_event.value):
        RETURN
    
    // Get BCLCTT data
    bclctt_comment = GetCommodityCharges(shipment)
    IF bclctt_comment IS NULL OR bclctt_comment == "":
        RETURN // No commodity charges available
    
    // Format comment text
    comment_text = "SHIPMENT ESTIMATED COMMODITY CHARGES " + bclctt_comment
    
    // Always add new comment
    INSERT Consolidated Comments > Shipment Comments:
        Shipment ID = shipment.ID
        Type = "BOS"
        Comment = comment_text
        Date = CURRENT_DATE
        User = CURRENT_USER
END FUNCTION
```

**Example Output:**
```
"SHIPMENT ESTIMATED COMMODITY CHARGES GST 3678.45 AUD, DUTY 267.89 AUD, WET 598.12 AUD"
```

### 6.3 Commodity Final Charges Comment

**Comment Creation Logic:**

```
FUNCTION ProcessCommodityFinalComment(shipment, trigger_event):
    // Check feature enabled
    IF NOT IsChargeCommentFeatureEnabled():
        RETURN
    
    // Check trigger match
    trigger_config = GetCommodityChargesFinalTrigger()
    IF NOT IsTriggerMatched(trigger_config, trigger_event.type, trigger_event.value):
        RETURN
    
    // Get BCLCTT data
    bclctt_comment = GetCommodityCharges(shipment)
    IF bclctt_comment IS NULL OR bclctt_comment == "":
        RETURN // No commodity charges available
    
    // Format comment text
    comment_text = "SHIPMENT FINAL COMMODITY CHARGES " + bclctt_comment
    
    // Always add new comment
    INSERT Consolidated Comments > Shipment Comments:
        Shipment ID = shipment.ID
        Type = "BOS"
        Comment = comment_text
        Date = CURRENT_DATE
        User = CURRENT_USER
END FUNCTION
```

**Example Output:**
```
"SHIPMENT FINAL COMMODITY CHARGES GST 3678.45 SGD, DUTY 267.89 SGD, WET 598.12 SGD"
```

### 6.4 Event Integration Points

**Rating Hold Reason Event (Extended):**

```
EVENT OnRatingHoldReasonAdded(shipment, hold_reason):
    // Existing comment auto-trigger (Section 2.3)
    ...
    
    // Declaration estimated comment (Section 4.4)
    ...
    
    // Commodity estimated comment
    trigger_event = {
        type: "RATING_HOLD",
        value: hold_reason
    }
    ProcessCommodityEstimatedComment(shipment, trigger_event)
END EVENT
```

**CUS Status Change Event (Extended):**

```
EVENT OnCUSStatusChanged(shipment, old_status, new_status):
    trigger_event = {
        type: "CUS_STATUS",
        value: new_status
    }
    
    // Declaration final comment (Section 4.4)
    ...
    
    // Commodity final comment
    ProcessCommodityFinalComment(shipment, trigger_event)
END EVENT
```

**Shipment Status Change Event (Extended):**

```
EVENT OnShipmentStatusChanged(shipment, old_status, new_status):
    trigger_event = {
        type: "SHIPMENT_STATUS",
        value: new_status
    }
    
    // Declaration final comment (Section 4.4)
    ...
    
    // Commodity final comment
    ProcessCommodityFinalComment(shipment, trigger_event)
END EVENT
```

## 7. DECIMAL PRECISION STANDARDIZATION

### 7.1 Affected Fields

**Database Schema Updates:**

All monetary fields must be configured with DECIMAL(18,2) precision:

```
ALTER TABLE Commodity:
    Entry_Freight DECIMAL(18,2)
    Discount DECIMAL(18,2)
    Value_Adjustment DECIMAL(18,2)
    Unit_Value DECIMAL(18,2)
    Statistical_Value DECIMAL(18,2)

ALTER TABLE Declaration_Charges:
    Declaration_Total DECIMAL(18,2)

ALTER TABLE Declaration_Adjustments:
    INS DECIMAL(18,2)
    FRT DECIMAL(18,2)

ALTER TABLE Commodity_Charges:
    Amount DECIMAL(18,2)
```

### 7.2 Display Formatting

**Universal Decimal Formatter:**

```
FUNCTION FormatDecimal(value, precision):
    IF value IS NULL:
        RETURN "0.00"
    
    // Round to specified precision
    rounded = ROUND(value, precision)
    
    // Format with leading zeros and trailing zeros
    formatted = FORMAT(rounded, "0." + REPEAT("0", precision))
    
    RETURN formatted
END FUNCTION
```

**Examples:**
```
FormatDecimal(1234.5, 2)      → "1234.50"
FormatDecimal(0.1, 2)         → "0.10"
FormatDecimal(999.999, 2)     → "1000.00" (rounded)
FormatDecimal(NULL, 2)        → "0.00"
```

### 7.3 Input Validation

**Charge Amount Input Validation:**

```
FUNCTION ValidateChargeAmount(input_value):
    // Convert to decimal
    decimal_value = ParseDecimal(input_value)
    
    IF decimal_value IS NULL:
        RETURN ERROR "Invalid numeric value"
    
    // Check precision (max 2 decimal places)
    decimal_part = decimal_value - FLOOR(decimal_value)
    decimal_places = CountDecimalPlaces(decimal_part)
    
    IF decimal_places > 2:
        RETURN ERROR "Charge amounts must have maximum 2 decimal places"
    
    // Check range (prevent overflow)
    IF decimal_value < 0:
        RETURN ERROR "Charge amounts cannot be negative"
    
    IF decimal_value > 999999999999.99:
        RETURN ERROR "Charge amount exceeds maximum allowed value"
    
    RETURN OK
END FUNCTION
```

### 7.4 Calculation Precision

**Intermediate Calculation Handling:**

```
FUNCTION CalculateChargeTotal(charge_list):
    // Use extended precision during calculation
    total = DECIMAL(28,10) 0.0
    
    FOR EACH charge IN charge_list:
        total += CAST(charge.Amount AS DECIMAL(28,10))
    
    // Round to 2 decimal places for final result
    final_total = ROUND(total, 2)
    
    RETURN final_total
END FUNCTION
```

**Currency Conversion Precision:**

```
FUNCTION ConvertCurrency(amount, from_currency, to_currency, exchange_rate):
    // Use extended precision during conversion
    converted = CAST(amount AS DECIMAL(28,10)) * CAST(exchange_rate AS DECIMAL(28,10))
    
    // Round to 2 decimal places
    final_amount = ROUND(converted, 2)
    
    RETURN final_amount
END FUNCTION
```

## 8. VISUAL FORMATTING

### 8.1 Comment Type Configuration

**Enhanced Comment Type Schema:**

```
COMMENT TYPE CONFIGURATION:
    Type Code: "BOS"
    Description: "Brokerage Operations Support"
    Bold: TRUE (configurable)
    Font Color: Red (configurable - hex #FF0000)
    Font Size: Standard (inherits from system)
    Background Color: None (transparent)
```

### 8.2 Remark Popup Rendering

**HTML Rendering Logic:**

```
FUNCTION RenderCommentInRemarkPopup(comment):
    comment_type_config = GetCommentTypeConfiguration(comment.Type)
    
    html = "<div class='comment-entry'>"
    
    // Apply visual formatting based on configuration
    style_attributes = []
    
    IF comment_type_config.Bold == TRUE:
        style_attributes.Append("font-weight: bold")
    
    IF comment_type_config.Font_Color IS NOT NULL:
        style_attributes.Append("color: " + comment_type_config.Font_Color)
    
    IF comment_type_config.Font_Size IS NOT NULL:
        style_attributes.Append("font-size: " + comment_type_config.Font_Size)
    
    IF comment_type_config.Background_Color IS NOT NULL:
        style_attributes.Append("background-color: " + comment_type_config.Background_Color)
    
    // Combine style attributes
    IF style_attributes IS NOT EMPTY:
        style = "style='" + JoinStrings(style_attributes, "; ") + "'"
    ELSE:
        style = ""
    
    // Render comment
    html += "<span " + style + ">"
    html += EscapeHTML(comment.Comment)
    html += "</span>"
    
    html += "</div>"
    
    RETURN html
END FUNCTION
```

**Remark Popup Assembly:**

```
FUNCTION GenerateRemarkPopup(shipment):
    comments = QUERY Consolidated Comments > Shipment Comments:
        WHERE Shipment ID = shipment.ID
        ORDER BY Date DESC, Comment Type
    
    html = "<div class='remark-popup'>"
    html += "<h3>Shipment Comments</h3>"
    
    FOR EACH comment IN comments:
        html += RenderCommentInRemarkPopup(comment)
    
    html += "</div>"
    
    RETURN html
END FUNCTION
```

### 8.3 CSS Styling

**Stylesheet Definitions:**

```css
.remark-popup {
    max-width: 600px;
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #ccc;
    padding: 10px;
    background-color: #fff;
}

.remark-popup h3 {
    margin-top: 0;
    border-bottom: 1px solid #ddd;
    padding-bottom: 5px;
}

.comment-entry {
    margin-bottom: 8px;
    padding: 5px;
    border-left: 3px solid transparent;
}

.comment-entry span {
    display: block;
    line-height: 1.4;
}

/* BOS comment type with bold red formatting */
.comment-entry.type-bos {
    border-left-color: #ff0000;
}
```

## 9. DATA VALIDATION AND INTEGRITY

### 9.1 BCLCTT Integrity Checks

**Validation on BCLCTT Update:**

```
FUNCTION ValidateBCLCTTIntegrity(shipment):
    // Get BCLCTT reference
    bclctt = QUERY Shipment > Summary > Customer Supplied References:
        WHERE Shipment ID = shipment.ID
        AND Type = "BCLCTT"
        LIMIT 1
    
    IF bclctt IS NULL:
        RETURN OK // No BCLCTT to validate
    
    // Parse BCLCTT comment
    charge_dict = ParseBCLCTTComment(bclctt.Comment)
    
    // Recalculate totals from commodity charges
    actual_totals = {}
    
    commodities = QUERY Commodity:
        WHERE Declaration.Shipment ID = shipment.ID
    
    FOR EACH commodity IN commodities:
        charges = QUERY Commodity Charges:
            WHERE Commodity ID = commodity.ID
            AND Billable = TRUE
        
        FOR EACH charge IN charges:
            IF IsChargeTypeIncluded(charge.Type):
                IF charge.Type NOT IN actual_totals:
                    actual_totals[charge.Type] = 0
                actual_totals[charge.Type] += charge.Amount
    
    // Compare BCLCTT totals with actual totals
    discrepancies = []
    
    FOR EACH charge_type IN charge_dict.Keys:
        expected = charge_dict[charge_type].amount
        actual = actual_totals.GetOrDefault(charge_type, 0)
        
        IF ABS(expected - actual) > 0.01: // Allow 1 cent tolerance
            discrepancies.Append({
                charge_type: charge_type,
                expected: expected,
                actual: actual
            })
    
    FOR EACH charge_type IN actual_totals.Keys:
        IF charge_type NOT IN charge_dict:
            discrepancies.Append({
                charge_type: charge_type,
                expected: 0,
                actual: actual_totals[charge_type]
            })
    
    IF discrepancies IS NOT EMPTY:
        RETURN ERROR "BCLCTT integrity check failed: " + FormatDiscrepancies(discrepancies)
    
    RETURN OK
END FUNCTION
```

**Integrity Check Trigger:**

```
SCHEDULE ValidateBCLCTTIntegrityBatch():
    // Run nightly for all active shipments
    shipments = QUERY Shipment:
        WHERE Status IN (Active Statuses)
        AND Modified Date >= CURRENT_DATE - 7 days
    
    errors = []
    
    FOR EACH shipment IN shipments:
        result = ValidateBCLCTTIntegrity(shipment)
        IF result != OK:
            errors.Append({
                shipment_id: shipment.ID,
                error: result
            })
    
    IF errors IS NOT EMPTY:
        GenerateIntegrityReport(errors)
        SendAlertToAdministrators(errors)
END SCHEDULE
```

### 9.2 Comment Duplication Prevention

**Prevent Duplicate Estimated Comments:**

```
FUNCTION PreventDuplicateEstimatedComment(shipment, comment_prefix):
    // Check for existing estimated comment created today
    existing = QUERY Consolidated Comments > Shipment Comments:
        WHERE Shipment ID = shipment.ID
        AND Type = "BOS"
        AND Comment STARTS WITH comment_prefix
        AND Date = CURRENT_DATE
        LIMIT 1
    
    IF existing IS NOT NULL:
        RETURN TRUE // Duplicate detected
    
    RETURN FALSE
END FUNCTION
```

**Usage in Comment Processing:**

```
FUNCTION ProcessDeclarationEstimatedComment_Enhanced(shipment, trigger_event):
    // (Previous validation checks...)
    
    // Check for duplicate
    IF PreventDuplicateEstimatedComment(shipment, "DECLARATION ESTIMATED VALUE"):
        RETURN // Skip to prevent duplicate
    
    // (Continue with comment creation...)
END FUNCTION
```

### 9.3 Currency Consistency Validation

**Validate Currency Across Charges:**

```
FUNCTION ValidateCurrencyConsistency(shipment):
    // Get local currency from first declaration
    first_declaration = QUERY Declaration:
        WHERE Shipment ID = shipment.ID
        ORDER BY Declaration Sequence ASC
        LIMIT 1
    
    IF first_declaration IS NULL:
        RETURN OK // No declarations to validate
    
    expected_currency = first_declaration.Charges.Local_Currency_Code
    
    // Check all declarations have same currency
    all_declarations = QUERY Declaration:
        WHERE Shipment ID = shipment.ID
    
    FOR EACH declaration IN all_declarations:
        IF declaration.Charges.Local_Currency_Code != expected_currency:
            RETURN ERROR "Currency mismatch: Expected " + expected_currency + 
                         ", found " + declaration.Charges.Local_Currency_Code
    
    // Check BCLCTT uses same currency
    bclctt = QUERY Shipment > Summary > Customer Supplied References:
        WHERE Shipment ID = shipment.ID
        AND Type = "BCLCTT"
        LIMIT 1
    
    IF bclctt IS NOT NULL:
        charge_dict = ParseBCLCTTComment(bclctt.Comment)
        FOR EACH charge_type IN charge_dict.Keys:
            IF charge_dict[charge_type].currency != expected_currency:
                RETURN ERROR "BCLCTT currency mismatch: Expected " + expected_currency +
                             ", found " + charge_dict[charge_type].currency
    
    RETURN OK
END FUNCTION
```

## 10. PERFORMANCE OPTIMIZATION

### 10.1 BCLCTT Update Batching

**Batch Multiple Charge Updates:**

```
TRANSACTION BatchCommodityChargeUpdates(commodity, charge_updates):
    // Disable BCLCTT update triggers
    DisableBCLCTTTriggers()
    
    // Apply all charge updates
    FOR EACH update IN charge_updates:
        ApplyCommodityChargeUpdate(commodity, update)
    
    // Re-enable triggers
    EnableBCLCTTTriggers()
    
    // Perform single BCLCTT recalculation
    shipment = GetShipmentForCommodity(commodity)
    RecalculateBCLCTT(shipment)
    
    COMMIT TRANSACTION
END TRANSACTION
```

**Full BCLCTT Recalculation:**

```
FUNCTION RecalculateBCLCTT(shipment):
    // Delete existing BCLCTT
    DELETE Shipment > Summary > Customer Supplied References:
        WHERE Shipment ID = shipment.ID
        AND Type = "BCLCTT"
    
    // Rebuild from commodity charges
    commodities = QUERY Commodity:
        WHERE Declaration.Shipment ID = shipment.ID
    
    FOR EACH commodity IN commodities:
        charges = QUERY Commodity Charges:
            WHERE Commodity ID = commodity.ID
            AND Billable = TRUE
        
        FOR EACH charge IN charges:
            IF IsChargeTypeIncluded(charge.Type):
                AddBillableCharge(
                    shipment,
                    charge.Type,
                    charge.Amount,
                    shipment.Declaration.Charges.Local_Currency_Code
                )
END FUNCTION
```

### 10.2 Comment Query Optimization

**Indexed Queries:**

```
CREATE INDEX idx_shipment_comments_type_date 
    ON Consolidated_Comments_Shipment_Comments (Shipment_ID, Type, Date DESC)

CREATE INDEX idx_customer_supplied_ref_type 
    ON Shipment_Summary_Customer_Supplied_References (Shipment_ID, Type)
```

**Optimized Comment Retrieval:**

```
FUNCTION GetRecentBOSComments(shipment, limit):
    // Leverage index for fast retrieval
    comments = QUERY Consolidated Comments > Shipment Comments:
        WHERE Shipment ID = shipment.ID
        AND Type = "BOS"
        ORDER BY Date DESC
        LIMIT limit
    
    RETURN comments
END FUNCTION
```

### 10.3 Trigger Event Optimization

**Debounce Rapid Status Changes:**

```
FUNCTION DebounceStatusChange(shipment, status_type, new_status, debounce_ms):
    // Store pending status change
    pending_key = shipment.ID + "_" + status_type
    
    IF pending_changes.Contains(pending_key):
        // Cancel previous pending change
        CancelPendingChange(pending_key)
    
    // Schedule new pending change
    pending_changes[pending_key] = ScheduleDelayed(debounce_ms, FUNCTION():
        ProcessStatusChangeTriggers(shipment, status_type, new_status)
        pending_changes.Remove(pending_key)
    END FUNCTION)
END FUNCTION
```

## 11. ERROR HANDLING

### 11.1 Graceful Degradation

**Comment Creation Error Handling:**

```
FUNCTION SafeProcessComment(shipment, processor_function):
    TRY:
        processor_function(shipment)
    CATCH error:
        // Log error but don't block transaction
        LogError({
            shipment_id: shipment.ID,
            processor: processor_function.Name,
            error: error.Message,
            timestamp: CURRENT_TIMESTAMP
        })
        
        // Add system comment indicating issue
        INSERT Consolidated Comments > Shipment Comments:
            Shipment ID = shipment.ID
            Type = "SYSTEM"
            Comment = "Error generating automatic comment: " + error.Message
            Date = CURRENT_DATE
            User = "SYSTEM"
    END TRY
END FUNCTION
```

**Usage:**

```
EVENT OnRatingHoldReasonAdded(shipment, hold_reason):
    // Wrap each comment processor in error handler
    SafeProcessComment(shipment, FUNCTION():
        ProcessDirectionSpecificComment(shipment, hold_reason)
    END FUNCTION)
    
    SafeProcessComment(shipment, FUNCTION():
        trigger_event = {type: "RATING_HOLD", value: hold_reason}
        ProcessDeclarationEstimatedComment(shipment, trigger_event)
    END FUNCTION)
    
    SafeProcessComment(shipment, FUNCTION():
        trigger_event = {type: "RATING_HOLD", value: hold_reason}
        ProcessCommodityEstimatedComment(shipment, trigger_event)
    END FUNCTION)
END EVENT
```

### 11.2 Data Validation Error Reporting

**Validation Error Aggregation:**

```
FUNCTION AggregateValidationErrors(shipment):
    errors = []
    
    // Validate currency consistency
    currency_result = ValidateCurrencyConsistency(shipment)
    IF currency_result != OK:
        errors.Append(currency_result)
    
    // Validate BCLCTT integrity
    bclctt_result = ValidateBCLCTTIntegrity(shipment)
    IF bclctt_result != OK:
        errors.Append(bclctt_result)
    
    // Validate decimal precision
    precision_result = ValidateDecimalPrecision(shipment)
    IF precision_result != OK:
        errors.Append(precision_result)
    
    RETURN errors
END FUNCTION
```

**User-Facing Error Display:**

```
FUNCTION DisplayValidationErrors(shipment):
    errors = AggregateValidationErrors(shipment)
    
    IF errors IS EMPTY:
        RETURN "No validation errors"
    
    error_html = "<div class='validation-errors'>"
    error_html += "<h4>Charge Comment Validation Errors:</h4>"
    error_html += "<ul>"
    
    FOR EACH error IN errors:
        error_html += "<li>" + EscapeHTML(error) + "</li>"
    
    error_html += "</ul>"
    error_html += "</div>"
    
    RETURN error_html
END FUNCTION
```

## 12. MIGRATION AND DEPLOYMENT

### 12.1 Database Migration Script

**Schema Changes:**

```sql
-- Create new lookup table types
INSERT INTO Local_Lookup_Table (Type, Description, Status)
VALUES 
    ('CUSCMT-I', 'Customs Status / Customer Comment (Import)', 'Active'),
    ('CUSCMT-X', 'Customs Status / Customer Comment (Export)', 'Active'),
    ('BCC-ENBL', 'BOS Charges Comment (Enable)', 'Active'),
    ('BCC-CLCT', 'BOS Charges Comment (Commodity-Line Charge Types)', 'Active'),
    ('BCC-DEVT', 'BOS Charges Comment (Declaration Estimated Values Trigger)', 'Active'),
    ('BCC-DFVT', 'BOS Charges Comment (Declaration Final Values Trigger)', 'Active'),
    ('BCC-CCET', 'BOS Charges Comment (Commodity Charges Estimated Trigger)', 'Active'),
    ('BCC-CCFT', 'BOS Charges Comment (Commodity Charges Final Trigger)', 'Active');

-- Create default configuration values
INSERT INTO Local_Lookup_Table (Type, Code, Description)
VALUES
    ('BCC-ENBL', 'DEFAULT', 'N'), -- Disabled by default
    ('BCC-CLCT', 'DEFAULT', 'GST,DUTY,WET,EXC,LCT');

-- Country-specific defaults for Project-A
INSERT INTO Local_Lookup_Table (Type, Code, Description, Country)
VALUES
    ('BCC-DEVT', 'AU-DEFAULT', 'RAT_HOLD_PFB', 'AU'),
    ('BCC-DFVT', 'AU-DEFAULT', 'CUS_CLR,CUS_CMP', 'AU'),
    ('BCC-CCET', 'AU-DEFAULT', 'RAT_HOLD_PFB', 'AU'),
    ('BCC-CCFT', 'AU-DEFAULT', 'CUS_CLR,CUS_CMP', 'AU');

-- Country-specific defaults for Project-S
INSERT INTO Local_Lookup_Table (Type, Code, Description, Country)
VALUES
    ('BCC-DEVT', 'SG-DEFAULT', 'RAT_HOLD_PFB', 'SG'),
    ('BCC-DFVT', 'SG-DEFAULT', 'SHIPMENT_STATUS_04', 'SG'),
    ('BCC-CCET', 'SG-DEFAULT', 'RAT_HOLD_PFB', 'SG'),
    ('BCC-CCFT', 'SG-DEFAULT', 'SHIPMENT_STATUS_04', 'SG');

-- Migrate existing CUS-CMMT codes
INSERT INTO Local_Lookup_Table (Type, Code, Description, Status)
SELECT 'CUSCMT-I', Code, Description, Status
FROM Local_Lookup_Table
WHERE Type = 'CUS-CMMT';

INSERT INTO Local_Lookup_Table (Type, Code, Description, Status)
SELECT 'CUSCMT-X', Code, Description, Status
FROM Local_Lookup_Table
WHERE Type = 'CUS-CMMT';

-- Add BCLCTT reference type
INSERT INTO Shipment_Reference_Types (Type_Code, Description, Parent_Type)
VALUES ('BCLCTT', 'BOS Commodity-Line Charge Types Total', 'Customer Supplied References');

-- Update decimal precision on charge fields
ALTER TABLE Commodity 
    ALTER COLUMN Entry_Freight DECIMAL(18,2),
    ALTER COLUMN Discount DECIMAL(18,2),
    ALTER COLUMN Value_Adjustment DECIMAL(18,2),
    ALTER COLUMN Unit_Value DECIMAL(18,2),
    ALTER COLUMN Statistical_Value DECIMAL(18,2);

ALTER TABLE Declaration_Charges
    ALTER COLUMN Declaration_Total DECIMAL(18,2);

ALTER TABLE Declaration_Adjustments
    ALTER COLUMN INS DECIMAL(18,2),
    ALTER COLUMN FRT DECIMAL(18,2);

ALTER TABLE Commodity_Charges
    ALTER COLUMN Amount DECIMAL(18,2);

-- Create indexes for performance
CREATE INDEX idx_shipment_comments_type_date 
    ON Consolidated_Comments_Shipment_Comments (Shipment_ID, Type, Date DESC);

CREATE INDEX idx_customer_supplied_ref_type 
    ON Shipment_Summary_Customer_Supplied_References (Shipment_ID, Type);

CREATE INDEX idx_commodity_charges_billable
    ON Commodity_Charges (Commodity_ID, Billable, Type);
```

### 12.2 Deployment Checklist

**Pre-Deployment:**
- [ ] Backup all Local Lookup Tables
- [ ] Backup Shipment Comments tables
- [ ] Backup Customer Supplied References tables
- [ ] Document current CUS-CMMT configurations
- [ ] Prepare rollback scripts

**Deployment Steps:**
1. Execute database migration script
2. Deploy updated application code
3. Verify lookup table creation
4. Verify decimal precision updates
5. Test comment auto-trigger for import shipment
6. Test comment auto-trigger for export shipment
7. Test BCLCTT creation and updates
8. Test declaration charge comments
9. Test commodity charge comments
10. Verify visual formatting in remark popup

**Post-Deployment:**
- [ ] Enable feature via BCC-ENBL (set to "Y")
- [ ] Monitor error logs for issues
- [ ] Validate BCLCTT integrity across sample shipments
- [ ] Confirm comment generation at all trigger points
- [ ] Review user feedback on visual formatting

### 12.3 Rollback Plan

**Emergency Rollback:**

```sql
-- Disable feature
UPDATE Local_Lookup_Table
SET Description = 'N'
WHERE Type = 'BCC-ENBL';

-- Optionally remove auto-generated comments
DELETE FROM Consolidated_Comments_Shipment_Comments
WHERE Type = 'BOS'
  AND (Comment LIKE 'DECLARATION ESTIMATED VALUE%'
    OR Comment LIKE 'DECLARATION FINAL VALUE%'
    OR Comment LIKE 'SHIPMENT ESTIMATED COMMODITY CHARGES%'
    OR Comment LIKE 'SHIPMENT FINAL COMMODITY CHARGES%')
  AND Date >= [DEPLOYMENT_DATE];

-- Optionally remove BCLCTT references
DELETE FROM Shipment_Summary_Customer_Supplied_References
WHERE Type = 'BCLCTT';

-- Restore previous application version
-- (Execute via deployment tool)
```

## 13. TESTING REQUIREMENTS

### 13.1 Unit Test Coverage

**Import/Export Differentiation:**
- Test direction detection for AU import shipments
- Test direction detection for AU export shipments
- Test direction detection for SG import shipments
- Test direction detection for SG export shipments
- Test fallback to CUS-CMMT when CUSCMT-I not configured
- Test fallback to CUS-CMMT when CUSCMT-X not configured
- Test lookup code matching by hold reason prefix

**Declaration Charge Comments:**
- Test Project-A first declaration extraction
- Test Project-S multi-declaration summation
- Test estimated comment creation on RAT Hold PFB
- Test estimated comment update (not duplicate)
- Test final comment creation on CUS CLR
- Test final comment creation on CUS CMP
- Test final comment creation on Shipment Status 04 (Project-S)
- Test decimal formatting to 2 places
- Test currency code display

**Commodity Charge Comments:**
- Test BCLCTT creation on first billable charge
- Test BCLCTT update on subsequent billable charges
- Test BCLCTT subtraction on billable flag change to false
- Test BCLCTT deletion when all charges removed
- Test charge type filtering via BCC-CLCT
- Test estimated comment creation on RAT Hold PFB
- Test final comment creation on CUS CLR/CMP
- Test final comment creation on Shipment Status 04 (Project-S)

**Visual Formatting:**
- Test bold font application to BOS comment type
- Test red font color application to BOS comment type
- Test remark popup rendering with formatted comments

**Decimal Precision:**
- Test 2 decimal place enforcement on commodity charges
- Test 2 decimal place enforcement on declaration charges
- Test rounding behavior for 3+ decimal inputs
- Test calculation precision for summations

### 13.2 Integration Test Scenarios

**Scenario 1: Complete Import Shipment Flow (Project-A)**
1. Create import shipment with Export Country = AU
2. Add rating hold reason PFB
3. Verify direction-specific BOS comment created from CUSCMT-I
4. Verify DECLARATION ESTIMATED VALUE comment created
5. Add billable GST charge to commodity
6. Verify BCLCTT created with GST total
7. Verify SHIPMENT ESTIMATED COMMODITY CHARGES comment created
8. Add billable DUTY charge to commodity
9. Verify BCLCTT updated with GST and DUTY totals
10. Change CUS status to CLR
11. Verify DECLARATION FINAL VALUE comment created (first declaration only)
12. Verify SHIPMENT FINAL COMMODITY CHARGES comment created
13. Open remark popup
14. Verify all comments display with correct formatting

**Scenario 2: Complete Export Shipment Flow (Project-S)**
1. Create export shipment with Import Country = SG
2. Create two declarations on shipment
3. Add declaration charges to both declarations
4. Add rating hold reason PFB
5. Verify direction-specific BOS comment created from CUSCMT-X
6. Verify DECLARATION ESTIMATED VALUE comment created (combined totals)
7. Add billable WET charge to commodity
8. Verify BCLCTT created with WET total
9. Verify SHIPMENT ESTIMATED COMMODITY CHARGES comment created
10. Change Shipment Status to 04
11. Verify DECLARATION FINAL VALUE comment created (combined totals)
12. Verify SHIPMENT FINAL COMMODITY CHARGES comment created
13. Open remark popup
14. Verify all comments display with correct formatting

**Scenario 3: Charge Modification and Recalculation**
1. Create shipment with existing BCLCTT containing GST 100.00 AUD, DUTY 50.00 AUD
2. Change GST charge from billable to non-billable
3. Verify BCLCTT updated to DUTY 50.00 AUD only
4. Delete DUTY charge
5. Verify BCLCTT removed entirely
6. Add new billable EXC charge 75.00 AUD
7. Verify new BCLCTT created with EXC 75.00 AUD

**Scenario 4: Feature Disable**
1. Set BCC-ENBL to "N"
2. Create shipment and add rating hold PFB
3. Verify no declaration or commodity charge comments created
4. Verify direction-specific BOS comment still created (legacy behavior)
5. Set BCC-ENBL to "Y"
6. Add another rating hold PFB to different shipment
7. Verify declaration and commodity charge comments created

### 13.3 Performance Test Scenarios

**Load Test 1: Bulk Commodity Charge Creation**
- Create shipment with 100 commodities
- Add 5 billable charges to each commodity (500 total charges)
- Measure time for BCLCTT updates
- Target: < 5 seconds total processing time

**Load Test 2: Multi-Declaration Summation**
- Create shipment with 20 declarations
- Trigger declaration final comment creation
- Measure time for charge summation
- Target: < 2 seconds

**Load Test 3: Concurrent Comment Creation**
- Trigger 100 simultaneous rating hold reason assignments
- Measure database lock contention
- Verify all comments created successfully
- Target: No deadlocks, < 10 seconds for all completions

### 13.4 Regression Test Coverage

**Verify No Impact To:**
- Existing CUS-CMMT behavior when CUSCMT-I/X not configured
- Non-charge-related BOS comments
- Shipment processing workflows
- Declaration calculation accuracy
- Commodity charge calculation accuracy
- Remark popup performance for shipments without charge comments
- User-entered BOS comments (manual)

---

**END OF TECHNICAL SPECIFICATION**

User stories:

title: Configuration of BOS Comments for Import / Export Shipments
description: As a SBSS user, I want BOS comments to be automatically added when specific holds are applied, depending on whether the shipment is import or export.
acceptance_criteria: As part of a previous implementation (User Story 4000417: BOS (F9) comment auto trigger), when specific Rating Hold Reasons are added to a shipment, the system may automatically add one or more corresponding BOS comments with it. These comments (IAD-1, IAD-2, CER-1, etc.) are configurable. CUS-CMMT is used as the (lookup list) type for these reference codes. This implementation must be modified: The BOS comments need to be configurable depending on whether the shipment is Import or Export. Two new lookup list types should be created: Reference Type Code Represents CUSCMT-I Customs Status / Customer Comment (Import) CUSCMT-X Customs Status / Customer Comment (Export) Any existing lookup codes under CUS-CMMT should be copied to both of the aforementioned new types. When a Rating Hold Reason is added to a shipment, the system must attempt to identify one or more corresponding Lookup Codes in the Local Lookup Table. For import shipments, the system should search under the CUSCMT-I type. If CUSCMT-I has not been configured, the system should search under the CUS-CMMT type. For export shipments, the system should search under the CUSCMT-X type. If CUSCMT-X has not been configured, the system should search under the CUS-CMMT type. If one or more corresponding Lookup Codes are found: The text in the Description field of these codes must be extracted, concatenated and added as a new Consolidated Comments > Shipment Comments > BOS comment. For example: If an import shipment receives a Rating Hold Reason of IAD (and CUSCMT-I is configured): The descriptions of codes beginning with "IAD" ⁽¹⁾ under the CUSCMT-I type should be combined and stored as a new Consolidated Comments > Shipment Comments > BOS comment. If an export shipment receives a Rating Hold Reason of CER (and CUSCMT-X is configured): The descriptions of codes beginning with "CER" ⁽²⁾ under the CUSCMT-X type should be combined and stored as a new Consolidated Comments > Shipment Comments > BOS comment. If an import shipment receives a Rating Hold Reason of INS (and CUSCMT-I is not configured): The descriptions of codes beginning with "INS" ⁽³⁾ under the CUS-CMMT type should be combined and stored as a new Consolidated Comments > Shipment Comments > BOS comment. If one or more corresponding Lookup Codes are not found: Do nothing. ⁽¹⁾ IAD-1, IAD-2, etc. ⁽²⁾ CER-1, CER-2, etc. ⁽³⁾ INS-1, etc.

title: Combined Declaration Charges / Adjustments - Local Lookup Code Configuration
description: As a SBSS user, I want a comment to be added to the shipment which combines the totals for declaration charges, insurance adjustments and freight adjustments. This story intends to implement new Local Lookup Codes which can be used to configure the enablement of the succeeding functionality.
acceptance_criteria: The following new Local Lookup Codes should be created: Type Description Represents BCC-ENBL Y BOS Charges Comment (Enable) BCC-CLCT GST,EXC,DTY BOS Charges Comment (Commodity-Line Charge Types)

title: LOP - Project-A / Project-S - Import / Export - Configuring Comment Types
description: LOP for Project-A and Project-S - Import & Export - Configuring Comment Types Please refer architeecture assessment Task 6423187: Architectural Assessment
acceptance_criteria: Create LOP diagram in Visio for Project-A and Project-S - Import & Export - Configuring Comment Types

title: Combined Declaration Charges / Adjustments - Declaration Estimated Values BOS Comment (Project-A)
description: As a SBSS user, I want a comment to be added to the shipment which combines the totals for declaration charges, insurance adjustments and freight adjustments. This story intends to implement functionality which either adds a new - or updates an existing - shipment BOS comment with the estimated declaration value, insurance and freight values when triggered. The associated requirements differ slightly between the two Project countries; the below acceptance criteria caters to Project-A.
acceptance_criteria: On RAT Hold Reason PFB: (RAT Hold Reason must be Admin-Configurable) ⁽¹⁾ If the Description of Local Lookup Code > BCC-ENBL is set to Y: The system must check if the shipment has an existing Consolidated Comments > Shipment Comments > BOS comment beginning with "DECLARATION ESTIMATED VALUE". If it does, then said existing Consolidated Comments > Shipment Comments > BOS comment must be UPDATED... If it does not, then a new Consolidated Comments > Shipment Comments > BOS comment must be ADDED... ...with the following information... The value of Declaration > Charges > Declaration Total on the first declaration - shown in the local currency. The value of Declaration > Charges > Declaration Adjustments > INS on the first declaration - shown in the local currency. The value of Declaration > Charges > Declaration Adjustments > FRT on the first declaration - shown in the local currency. ...structured as "DECLARATION ESTIMATED VALUE [1], INSURANCE [2], FREIGHT [3]", for example: DECLARATION ESTIMATED VALUE 2934.21 AUD, INSURANCE 213.56 AUD, FREIGHT 482.34 AUD ⁽¹⁾ Recommended Admin-Configurable Local Lookup Code: Type Represents BCC-DEVT BOS Charges Comment (Declaration Estimated Values Trigger)

title: Combined Declaration Charges / Adjustments - Declaration Final Values BOS Comment (Project-A)
description: As a SBSS user, I want a comment to be added to the shipment which combines the totals for declaration charges, insurance adjustments and freight adjustments. This story intends to implement functionality which adds a new shipment BOS comment with the finalized declaration value, insurance and freight values when triggered. The associated requirements differ slightly between the two Project countries; the below acceptance criteria caters to Project-A.
acceptance_criteria: On CUS = CLR or On CUS = CMP: (CUS Status must be Admin-Configurable) ⁽¹⁾ If the Description of Local Lookup Code > BCC-ENBL is set to Y: A new Consolidated Comments > Shipment Comments > BOS comment must be ADDED with the following information... The value of Declaration > Charges > Declaration Total on the first declaration - shown in the local currency. The value of Declaration > Charges > Declaration Adjustments > INS on the first declaration - shown in the local currency. The value of Declaration > Charges > Declaration Adjustments > FRT on the first declaration - shown in the local currency. ...structured as "DECLARATION FINAL VALUE [1], INSURANCE [2], FREIGHT [3]", for example: DECLARATION FINAL VALUE 3678.45 AUD, INSURANCE 267.89 AUD, FREIGHT 598.12 AUD ⁽¹⁾ Recommended Admin-Configurable Local Lookup Code: Type Represents BCC-DFVT BOS Charges Comment (Declaration Final Values Trigger)

title: Combined Declaration Charges / Adjustments - Declaration Estimated Values BOS Comment (Project-S)
description: As a SBSS user, I want a comment to be added to the shipment which combines the totals for declaration charges, insurance adjustments and freight adjustments. This story intends to implement functionality which either adds a new - or updates an existing - shipment BOS comment with the estimated declaration value, insurance and freight values when triggered. The associated requirements differ slightly between the two Project countries; the below acceptance criteria caters to Project-S.
acceptance_criteria: On RAT Hold Reason PFB: (RAT Hold Reason must be Admin-Configurable) ⁽¹⁾ If the Description of Local Lookup Code > BCC-ENBL is set to Y: The system must check if the shipment has an existing Consolidated Comments > Shipment Comments > BOS comment beginning with "DECLARATION ESTIMATED VALUE". If it does, then said existing Consolidated Comments > Shipment Comments > BOS comment must be UPDATED... If it does not, then a new Consolidated Comments > Shipment Comments > BOS comment must be ADDED... ...with the following information... The combined value of Declaration > Charges > Declaration Total for all declarations - shown in the local currency. The combined value of Declaration > Charges > Declaration Adjustments > INS for all declarations - shown in the local currency. The combined value of Declaration > Charges > Declaration Adjustments > FRT for all declarations - shown in the local currency. ...structured as "DECLARATION ESTIMATED VALUE [1], INSURANCE [2], FREIGHT [3]", for example: DECLARATION ESTIMATED VALUE 1732.89 SGD, INSURANCE 184.57 SGD, FREIGHT 329.14 SGD ⁽¹⁾ Recommended Admin-Configurable Local Lookup Code: Type Represents BCC-DEVT BOS Charges Comment (Declaration Estimated Values Trigger)

title: Combined Declaration Charges / Adjustments - Declaration Final Values BOS Comment (Project-S)
description: As a SBSS user, I want a comment to be added to the shipment which combines the totals for declaration charges, insurance adjustments and freight adjustments. This story intends to implement functionality which adds a new shipment BOS comment with the finalized declaration value, insurance and freight values when triggered. The associated requirements differ slightly between the two Project countries; the below acceptance criteria caters to Project-S.
acceptance_criteria: On Shipment Status 04: (Shipment Status must be Admin-Configurable) ⁽¹⁾ If the Description of Local Lookup Code > BCC-ENBL is set to Y: A new Consolidated Comments > Shipment Comments > BOS comment must be ADDED with the following information... The combined value of Declaration > Charges > Declaration Total for all declarations - shown in the local currency. The combined value of Declaration > Charges > Declaration Adjustments > INS for all declarations - shown in the local currency. The combined value of Declaration > Charges > Declaration Adjustments > FRT for all declarations - shown in the local currency. ...structured as "DECLARATION FINAL VALUE [1], INSURANCE [2], FREIGHT [3]", for example: DECLARATION FINAL VALUE 4678.92 SGD, INSURANCE 342.19 SGD, FREIGHT 715.43 SGD ⁽¹⁾ Recommended Admin-Configurable Local Lookup Code: Type Represents BCC-DFVT BOS Charges Comment (Declaration Final Values Trigger)

title: Combined Commodity-Line Charges - Maintain Rolling Total of Relevant Charges
description: As a SBSS user, I want the system to maintain a rolling record of the combined total for commodity-line charge types of my choosing.
acceptance_criteria: A new Shipment > Summary > Customer Supplied References type code should be created: Type Code Represents BCLCTT BOS Commodity-Line Charge Types Total The Description of Local Lookup Code > BCC-CLCT should be amended to correct DTY with DUTY. DTY was originally implemented in User Story 6299437: Combined Declaration Charges / Adjustments - Local Lookup Code Configuration. When the Billable flag of a commodity-line charge type is set to TRUE (checked) ⁽¹⁾, and the charge type matches any of those listed in the Description of Local Lookup Code > BCC-CLCT:The system must validate if the shipment has an existing Shipment > Summary > Customer Supplied References > BCLCTT type code. If it does, then the existing BCLCTT > Comment must be UPDATED to add / incorporate the type and value of this commodity-line charge, in the local currency code. If it does not, then a new BCLCTT must be ADDED with the Comment field reflecting the type and value of this commodity-line charge, in the local currency code. Example: Charge Type GST with a value of 254.98 AUD. There is no instance of BCLCTT on the shipment.Result: BCLCTT is added with the Comment: GST 254.98 AUD Example: Charge Type WET with a value of 168.32 AUD. An instance of BCLCTT exists on the shipment, with the Comment field containing: GST 254.98 AUDResult: BCLCTT > Comment is updated to: GST 254.98 AUD, WET 168.32 AUD Example: Charge Type WET with a value of 101.51 AUD. An instance of BCLCTT exists on the shipment, with the Comment field containing: GST 254.98 AUD, WET 168.32 AUDResult: BCLCTT > Comment is updated to: GST 254.98 AUD, WET 269.83 AUD When the Billable flag of a commodity-line charge type is changed from TRUE (checked) to FALSE (unchecked) ⁽²⁾, and the charge type matches any of those listed in the Description of Local Lookup Code > BCC-CLCT: The existing BCLCTT > Comment must be UPDATED to subtract the value (in the local currency) of the now-unbillable, commodity-line charge. If this subtraction results in a value of zero for a given charge type, then it should be omitted entirely. If this the aforementioned omission would result in the Comment field being blank / empty, BCLCTT should be removed. Example: Charge Type LCT with a value of 171.38 AUD. An instance of BCLCTT exists on the shipment, with the Comment field containing: LCT 406.88 AUDResult: BCLCTT > Comment is updated to: LCT 235.50 AUD Example: Charge Type DTY with a value of 61.40 AUD. An instance of BCLCTT exists on the shipment, with the Comment field containing: GST 38.67 AUD, DTY 195.92 AUDResult: BCLCTT > Comment is updated to: GST 38.67 AUD, DTY 134.52 AUD Example: Charge Type EXC with a value of 77.82 AUD. An instance of BCLCTT exists on the shipment, with the Comment field containing: EXC 77.82 AUDResult: BCLCTT is removed. ⁽¹⁾ This also includes instances where a commodity-line charge type is newly-added with the Billable flag set to TRUE (checked). ⁽²⁾ This also includes instances where a commodity-line charge type with the Billable flag set to TRUE (checked) is deleted / removed.

title: Combined Commodity-Line Charges - Shipment Estimated Commodity Charges BOS Comment (Project-A)
description: As a SBSS user, I want a comment to be added to the shipment which shows the combined totals for commodity-line charges of my choosing. This story intends to implement functionality which adds a new shipment BOS comment stating the estimated commodity-line charges when triggered. The below acceptance criteria caters to Project-A.
acceptance_criteria: On RAT Hold Reason PFB: (RAT Hold Reason must be Admin-Configurable) ⁽¹⁾ If the Description of Local Lookup Code > BCC-ENBL is set to Y: The system must validate if the shipment has an existing Shipment > Summary > Customer Supplied References > BCLCTT type code. If it does, then a new Consolidated Comments > Shipment Comments > BOS comment must be ADDED with text reflecting the contents of BCLCTT > Comment, structured as "SHIPMENT ESTIMATED COMMODITY CHARGES [BCLCTT > Comment]", for example:SHIPMENT ESTIMATED COMMODITY CHARGES GST 3678.45 AUD, DUTY 267.89 AUD, WET 598.12 AUD If it does not, then do nothing. No action is required. ⁽¹⁾ Recommended Admin-Configurable Local Lookup Code: Type Represents BCC-CCET BOS Charges Comment (Commodity Charges Estimated Trigger)

title: Combined Commodity-Line Charges - Shipment Final Commodity Charges BOS Comment (Project-A)
description: As a SBSS user, I want a comment to be added to the shipment which shows the combined totals for commodity-line charges of my choosing. This story intends to implement functionality which adds a new shipment BOS comment stating the finalized commodity-line charges when triggered. The below acceptance criteria caters to Project-A.
acceptance_criteria: On CUS = CLR or On CUS = CMP: (CUS Status must be Admin-Configurable) ⁽¹⁾ If the Description of Local Lookup Code > BCC-ENBL is set to Y: The system must validate if the shipment has an existing Shipment > Summary > Customer Supplied References > BCLCTT type code. If it does, then a new Consolidated Comments > Shipment Comments > BOS comment must be ADDED with text reflecting the contents of BCLCTT > Comment, structured as "SHIPMENT FINAL COMMODITY CHARGES [BCLCTT > Comment]", for example:SHIPMENT FINAL COMMODITY CHARGES GST 3678.45 AUD, DUTY 267.89 AUD, WET 598.12 AUD If it does not, then do nothing. No action is required. ⁽¹⁾ Recommended Admin-Configurable Local Lookup Code: Type Represents BCC-CCFT BOS Charges Comment (Commodity Charges Final Trigger)

title: Combined Commodity-Line Charges - Shipment Estimated Commodity Charges BOS Comment (Project-S)
description: As a SBSS user, I want a comment to be added to the shipment which shows the combined totals for commodity-line charges of my choosing. This story intends to implement functionality which adds a new shipment BOS comment stating the estimated commodity-line charges when triggered. The below acceptance criteria caters to Project-S. While, at the time of writing, the below acceptance criteria are nearly identical to the equivalent Project-A story (User Story 6482591: Combined Commodity-Line Charges - Shipment Estimated Commodity Charges BOS Comment (Project-A)), we have intentionally chosen to implement the two countries separately to ensure the agreed-upon functionality is not part-delivered for Project-S, being mindful of the following, closely-related stories where there are differences in criteria between the countries: User Story 6455269: Combined Declaration Charges / Adjustments - Declaration Estimated Values BOS Comment (Project-S) User Story 6455271: Combined Declaration Charges / Adjustments - Declaration Final Values BOS Comment (Project-S) User Story 6503948: Combined Commodity-Line Charges - Shipment Final Commodity Charges BOS Comment (Project-S)
acceptance_criteria: On RAT Hold Reason PFB: (RAT Hold Reason must be Admin-Configurable) ⁽¹⁾ If the Description of Local Lookup Code > BCC-ENBL is set to Y: The system must validate if the shipment has an existing Shipment > Summary > Customer Supplied References > BCLCTT type code. If it does, then a new Consolidated Comments > Shipment Comments > BOS comment must be ADDED with text reflecting the contents of BCLCTT > Comment, structured as "SHIPMENT ESTIMATED COMMODITY CHARGES [BCLCTT > Comment]", for example:SHIPMENT ESTIMATED COMMODITY CHARGES GST 3678.45 SGD, DUTY 267.89 SGD, WET 598.12 SGD If it does not, then do nothing. No action is required. ⁽¹⁾ Recommended Admin-Configurable Local Lookup Code: Type Represents BCC-CCET BOS Charges Comment (Commodity Charges Estimated Trigger)

title: Combined Commodity-Line Charges - Shipment Final Commodity Charges BOS Comment (Project-S)
description: As a SBSS user, I want a comment to be added to the shipment which shows the combined totals for commodity-line charges of my choosing. This story intends to implement functionality which adds a new shipment BOS comment stating the finalized commodity-line charges when triggered. The below acceptance criteria caters to Project-S.
acceptance_criteria: On Shipment Status 04: (Shipment Status must be Admin-Configurable) ⁽¹⁾ If the Description of Local Lookup Code > BCC-ENBL is set to Y: The system must validate if the shipment has an existing Shipment > Summary > Customer Supplied References > BCLCTT type code. If it does, then a new Consolidated Comments > Shipment Comments > BOS comment must be ADDED with text reflecting the contents of BCLCTT > Comment, structured as "SHIPMENT FINAL COMMODITY CHARGES [BCLCTT > Comment]", for example:SHIPMENT FINAL COMMODITY CHARGES GST 3678.45 SGD, DUTY 267.89 SGD, WET 598.12 SGD If it does not, then do nothing. No action is required. ⁽¹⁾ Recommended Admin-Configurable Local Lookup Code: Type Represents BCC-CCFT BOS Charges Comment (Commodity Charges Final Trigger)

title: Limit Precision for Commodity Amounts Calculation
description: As a SBSS user, I need charge amounts in SBSS to have the appropriate decimal precision, to ensure compliance with Customs rules and regulations.
acceptance_criteria: The decimal precision of charge amounts and values should be configured to a maximum precision of two decimal places. Fields include (but are not limited to): Commodity > Entry Freight Commodity > Discount Commodity > Value Adjustment Commodity > Unit Value Commodity > Statistical Value