Skip to content

Tax Forms Workflow

1. Executive Summary

Purpose

The tax forms workflow enables UTA to fulfill its regulatory obligations as a withholding agent for talent payments made to non-resident aliens (US jurisdiction) and foreign entertainers (UK jurisdiction). Withholding taxes are calculated and applied upstream during worksheet processing; this workflow covers the downstream steps: generating tax forms from those actual applied deductions, organizing them into filing packages, previewing PDF output, tracking filing status, and producing the electronic filing artifacts required by the IRS and HMRC. The workflow sits at the end of the financial chain — after cash has been received, worksheets have been applied, and withholding deductions have been recorded against PAY receivables.

Scope

Covered:

  • Generating individual tax form records (IRS 1042-S, IRS 1099-NEC, HMRC FEU1, HMRC FEU2) from actual worksheet transaction data
  • Generating annual IRS filing packages (Form 1042-T transmittal + Form 1042-S per-payee forms in Mailing 1; Form 1042 annual return in Mailing 2)
  • Cross-form reconciliation: verifying that aggregate 1042-S totals match the 1042-T transmittal and Form 1042 annual return
  • Viewing and downloading individual tax form PDFs with source lineage drill-down
  • Tracking filing status transitions: Generated → Filed → Submitted
  • Deleting draft/generated form records that have not yet been filed
  • Electronic filing preview: IRS FIRE file format (Publication 1187) and MeF XML stub
  • Compliance monitoring for expiring CWA approvals and W-8 forms (surfaced upstream but maintained via party tax profiles consumed here)

Not covered (documented separately):

  • Party tax profile maintenance (residency, CWA, W-8/W-9, VAT registration) — see Worksheets Workflow and party management
  • Withholding tax calculation during worksheet processing — see Worksheets Workflow
  • Cash application and deduction recording — see Worksheets Workflow
  • UK VAT on artist fees and commissions (applied at worksheet time) — see Worksheets Workflow

Key Objectives

  • Produce accurate, audit-traceable regulatory filings from actual cash application data — not from estimates or billing item due dates
  • Organize IRS annual filings into the IRS-mandated two-mailing structure and verify cross-form totals before submission
  • Provide full source lineage from each form field value back to the specific cash_receipt_application and cash_receipt_application_deduction records that contributed to it
  • Track the lifecycle of each form from generation through tax authority acknowledgement

2. Process Overview

mermaid
flowchart TD
    A[Worksheets Applied\nWithholding Deductions Recorded] --> B{Form Type?}
    B -->|IRS 1042-S / 1099-NEC\nor HMRC FEU1 / FEU2| C[Individual Form Generation]
    B -->|IRS Annual Package| D[Annual Filing Package Generation]

    C --> C1[Select Form Type + Party + Period]
    C1 --> C2[System aggregates PAY applications\nand withholding deductions from actuals]
    C2 --> C3[tax_form record created\nstatus_cd = GENERATED]
    C3 --> C4[Review form data and PDF preview]
    C4 --> C5[Source lineage drill-down optional]

    D --> D1[Select Tax Year]
    D1 --> D2[System discovers all parties\nwith NRA withholding in period]
    D2 --> D3[1042-S generated per recipient\nassigned to Mailing 1]
    D3 --> D4[1042-T transmittal generated\nsequence 1 in Mailing 1]
    D4 --> D5[Form 1042 annual return generated\nassigned to Mailing 2]
    D5 --> D6[Reconciliation computed\nand stored in tax_filing_package]
    D6 --> D7[Review package and reconciliation]

    C4 --> E[Mark as Filed\nstatus_cd = FILED]
    D7 --> E
    E --> F[Mark as Submitted\nstatus_cd = SUBMITTED]
    F --> G[Terminal State]

Walkthrough

  1. Prerequisites in place — Worksheets for the tax period have been applied and withholding deductions (cash_receipt_application_deduction) have been recorded with type codes WH_US_NRA (US NRA) or WH_UK_FEU (UK FEU). The tax form workflow reads these existing deduction records; it does not recalculate withholding.

  2. Choose generation mode — Users choose either individual form generation (for a specific party, form type, and period) or annual filing package generation (for the IRS 1042 suite). The annual package mode auto-discovers all recipients with NRA withholding in the year.

  3. Form data built from actuals — The system queries cash_receipt_application and cash_receipt_application_deduction records for the party and period. It aggregates gross PAY applications and withholding deduction totals. These become the authoritative values in tax_form.form_data_json. A source_map_json is built alongside, linking each form field value to its contributing records.

  4. Record created in Generated status — A tax_form record is inserted with status_cd = 'GENERATED' and generated_dt set to the current timestamp. For package generation, a tax_filing_package record is also created, and reconciliation is computed.

  5. Review, PDF preview, and drill-down — Users review the form data on the detail screen. Monetary field values that have source lineage display as clickable links; clicking opens a side panel showing the specific worksheet applications and deductions that contributed to the value.

  6. Refresh data option — For forms in GENERATED or DRAFT status, users can regenerate the form data from current actuals. This re-queries the source tables and updates form_data_json and source_map_json in place.

  7. Mark as Filed — After transmitting to the IRS or HMRC, the user updates tax_form.status_cd to 'FILED' and filed_dt is set to the current timestamp.

  8. Mark as Submitted — After the tax authority acknowledges receipt, the user updates tax_form.status_cd to 'SUBMITTED'. This is a terminal state; no further status transitions are permitted.


3. Business Rules

3.1 Tax Forms Are Derived from Actual Transactions Only

Business rule: Tax form data is populated exclusively from cash_receipt_application and cash_receipt_application_deduction records on active (Applied, Settled, or Approved) worksheets. Billing item amounts, split reference amounts, or estimated figures are never used as form field sources.

Foundation reference: Tax Withholding Data Model — Section 2.5 tax_form

Workflow context: When a user triggers form generation, the system queries actual PAY applications and withholding deduction records for the party and period. If no deduction records exist for the period, form totals will be zero. Users should verify that worksheets for the period are in Applied (P) or later status before generating forms.


3.2 Only Active Worksheets Contribute to Form Totals

Business rule: The form data aggregation queries filter to worksheets with cash_receipt_worksheet_status_cd IN ('P', 'T', 'A') (Applied, Settled, Approved). Returned (R) worksheets are excluded. Reversal applications (reversal_of_application_id IS NOT NULL) are also excluded.

Foundation reference: Tax Withholding Queries — Section 2.5.1 getPayApplicationsForParty


3.3 Tax Year Boundaries Differ by Jurisdiction

Business rule: For US forms (IRS 1042-S, 1042, 1042-T, 1099-NEC), the tax period is the calendar year: January 1 through December 31. For UK forms (HMRC FEU1, FEU2), the tax period follows the UK tax year: April 6 through the following April 5. Quarters within the UK tax year are: Q1 (Apr 6–Jun 30), Q2 (Jul 1–Sep 30), Q3 (Oct 1–Dec 31), Q4 (Jan 1–Apr 5 of the following year).

Foundation reference: Tax Withholding Queries — Section 3.6 UK Tax Period Date Ranges

Workflow context: When generating HMRC FEU1 or FEU2 forms, the user must select both a tax year and a quarter. The quarter selector displays the UK-aligned date ranges (e.g., "Q1: Apr 6 – Jun 30"). For IRS annual forms, no quarter selection is required.


3.4 IRS Annual Package Structure Is Mandated

Business rule: IRS annual 1042 filings must be organized into two separate mailings. Mailing 1 contains the 1042-T transmittal cover (sequence 1) followed by all 1042-S Copy A forms. Mailing 2 contains only the Form 1042 annual return. These two mailings must never be combined into a single submission.

Foundation reference: Tax Withholding Data Model — Section 2.6 tax_filing_package and Section 5.9 Mailing Codes

Workflow context: The annual filing package detail screen organizes forms into the two mailing groups with separate download buttons. Each mailing section shows its forms, their gross and withholding amounts, and their chapter classification (Chapter 3 or Chapter 4). The description on each mailing section includes IRS mailing address guidance and due date.


3.5 Reconciliation Must Pass Before Filing

Business rule: For an IRS annual filing package, the sum of gross income and federal tax withheld across all 1042-S forms must exactly equal the corresponding totals on the 1042-T transmittal form and on the Form 1042 annual return. The package's reconciliation_json records whether allReconciled = true or false. A package showing allReconciled = false has mismatched totals and must not be filed.

Foundation reference: Tax Withholding Data Model — Section 3.2 tax_filing_package Status — Transition: Generated → Reviewed

Workflow context: The Reconciliation Check panel on the filing package detail screen displays a cross-form comparison table showing aggregate 1042-S totals, 1042-T totals, and Form 1042 totals side by side. Each comparison row includes a match indicator. The overall status displays "All Matched" or "Mismatch Detected."


3.6 Quarterly UK Forms Require a Quarter Code

Business rule: When tax_form.jurisdiction_cd = 'GB' and form_code_cd is HMRC_FEU1 or HMRC_FEU2, quarter_cd is required. Annual UK forms do not require a quarter.

Foundation reference: Tax Withholding Data Model — Section 4 Validation — Quarter required for HMRC quarterly forms

Workflow context: When a user selects an HMRC FEU1 or FEU2 form type, the quarter selector becomes visible. The Generate button remains disabled until a quarter is selected.


3.7 Status Transitions Are Forward-Only

Business rule: tax_form.status_cd moves only forward: DRAFTGENERATEDFILEDSUBMITTED. A form that has been filed cannot be moved back to Generated. A Submitted form has no further transitions.

Foundation reference: Tax Withholding Data Model — Section 3.1 tax_form Status

Workflow context: The queue table shows status-appropriate actions in each row's overflow menu. Once a form reaches FILED, the "Mark as Filed" action is hidden. Once SUBMITTED, no further status actions are available — only "View Details" and "Download PDF."


3.8 Form Data Cannot Be Refreshed After Filing

Business rule: The "Refresh Data" button on the form detail screen is only enabled for forms with status_cd = 'DRAFT' or status_cd = 'GENERATED'. Once a form is marked as Filed or Submitted, its form_data_json and source_map_json are treated as the official filed record and must not be overwritten.

Foundation reference: Tax Withholding Data Model — Section 3.1 tax_form Status


3.9 FEU1 Aggregates All Parties; FEU2 Is Per-Party

Business rule: HMRC FEU1 is a quarterly return covering all foreign entertainers paid in the quarter. HMRC FEU2 is a per-recipient certificate issued to each individual entertainer. FEU2 requires a party_id to identify the specific entertainer; FEU1 does not require a specific client.

Foundation reference: Tax Withholding Data Model — Section 5.5 Tax Form Codes

Workflow context: In the generator form, the "Client / Payee" field is hidden when the user selects HMRC FEU1 (requires all UK withholding records for the period, not a single party). It is shown and required for HMRC FEU2.


3.10 Source Lineage Is Generated at Form Creation Time

Business rule: The source_map_json field in tax_form links each form field name to an array of contributing source records (cash_receipt_application or cash_receipt_application_deduction). This lineage snapshot is created when the form is generated and captures the state of the data at that moment. Subsequent changes to underlying worksheets do not automatically update the form lineage unless the user explicitly refreshes the form data.

Foundation reference: Tax Withholding Data Model — Section 2.5 tax_form — source_map_json


4. Data Access & Operations References

4.1 Queries Used

OperationFoundation DocPurpose in This Workflow
getTaxFormsTax Withholding Queries — 2.5.xLoads the tax form list for the queue table with optional filters by tax year, jurisdiction, status, and search text
getTaxFormByIdTODO: Document in foundation/queries/tax-withholding.mdLoads a single tax_form record with all fields including form_data_json and source_map_json for the detail screen
getTaxFormStatsTODO: Document in foundation/queries/tax-withholding.mdAggregates form counts by status and jurisdiction for the stats cards on the queue screen
getFilingPackagesTODO: Document in foundation/queries/tax-withholding.mdLoads all tax_filing_package records for the packages summary card
getFilingPackageTODO: Document in foundation/queries/tax-withholding.mdLoads a single tax_filing_package with its associated tax_form records for the package detail screen
getPayApplicationsForPartyTax Withholding Queries — 2.5.1Aggregates PAY applications for a party within a tax period to populate gross income on form data
getWithholdingDeductionsForApplicationsTax Withholding Queries — 2.5.2Retrieves withholding deduction records for the application set to populate federal tax withheld fields
aggregateForPeriodTax Withholding Queries — 2.5.3Combined aggregate of gross and withholding for the form period
getPartiesWithWithholdingTax Withholding Queries — 2.5.4Discovers all parties with NRA withholding deductions in a period for auto-populating 1042-S recipients in the annual package
aggregate1042SFormsForYearTax Withholding Queries — 2.5.5Sums 1042-S gross and withheld totals for building Form 1042-T transmittal and Form 1042 annual return
getTaxLiabilityByPeriodTax Withholding Queries — 2.5.6Buckets withholding deductions by semi-monthly period for IRS Form 1042 Section 1 deposit schedule
getPartyTaxProfileTax Withholding Queries — 2.1.1Reads party residency, treaty status, and entity type for populating recipient fields on IRS forms
getTaxPeriodTax Withholding Queries — 3.6Computes the date range for a given tax year, quarter, and jurisdiction
getSourceRecordsTODO: Document in foundation/queries/tax-withholding.mdResolves source_map_json entries to display records for the source lineage drill-down panel

4.2 Procedures Used

OperationFoundation DocTrigger in This Workflow
createTaxFormRecordTax Withholding Procedures — 2.4 Tax Form GenerationUser clicks "Generate Form Record" in the generator panel, or the system creates child forms during annual package generation
updateTaxFormStatusTax Withholding Procedures — 2.4.xUser selects "Mark as Filed" or "Mark as Submitted" from the form's overflow menu
deleteTaxFormRecordTax Withholding Procedures — 2.4.xUser confirms deletion from the form's overflow menu
regenerateTaxFormDataTax Withholding Procedures — 2.4.xUser clicks "Refresh Data" on a DRAFT or GENERATED form detail screen
generateAnnualFilingPackageTax Withholding Procedures — 2.5 Annual Filing PackageUser clicks "Generate Annual Filing Package" with a selected tax year
generateTaxFormPDFTODO: Document in foundation/procedures/tax-withholding.mdPDF preview auto-loads on the form detail screen; user can also click "Regenerate PDF"
generateMailingPdfTODO: Document in foundation/procedures/tax-withholding.mdUser clicks "Download PDF" on a mailing section of the filing package detail screen
getFireFilePreviewTODO: Document in foundation/procedures/tax-withholding.mdUser expands the "FIRE File Preview" section on the e-filing panel
getMeFXmlStubTODO: Document in foundation/procedures/tax-withholding.mdUser expands the "MeF XML Stub" section on the e-filing panel

5. Key User Actions

5.1 Generate Individual Tax Form

Preconditions:

  • Worksheets for the relevant party and tax period must be in Applied ('P'), Settled ('T'), or Approved ('A') status with withholding deduction records in cash_receipt_application_deduction
  • For HMRC FEU2: a party_id must be selected
  • For HMRC FEU1: no specific party required
  • For IRS 1042-S: a party_id must be selected; the party should have NRA withholding deductions (WH_US_NRA) in the period

Procedure reference: Tax Withholding Procedures — 2.4 Tax Form Generation

Steps:

  1. User selects a form type from the "Generate Form" section. A side panel displays the form's description, jurisdiction, filing frequency, and due date.
  2. For forms requiring a client, the user types to search for a party by name and selects from the typeahead suggestions. The selection captures both the party_id and display name.
  3. User selects the tax year. For quarterly UK forms, user also selects the quarter.
  4. User optionally enters notes.
  5. User clicks "Generate Form Record." The system calls buildFormDataFromActuals to query cash_receipt_application and cash_receipt_application_deduction records for the party and period, aggregates totals, and builds the source_map_json lineage.
  6. A new tax_form record is inserted with status_cd = 'GENERATED', generated_dt = now(), source_type_cd = 'WORKSHEET', and form_data_json / source_map_json populated.
  7. The generator section collapses and the forms queue refreshes to show the new record.

Postconditions:

  • tax_form.status_cd = 'GENERATED'
  • tax_form.form_data_json populated with aggregated income and withholding values
  • tax_form.source_map_json populated with per-field lineage records
  • tax_form.generated_dt = current timestamp
  • tax_form.source_type_cd = 'WORKSHEET'

UI trigger: "Generate Form Record" button in the generator panel. Visible always. Enabled when a form type is selected.


5.2 Generate Annual IRS Filing Package

Preconditions:

  • At least one party must have WH_US_NRA withholding deductions on active worksheets within the calendar year selected

Procedure reference: Tax Withholding Procedures — 2.5 Annual Filing Package

Steps:

  1. User selects a tax year from the "Annual Filing Package (1042)" card.
  2. User clicks "Generate Annual Filing Package."
  3. The system calls getPartiesWithWithholding to discover all parties with WH_US_NRA deductions in the calendar year.
  4. For each discovered party, a 1042-S form record is created via createTaxFormRecord with mailing_cd = 'MAILING_1' and chapter_cd = 'CH3_ORIG'. Each form's data is built from the party's actual PAY applications and NRA withholding deductions for the year.
  5. A Form 1042-T (transmittal) record is created with mailing_cd = 'MAILING_1', sequence_no = 1. Its data is built by calling aggregate1042SFormsForYear to sum across all the 1042-S forms just created.
  6. A Form 1042 (annual return) record is created with mailing_cd = 'MAILING_2'. Its data includes total gross amounts, total withholding, and the semi-monthly deposit schedule from getTaxLiabilityByPeriod.
  7. A tax_filing_package record is inserted with status_cd = 'GENERATED', filing_type_cd = 'IRS_1042_ANNUAL', and reconciliation_json computed from the cross-form total verification.
  8. All created tax_form records are linked to the package via tax_filing_package_id.
  9. The user is navigated to the new filing package detail screen.

Postconditions:

  • tax_filing_package.status_cd = 'GENERATED'
  • tax_filing_package.reconciliation_json populated with totalGrossFrom1042S, totalWithheldFrom1042S, form1042TGross, form1042Gross, grossMatch, withheldMatch, allReconciled, and formBreakdown
  • One tax_form record per NRA recipient with form_code_cd = 'IRS_1042_S', mailing_cd = 'MAILING_1'
  • One tax_form record with form_code_cd = 'IRS_1042_T', mailing_cd = 'MAILING_1', sequence_no = 1
  • One tax_form record with form_code_cd = 'IRS_1042', mailing_cd = 'MAILING_2'

UI trigger: "Generate Annual Filing Package" button in the Annual Filing Package card. Visible always. Enabled when a tax year is selected.


5.3 View Form Detail and PDF Preview

Preconditions:

  • A tax_form record exists in any status

Procedure reference: Tax Withholding Queries — 2.5.x

Steps:

  1. User clicks a row in the tax forms queue, or selects "View Details" from the row's overflow menu.
  2. The detail screen loads the tax_form record. The PDF is generated automatically on page load by calling generateTaxFormPDF.
  3. The left panel shows structured form data organized by form type. Monetary fields with source lineage are underlined (clickable).
  4. The right panel shows an embedded PDF preview.
  5. User can click "Download PDF" to save the form to disk.
  6. User can click "Regenerate PDF" to re-render the PDF from current form_data_json without re-querying actuals.

Postconditions:

  • No data mutations. Read-only operation.

UI trigger: Row click on the tax forms queue, or "View Details" menu item. Always visible.


5.4 Drill Down to Source Records

Preconditions:

  • The form has a non-null source_map_json
  • The specific field being drilled has an entry in source_map_json

Procedure reference: TODO: Document in foundation/procedures/tax-withholding.md

Steps:

  1. On the form detail screen, user clicks an underlined monetary value (e.g., "Gross Income" or "Federal Tax Withheld").
  2. A side panel opens. The system calls getSourceRecords with the tax_form_id and the clicked fieldName.
  3. The panel displays the aggregation type (SUM), the count of contributing records, and a table of individual source records with label, amount, and a link to the contributing worksheet.
  4. User can click the worksheet link to navigate to the worksheet detail screen in a new tab.

Postconditions:

  • No data mutations. Read-only operation.

UI trigger: Underlined/dotted monetary value fields on the form detail screen. Visible only when the field has a source_map_json entry.


5.5 Refresh Form Data

Preconditions:

  • tax_form.status_cd is 'DRAFT' or 'GENERATED'
  • The form has not yet been filed

Procedure reference: Tax Withholding Procedures — 2.4.x

Steps:

  1. User clicks "Refresh Data" on the form detail screen.
  2. The system re-runs buildFormDataFromActuals for the form's party, year, quarter (if applicable), and jurisdiction.
  3. The tax_form.form_data_json and source_map_json are overwritten with the fresh aggregation results.
  4. The page reloads to display the updated data, and the PDF preview regenerates.

Postconditions:

  • tax_form.form_data_json updated with current aggregated values
  • tax_form.source_map_json updated with current lineage

UI trigger: "Refresh Data" button on the form detail header. Visible and enabled only when status_cd is 'DRAFT' or 'GENERATED'.


5.6 Mark Form as Filed

Preconditions:

  • tax_form.status_cd is not 'FILED' and not 'SUBMITTED'
  • The user has transmitted the form to the IRS or HMRC out-of-system

Procedure reference: Tax Withholding Procedures — 2.4.x

Steps:

  1. User selects "Mark as Filed" from the row's overflow menu on the forms queue.
  2. The system updates tax_form.status_cd = 'FILED' and tax_form.filed_dt = current timestamp.
  3. The queue table refreshes to reflect the new status.

Postconditions:

  • tax_form.status_cd = 'FILED'
  • tax_form.filed_dt = current timestamp

UI trigger: "Mark as Filed" item in the row overflow menu. Visible when status_cd != 'FILED' and status_cd != 'SUBMITTED'.


5.7 Mark Form as Submitted

Preconditions:

  • tax_form.status_cd is not 'SUBMITTED'

Procedure reference: Tax Withholding Procedures — 2.4.x

Steps:

  1. User selects "Mark as Submitted" from the row's overflow menu.
  2. The system updates tax_form.status_cd = 'SUBMITTED' and tax_form.filed_dt = current timestamp (if not already set).
  3. The queue table refreshes.

Postconditions:

  • tax_form.status_cd = 'SUBMITTED'
  • Terminal state — no further transitions available

UI trigger: "Mark as Submitted" item in the row overflow menu. Visible when status_cd != 'SUBMITTED'.


5.8 Delete Form Record

Preconditions:

  • The form has not been filed with a tax authority

Procedure reference: Tax Withholding Procedures — 2.4.x

Steps:

  1. User selects "Delete" from the row's overflow menu.
  2. A confirmation dialog appears naming the form type being deleted.
  3. User confirms deletion.
  4. The tax_form record is hard-deleted from the database.
  5. The queue table refreshes.

Postconditions:

  • tax_form record removed from the database

UI trigger: "Delete" item (destructive) in the row overflow menu. Always visible.

WARNING

The PoC permits deletion of any form record regardless of status. Production should restrict deletion to forms in DRAFT or GENERATED status only, preventing accidental deletion of filed or submitted records.


5.9 View Filing Package and Reconciliation

Preconditions:

  • A tax_filing_package record exists (created by the annual package generator)

Procedure reference: Tax Withholding Queries — 2.5.5

Steps:

  1. User clicks a filing package link in the "Filing Packages" section of the main tax forms screen, or navigates directly to the package detail screen.
  2. The detail screen loads the tax_filing_package record and all associated tax_form records grouped by mailing_cd.
  3. The Reconciliation Check panel displays cross-form total comparison. If reconciliation_json.allReconciled = true, the panel shows "All Matched." If false, "Mismatch Detected" is shown.
  4. Mailing sections list each form with gross, withheld, and chapter classification. Each form has a link to its detail page.
  5. User can download a combined mailing PDF per mailing section.
  6. User can expand the Electronic Filing section to preview the IRS FIRE file format and MeF XML stub.

Postconditions:

  • No data mutations. Read-only operation.

UI trigger: Filing package row click in the "Filing Packages" card. Always visible for existing packages.


5.10 Preview Electronic Filing Artifacts

Preconditions:

  • A tax_filing_package record exists with status_cd = 'GENERATED' or later

Procedure reference: TODO: Document in foundation/procedures/tax-withholding.md

Steps:

  1. On the filing package detail screen, user expands "FIRE File Preview (1042-S)" to see the IRS Publication 1187 fixed-width format record structure with T (Transmitter), A (Payer), B (Payee), C (End of Payer), and F (End of Transmission) record types.
  2. User can expand "MeF XML Stub (Form 1042)" to see an informational XML stub for the IRS Modernized e-File system.
  3. User can expand "How to Get FIRE / IRIS Approved" to see step-by-step instructions for applying for a Transmitter Control Code (TCC) and submitting production files.

Postconditions:

  • No data mutations. Read-only operation.

UI trigger: Collapsible sections within the Electronic Filing card on the package detail screen. Always visible on that screen.

**PoC Artifact:**

The FIRE file preview and MeF XML stub are informational previews only. They contain placeholder values (TCC, EIN) and are marked "TEST FILE." Production implementation would require actual TCC registration with the IRS and submission through the FIRE system (or its IRIS successor, which replaces FIRE effective January 1, 2026).


6. Permissions & Role-Based Access

ActionCASH_MANAGERCASH_PROCESSORSETTLEMENT_APPROVERIT
View tax forms listYesYesYesYes
Generate individual tax formYesYesYesYes
Generate annual filing packageYesYesYesYes
Refresh form dataYesYesYesYes
Download PDFYesYesYesYes
View source lineage drill-downYesYesYesYes
Mark form as FiledYesYesYesYes
Mark form as SubmittedYesYesYesYes
Delete form recordYes
View filing packageYesYesYesYes
View e-filing previewYesYesYesYes

**PoC Artifact:**

Role-based access control is not enforced at the action or service layer in the PoC implementation. All authenticated users have full access to all tax form operations. The table above reflects the intended production permissions design. In particular, deletion of form records should be restricted to IT/Admin to prevent accidental removal of filed records.

Field-level restrictions:


7. Integration Points

7.1 Upstream

SourceData ProvidedMechanism
Worksheets Workflowcash_receipt_application records (PAY applications) and cash_receipt_application_deduction records (withholding deductions with type codes WH_US_NRA, WH_UK_FEU) from applied/settled/approved worksheetsDirect FK joins at query time via TaxFormDataService
Party Tax Profile Maintenanceparty_tax_info records (residency, TIN type, CWA status, treaty status, VAT registration) for populating recipient fields on IRS formsFK lookup via party_tax_info.party_id matching billing_item.client_id
Billing Item Domainbilling_item.client_id links PAY application records to the party identity used for form generationFK join through billing_item_detailbilling_item

7.2 Downstream

ConsumerData ConsumedMechanism
IRS (paper filing)Form 1042-S Copy A (per NRA payee), Form 1042-T transmittal, Form 1042 annual return — organized into Mailing 1 and Mailing 2 PDF packagesPDF download from filing package screen; physical mail to IRS Ogden, UT
IRS (electronic filing)FIRE fixed-width format file (Publication 1187) for 1042-S e-filing; MeF XML for Form 1042FIRE file preview in e-filing panel (production: upload to IRS FIRE/IRIS system)
HMRCFEU1 quarterly return (all UK performers) and FEU2 certificate (per performer) PDF formsPDF download from individual form detail screen; submission to HMRC
Recipient parties (talent)FEU2 certificate of tax deducted mailed to each entertainerPDF download

7.3 External Integrations

SystemDirectionProtocolNotes
IRS FIRE System (Publication 1187)OutboundFixed-width ASCII file uploadSubmitter requires a Transmitter Control Code (TCC). PoC generates a format preview only. The FIRE system retires December 31, 2026.
IRS IRIS SystemOutboundXML/API (IRIS portal)Successor to FIRE, operational from January 1, 2026. PoC provides an MeF XML stub for informational purposes only.
HMRC FEU Online ServiceOutboundManual / paper / HMRC portalNo direct API integration in PoC. Forms are downloaded as PDFs and submitted out-of-system.

8. Functional Screen Requirements

8.1 Tax Forms List Screen

Route: /tax-forms

Data loading:

  • getFilingPackages — loads all tax_filing_package records for the Filing Packages card
  • getTaxForms (with active filter state) — loads tax_form records for the queue table
  • getTaxFormStats — loads form count aggregates by status and jurisdiction for stats cards

Filing Packages Region

Shows existing annual filing packages as clickable navigation cards. Each card shows the tax year label, form count, and package status.

Field / ColumnSourceEditable?Condition
Tax Year Labeltax_filing_package.tax_year formatted as "TY XXXX Annual Filing Package"NoAlways visible
Form CountCount of tax_form records with this tax_filing_package_idNoAlways visible
Status Badgetax_filing_package.status_cdNoAlways visible

Conditional display:

  • Entire Filing Packages section hidden when no tax_filing_package records exist

Generator Region

Collapsible section containing the Annual Filing Package card and the individual form generator card side by side.

Field / ColumnSourceEditable?Condition
Annual Package Tax YearUser inputYesAlways visible in the Annual Filing Package card
Form Type selectorFORM_OPTIONS constant (IRS 1042-S, 1099-NEC, HMRC FEU1, FEU2)YesIndividual form card
Client / Payee typeaheadparty.display_name via searchPartiesYesShown only when form.requiresClient = true
Tax Year selectorUser input (current year minus 4 years shown)YesIndividual form card
Quarter selectorUK quarter options (Q1–Q4 with date ranges)YesShown only when form is quarterly (HMRC FEU1/FEU2)
NotesFree text, up to 500 charactersYesIndividual form card
Form info cardDescription, jurisdiction, filing frequency, due date from FORM_OPTIONSNoShown only when a form type is selected

Grid features:

  • No grid in this region

Conditional display:

  • Quarter selector visible only when isQuarterly = true (HMRC FEU1 or FEU2 selected)
  • Client / Payee field visible only when form.requiresClient = true
  • "Generate Form Record" button enabled only when a form type is selected and (for quarterly forms) a quarter is selected

Queue Region

Grid of all tax_form records matching the current filter state.

Field / ColumnSourceEditable?Condition
Formtax_form.form_code_cd displayed as human-readable labelNoAlways visible
Clienttax_form.party_nameNoAlways visible
Jurisdictiontax_form.jurisdiction_cd displayed as "US / IRS" or "UK / HMRC"NoAlways visible
Periodtax_form.quarter_cd + tax_form.tax_year or "TY XXXX"NoAlways visible
Statustax_form.status_cd as badgeNoAlways visible
Generatedtax_form.generated_dt formatted dateNoAlways visible
Filedtax_form.filed_dt formatted dateNoAlways visible
ActionsOverflow menu (View Details, Download PDF, Mark as Filed, Mark as Submitted, Delete)Always visible

Grid features:

  • Sortable columns: none in PoC (ordered by tax_form.created_dt descending)
  • Filters: Tax Year (select), Jurisdiction (US / GB / All), Status (DRAFT / GENERATED / FILED / SUBMITTED / All), Search text (matches party_name, form_code_cd, notes)
  • Row selection: single row click navigates to form detail
  • Pagination: hard limit of 200 records in PoC

Conditional display:

  • Stats cards (Total, Draft, US/IRS, UK/HMRC) visible only when stats.totalForms > 0 for the selected year filter
  • Empty state shown when no forms match current filters
  • "Mark as Filed" menu item hidden when status_cd = 'FILED' or status_cd = 'SUBMITTED'
  • "Mark as Submitted" menu item hidden when status_cd = 'SUBMITTED'

8.2 Tax Form Detail Screen

Route: /tax-forms/[id]

Data loading:

  • getTaxFormById(taxFormId) — loads the full tax_form record including form_data_json and source_map_json
  • generateTaxFormPDF(taxFormId) — called automatically on page load to produce the PDF preview (base64 encoded)

Header Region

Shows form identity, filing package membership, status, and primary action buttons.

Field / ColumnSourceEditable?Condition
Form Labeltax_form.form_code_cd as human-readable labelNoAlways visible
Status Badgetax_form.status_cdNoAlways visible
Source Type Badge ("Manual Entry")tax_form.source_type_cdNoVisible only when source_type_cd = 'MANUAL'
Party Nametax_form.party_nameNoAlways visible
Period Labeltax_form.tax_year, tax_form.quarter_cd, tax_form.jurisdiction_cdNoAlways visible
Record IDtax_form.tax_form_idNoAlways visible
Filing Package Bannertax_form.tax_filing_package_id as link, tax_form.tax_year, tax_form.mailing_cdNoVisible only when tax_filing_package_id is not null

Conditional display:

  • "Refresh Data" button visible and enabled only when status_cd = 'DRAFT' or status_cd = 'GENERATED'
  • "Download PDF" button enabled only when PDF has been generated (pdfBase64 is set)

Form Data Panel

Structured view of tax_form.form_data_json rendered by form type. Each form type has its own renderer (1042-S, 1042, 1099-NEC, FEU1, FEU2). Monetary fields with matching source_map_json entries are rendered as clickable underlined links.

Field / ColumnSourceEditable?Condition
Form Codetax_form.form_code_cdNoRecord Info collapsible (collapsed by default)
Tax Yeartax_form.tax_yearNoRecord Info
Quartertax_form.quarter_cdNoRecord Info; visible only when not null
Jurisdictiontax_form.jurisdiction_cd as labelNoRecord Info
Statustax_form.status_cd as labelNoRecord Info
Generated Datetax_form.generated_dtNoRecord Info
Filed Datetax_form.filed_dtNoRecord Info
Notestax_form.notesNoRecord Info; visible only when not null
Gross Incometax_form.form_data_json.grossIncomeNo1042-S income summary; clickable when in source map
Federal Tax Withheldtax_form.form_data_json.federalTaxWithheldNo1042-S income summary; clickable when in source map
Net IncomeComputed: grossIncome - federalTaxWithheldNo1042-S income summary
Total Gross Amountstax_form.form_data_json.totalGrossAmountsNoForm 1042 summary; clickable when in source map
Total Withholding Taxtax_form.form_data_json.totalWithholdingTaxNoForm 1042 summary; clickable when in source map
Quarterly Gross (FEU)tax_form.form_data_json.totalGrossPaymentNoFEU1/FEU2; clickable when in source map
Quarterly Withholding (FEU)tax_form.form_data_json.totalWithholdingNoFEU1/FEU2; clickable when in source map
Entertainer rowstax_form.form_data_json.rows arrayNoFEU1; shown when rows array is non-empty
Recipient name and countrytax_form.form_data_json.recipientNo1042-S recipient section
Payer / Agent infotax_form.form_data_json.withholdingAgent or .payerNoForm-type-specific sections

Grid features:

  • No grid; collapsible sections with key-value rows

Conditional display:

  • "No form data available" message shown when form_data_json is null
  • Clickable underlined links shown only for monetary fields with source_map_json entries

PDF Preview Panel

Embedded PDF iframe showing the rendered form. Fixed to viewport height with scrolling.

Field / ColumnSourceEditable?Condition
PDF iframegenerateTaxFormPDF result (base64)NoWhen pdfBase64 is populated

Conditional display:

  • Loading spinner shown during PDF generation
  • Error state with "Retry" button shown when generation fails
  • PDF iframe shown when pdfBase64 is available

8.3 Source Records Drill-Down Panel

Route: Slide-in panel on /tax-forms/[id] (no URL change)

Data loading:

  • getSourceRecords(taxFormId, fieldName) — resolves source_map_json entries to displayable records on demand when the panel opens

Source Records Region

Side panel listing the cash_receipt_application and cash_receipt_application_deduction records contributing to the clicked form field.

Field / ColumnSourceEditable?Condition
Aggregation Type Badgesource_map_json[fieldName].aggregation (e.g., "SUM")NoVisible when records exist
Record CountCount of contributing recordsNoVisible when records exist
Total AmountSUM(record.amount)NoVisible when records exist
Source Labelrecord.label (e.g., "WS #42 - Deal Name - $10,000.00")NoPer row
Deduction Typerecord.deductionTypeCdNoVisible only when record is a deduction type
Amountrecord.amountNoPer row
Worksheet Linkrecord.href (e.g., /worksheets/42)NoVisible only when href is set

Grid features:

  • No sorting or filtering
  • Worksheet links open in a new tab

Conditional display:

  • "No source records available" message shown when no records exist for the field
  • Loading spinner shown during data fetch

8.4 Filing Package Detail Screen

Route: /tax-forms/packages/[id]

Data loading:

  • getFilingPackage(packageId) — loads the tax_filing_package record and all associated tax_form records grouped by mailing_cd into mailing1Forms and mailing2Forms arrays

Header Region

Package identity, status, and generation metadata.

Field / ColumnSourceEditable?Condition
Tax Year Labeltax_filing_package.tax_yearNoAlways visible
Status Badgetax_filing_package.status_cdNoAlways visible
Form CountTotal count of associated tax_form recordsNoAlways visible
Generated Datetax_filing_package.generated_dtNoVisible when not null

Reconciliation Check Region

Cross-form total verification table. Compares aggregate 1042-S totals against the 1042-T and Form 1042 summary forms.

Field / ColumnSourceEditable?Condition
Sum of 1042-S Grosstax_filing_package.reconciliation_json.totalGrossFrom1042SNoAlways visible
1042-T Grosstax_filing_package.reconciliation_json.form1042TGrossNoAlways visible
Form 1042 Grosstax_filing_package.reconciliation_json.form1042GrossNoAlways visible
Gross Match Indicatortax_filing_package.reconciliation_json.grossMatchNoAlways visible
Sum of 1042-S Withheldtax_filing_package.reconciliation_json.totalWithheldFrom1042SNoAlways visible
1042-T Withheldtax_filing_package.reconciliation_json.form1042TWithheldNoAlways visible
Form 1042 Withheldtax_filing_package.reconciliation_json.form1042WithheldNoAlways visible
Withheld Match Indicatortax_filing_package.reconciliation_json.withheldMatchNoAlways visible
Per-Recipient Breakdowntax_filing_package.reconciliation_json.formBreakdown arrayNoCollapsible; shown when array is non-empty

Conditional display:

  • "All Matched" badge when reconciliation_json.allReconciled = true
  • "Mismatch Detected" badge (destructive) when allReconciled = false
  • Entire reconciliation panel hidden when reconciliation_json is null

Mailing Sections Region

One section per mailing group (Mailing 1 and Mailing 2). Each section lists its forms with financial summary columns and a combined PDF download action.

Field / ColumnSourceEditable?Condition
Form Labeltax_form.form_code_cd as badgeNoPer row
Party Nametax_form.party_nameNoPer row
Grosstax_form.form_data_json.grossIncome or equivalentNoPer row
Withheldtax_form.form_data_json.federalTaxWithheld or equivalentNoPer row
Chaptertax_form.chapter_cd displayed as "Ch. 3", "Ch. 4", or "Amended"NoPer row; blank when null
Detail LinkNavigation link to /tax-forms/[tax_form_id]NoPer row

Grid features:

  • No sorting or filtering within mailing section tables
  • "Download PDF" button at mailing section header level downloads a combined PDF for all forms in that mailing

Conditional display:

  • Entire mailing section hidden when that mailing has zero forms

Electronic Filing Region

Collapsible sub-sections for FIRE file preview, MeF XML stub, and FIRE/IRIS setup instructions.

Field / ColumnSourceEditable?Condition
FIRE record structuregetFireFilePreview result (record type T, A, B, C, F rows)NoExpanded on demand
Record count and payee countfirePreview.totalRecords, firePreview.summary.payeeCountNoVisible when FIRE preview loaded
MeF XML stubgetMeFXmlStub resultNoExpanded on demand
FIRE/IRIS instructionsStatic content or firePreview.instructionsNoExpanded on demand

Conditional display:

  • Loading spinner while fetching FIRE preview or MeF XML
  • "TEST FILE" badge always visible on the FIRE preview

9. Additional Diagrams

Tax Form Status Lifecycle

mermaid
stateDiagram-v2
    [*] --> DRAFT : Form record created without data
    [*] --> GENERATED : Form created with data (typical path)
    DRAFT --> GENERATED : Refresh Data
    GENERATED --> FILED : Mark as Filed
    FILED --> SUBMITTED : Mark as Submitted
    SUBMITTED --> [*] : Terminal state

Filing Package Status Lifecycle

mermaid
stateDiagram-v2
    [*] --> GENERATED : generateAnnualFilingPackage
    GENERATED --> REVIEWED : User confirms reconciliation
    REVIEWED --> FILED : Package filed with authority
    FILED --> SUBMITTED : Authority acknowledges
    SUBMITTED --> [*] : Terminal state

**PoC Artifact:**

The REVIEWED status transition (package GENERATEDREVIEWED) is modeled in the data model but does not have a corresponding UI action in the PoC. The package detail screen shows the reconciliation result but does not provide a "Mark as Reviewed" button. Production should add this gate to block filing of packages where allReconciled = false.

IRS Annual Package Assembly Flow

mermaid
flowchart TD
    A[User: Generate Annual Package for TY XXXX] --> B[getPartiesWithWithholding\nNRA deductions WH_US_NRA\nin calendar year]
    B --> C{Parties found?}
    C -->|None| Z[Package created with\nzero 1042-S forms\n1042-T and 1042 totals = 0]
    C -->|1..N parties| D[For each party:\naggregateForPeriod\nWH_US_NRA deductions]
    D --> E[createTaxFormRecord\nIRS_1042_S\nmailing_cd = MAILING_1\nchapter_cd = CH3_ORIG]
    E --> F[aggregate1042SFormsForYear\nsum gross + withheld\nacross all new 1042-S]
    F --> G[createTaxFormRecord\nIRS_1042_T\nmailing_cd = MAILING_1\nsequence_no = 1]
    G --> H[getTaxLiabilityByPeriod\nsemi-monthly deposit schedule]
    H --> I[createTaxFormRecord\nIRS_1042\nmailing_cd = MAILING_2]
    I --> J[INSERT tax_filing_package\ncompute reconciliation_json\nstatus_cd = GENERATED]
    J --> K[Link all tax_form records\ntax_filing_package_id set]
    K --> L[Navigate user to package detail]

10. Cross-References

DocumentRelationship
Tax Withholding Data ModelDefines all tables used in this workflow: tax_form, tax_filing_package, party_tax_info, tax_rate_config, tax_calculation_audit
Tax Withholding QueriesSpecifies all data retrieval operations for form data aggregation, party discovery, and reconciliation
Tax Withholding ProceduresSpecifies all data mutation operations: form record creation, status transitions, package assembly
Worksheets WorkflowUpstream: withholding deductions (cash_receipt_application_deduction with type codes WH_US_NRA, WH_UK_FEU) are recorded during worksheet Apply. Tax form generation reads these deduction records. The worksheet detail screen also shows tax preview badges and pre-populated deduction dialogs (context type WORKSHEET_PREVIEW in tax_calculation_audit) — these previews are separate from form generation.
Settlements WorkflowIndirectly upstream: PAY settlement and payment execution do not affect tax form generation directly. The tax deductions are locked to the PAY application record, not to the settlement.
Cash Receipts WorkflowSplit-level tax warnings (context type SPLIT_WARNING in tax_calculation_audit) provide early indication that NRA or FEU withholding may apply when a party reference is added to a split. These warnings do not generate form records — they are advisory only.

11. Gherkin Scenarios

gherkin
Feature: Tax Forms - Individual Form Generation

  Scenario: Generate IRS 1042-S for a non-resident alien client with NRA withholding
    Given party "Luna Vasquez" (party_id = 101) has tax_residence_cd = 'MX' in party_tax_info with current_item_ind = true
    And worksheet W-55 has cash_receipt_worksheet_status_cd = 'A' (Approved) and applied_dt in calendar year 2025
    And worksheet W-55 has a PAY cash_receipt_application of $50,000 for billing_item.client_id = 101
    And that application has a cash_receipt_application_deduction with billing_item_deduction_type_cd = 'WH_US_NRA' and deduction_amt_applied = 15000.00
    When the user selects form type "IRS 1042-S", selects "Luna Vasquez" as the client, selects tax year 2025, and clicks "Generate Form Record"
    Then a tax_form record is inserted with form_code_cd = 'IRS_1042_S', tax_year = 2025, jurisdiction_cd = 'US'
    And tax_form.status_cd = 'GENERATED'
    And tax_form.form_data_json.grossIncome = 50000
    And tax_form.form_data_json.federalTaxWithheld = 15000
    And tax_form.source_map_json contains a 'grossIncome' entry referencing the cash_receipt_application from W-55
    And tax_form.source_map_json contains a 'federalTaxWithheld' entry referencing the cash_receipt_application_deduction record
    And tax_form.source_type_cd = 'WORKSHEET'
    And the forms queue refreshes showing the new record

  Scenario: Generate HMRC FEU2 for a UK entertainer for Q2 of the 2025 UK tax year
    Given party "James Okafor" (party_id = 202) has tax_residence_cd = 'GB' in party_tax_info
    And a PAY application of £30,000 exists on an approved worksheet with applied_dt between 2025-07-01 and 2025-09-30
    And that application has a cash_receipt_application_deduction with billing_item_deduction_type_cd = 'WH_UK_FEU' and deduction_amt_applied = 6000
    When the user selects form type "HMRC FEU2", selects "James Okafor", selects tax year 2025, selects quarter "Q2: Jul 1 – Sep 30", and clicks "Generate Form Record"
    Then a tax_form record is inserted with form_code_cd = 'HMRC_FEU2', tax_year = 2025, quarter_cd = 'Q2', jurisdiction_cd = 'GB'
    And tax_form.form_data_json.totalGrossPayment = 30000
    And tax_form.form_data_json.totalWithholding = 6000
    And tax_form.status_cd = 'GENERATED'

  Scenario: Quarter selector is required before generating HMRC FEU1
    Given the user selects form type "HMRC FEU1" and tax year 2025
    But no quarter has been selected
    When the user attempts to click "Generate Form Record"
    Then the "Generate Form Record" button remains disabled
    And the quarter dropdown is visible with the label "Quarter (UK Tax Year)"

  Scenario: Client / Payee field is hidden for HMRC FEU1
    Given the user selects form type "HMRC FEU1"
    Then the Client / Payee input field is not displayed in the generator panel

Feature: Tax Forms - Annual Filing Package

  Scenario: Generate annual IRS 1042 filing package for a year with two NRA recipients
    Given party "Elena Reyes" (party_id = 301) has WH_US_NRA deduction of $9,000 on an approved worksheet with applied_dt in calendar year 2025
    And party "Kenji Nakamura" (party_id = 302) has WH_US_NRA deduction of $4,500 on an approved worksheet in calendar year 2025
    And their gross PAY applications are $30,000 and $15,000 respectively
    When the user selects tax year 2025 in the Annual Filing Package card and clicks "Generate Annual Filing Package"
    Then a tax_filing_package record is inserted with tax_year = 2025, filing_type_cd = 'IRS_1042_ANNUAL', status_cd = 'GENERATED'
    And a tax_form record is inserted for Elena Reyes with form_code_cd = 'IRS_1042_S', mailing_cd = 'MAILING_1', chapter_cd = 'CH3_ORIG', form_data_json.grossIncome = 30000
    And a tax_form record is inserted for Kenji Nakamura with form_code_cd = 'IRS_1042_S', mailing_cd = 'MAILING_1', chapter_cd = 'CH3_ORIG', form_data_json.grossIncome = 15000
    And a tax_form record is inserted with form_code_cd = 'IRS_1042_T', mailing_cd = 'MAILING_1', sequence_no = 1, form_data_json reflecting $45,000 total gross and $13,500 total withheld
    And a tax_form record is inserted with form_code_cd = 'IRS_1042', mailing_cd = 'MAILING_2'
    And tax_filing_package.reconciliation_json.allReconciled = true
    And all four tax_form records have their tax_filing_package_id set to the new package
    And the user is navigated to the filing package detail screen

  Scenario: Reconciliation detects mismatch when 1042-T total does not match aggregate 1042-S total
    Given a tax_filing_package for TY 2024 has been generated
    And the aggregate of all 1042-S form_data_json.grossIncome values is $200,000
    But the 1042-T form_data_json.totalGrossIncome was computed as $180,000 due to a data discrepancy
    Then tax_filing_package.reconciliation_json.grossMatch = false
    And tax_filing_package.reconciliation_json.allReconciled = false
    And the Reconciliation Check panel on the filing package detail screen shows the "Mismatch Detected" badge

Feature: Tax Forms - Status Lifecycle

  Scenario: Mark a generated form as filed after IRS submission
    Given a tax_form record with tax_form_id = 88 and status_cd = 'GENERATED'
    When the user selects "Mark as Filed" from the row's overflow menu
    Then tax_form.status_cd is updated to 'FILED'
    And tax_form.filed_dt is set to approximately the current timestamp
    And the queue row reflects the updated status badge

  Scenario: Mark a filed form as submitted after IRS acknowledgement
    Given a tax_form record with tax_form_id = 88 and status_cd = 'FILED'
    When the user selects "Mark as Submitted" from the row's overflow menu
    Then tax_form.status_cd is updated to 'SUBMITTED'
    And no further status transitions are available for this record
    And the "Mark as Filed" and "Mark as Submitted" menu items are not shown

  Scenario: Filed form cannot be marked as filed again
    Given a tax_form record with tax_form_id = 88 and status_cd = 'FILED'
    When the user opens the row's overflow menu
    Then "Mark as Filed" is not shown in the menu

Feature: Tax Forms - Source Lineage Drill-Down

  Scenario: User drills into gross income to verify contributing applications
    Given tax_form_id = 77 has form_code_cd = 'IRS_1042_S' with form_data_json.grossIncome = 75000
    And source_map_json.grossIncome references two cash_receipt_application records (IDs 201 and 202) each contributing $37,500 from worksheets 10 and 11
    When the user clicks the "Gross Income" value on the form detail screen
    Then the source records panel opens
    And the panel shows aggregation type "SUM" and 2 records
    And the total badge shows $75,000.00
    And each row shows the label "WS #10 - [dealName] - $37,500.00" and "WS #11 - [dealName] - $37,500.00" respectively
    And each row has a link to its contributing worksheet

  Scenario: Refresh data re-queries actuals and updates form totals
    Given tax_form_id = 77 has status_cd = 'GENERATED' with form_data_json.grossIncome = 50000
    And since the form was generated, an additional PAY application of $10,000 has been posted on an approved worksheet for the same party_id and within the same tax period
    When the user clicks "Refresh Data" on the form detail screen
    Then the system re-aggregates PAY applications and WH_US_NRA deductions for the party and period
    And tax_form.form_data_json.grossIncome is updated to 60000
    And tax_form.source_map_json is updated to include the new application record
    And the PDF preview regenerates with the updated values

Feature: Tax Forms - Edge Cases

  Scenario: Generate form for a party with PAY applications but no withholding deductions
    Given party "Sam Bright" (party_id = 501) has PAY applications totaling $40,000 on approved worksheets in 2025
    And no cash_receipt_application_deduction records with type WH_US_NRA exist for this party in 2025
    When the user generates an IRS 1042-S for Sam Bright for TY 2025
    Then a tax_form record is created with form_data_json.grossIncome = 40000
    And form_data_json.federalTaxWithheld = 0
    And the form is generated without error

  Scenario: Generate annual package for a year with no NRA withholding activity
    Given no cash_receipt_application_deduction records with billing_item_deduction_type_cd = 'WH_US_NRA' exist on active worksheets for calendar year 2023
    When the user generates an annual filing package for TY 2023
    Then a tax_filing_package record is inserted for TY 2023
    And no IRS_1042_S forms are created
    And the IRS_1042_T and IRS_1042 forms are generated with zero gross and withholding totals
    And tax_filing_package.reconciliation_json.allReconciled = true

  Scenario: Returned worksheet applications do not contribute to form totals
    Given party "Alia Moss" (party_id = 601) has a PAY application of $20,000 on worksheet W-99
    And worksheet W-99 has cash_receipt_worksheet_status_cd = 'R' (Returned)
    And party "Alia Moss" also has a PAY application of $25,000 on worksheet W-100 with status_cd = 'A' (Approved)
    And both worksheets have WH_US_NRA deductions
    When the user generates an IRS 1042-S for Alia Moss for TY 2025
    Then tax_form.form_data_json.grossIncome reflects only the $25,000 from worksheet W-100
    And the $20,000 PAY application from the returned worksheet W-99 is not included

Confidential. For internal use only.