---
title: Phase A0 — Discovery and contract delta
last_verified: 2026-05-06
verification_type: live SOQL + screen-flow XML grep
verification_ttl_days: 30
status: complete
phase: A0
parent: plan.md
---

# Phase A0 — Discovery and contract delta

> **Purpose:** before committing to `PatientOrderIntakeService`'s class shape, validate §3 of the parent plan against (a) the screen flow's actual `<assignmentItems>` for every service-bound SObject variable, and (b) live `FieldDefinition` SOQL on the target objects. Surface what §3 got right, what it got wrong, and what's still unclear.
>
> **Method:** grep the 7,904-line screen-flow XML for `<assignToReference>{var}.` against every SObject variable the service is going to assemble; cross-reference each field against `FieldDefinition` Tooling-API SOQL on the live ClaudeTest schema; tabulate the deltas.
>
> **Verdict:** §3's contract has **multiple material errors**. The biggest is structural: `Create_Patient` does NOT create a Contact — it creates a `HealthCloudGA__EhrPatient__c` (Health Cloud managed object). The Contact is created automatically by the Health Cloud package's downstream automation. §3 had the wrong object for the patient anchor. Eight other contract additions are smaller but real — fields the screen flow sets that §3 didn't enumerate.

## §1 — What the screen flow actually writes (per SObject variable)

Extracted via grep on `<assignToReference>{var}.` against the screen-flow XML. SObject-variable assignments are spread across Assignment nodes and don't correspond to a single contiguous block.

### `Account_to_create` → `Account`

| Field                              | Source                         | Notes                                                                                                   |
| ---------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------- |
| `RecordTypeId`                     | hardcoded `0124W0000011cqUQAQ` | **Individual RT — hardcoded ID anti-pattern** (`flow.md` §3.11)                                         |
| `Name`                             | `Account_name_Formula`         | LastName, FirstName format                                                                              |
| `HealthCloudGA__IndividualType__c` | `'Group'`                      | **Missed by §3**                                                                                        |
| `HealthCloudGA__EnrollmentType__c` | `'NonDual'`                    | **Missed by §3**                                                                                        |
| `SF_Manually_Entered__c`           | `true`                         | **Missed by §3** — same flag as on Rx; same semantics ("needs post-processing"); applied to Account too |

Reuse path (existing-patient branch, line 639): `Account_to_create.Id = Case.Contact.AccountId` — when intake matches an existing Contact, reuse that Contact's Account rather than creating a new one.

### `PatientToCreate` → `HealthCloudGA__EhrPatient__c` ⚠️ **NOT Contact**

This is the load-bearing correction. `PatientToCreate` is an EhrPatient, not a Contact.

| Field                           | Source                                           | Notes                                                                       |
| ------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------- |
| `HealthCloudGA__Account__c`     | `Account_to_create.Id`                           | Lookup to Account                                                           |
| `HealthCloudGA__BirthDate__c`   | `Get_Contact_Created_by_Health_Cloud.Birthdate`  | Read from the Contact HC auto-created                                       |
| `HealthCloudGA__GenderLabel__c` | `Get_Contact_Created_by_Health_Cloud.Gender`     | Same                                                                        |
| `HealthCloudGA__Name__c`        | `Account_name_Formula`                           | Same Name formula as Account                                                |
| `HealthCloudGA__GivenName1__c`  | `Get_Contact_Created_by_Health_Cloud.FirstName`  | First name                                                                  |
| `HealthCloudGA__GivenName2__c`  | `Get_Contact_Created_by_Health_Cloud.MiddleName` | Middle name                                                                 |
| `HealthCloudGA__GivenName3__c`  | `Get_Contact_Created_by_Health_Cloud.LastName`   | Last name (note the GivenName1/2/3 → first/middle/last shape — non-obvious) |
| `Contact__c`                    | `Get_Contact_Created_by_Health_Cloud.Id`         | Custom lookup back to the paired Contact                                    |

**The patient-creation flow is 3 steps, not 1:**

1. Create the `Account` (Individual RT). Inserted, gets an Id.
2. Insert `Account` triggers downstream automation. **Health Cloud's managed-package code creates a paired `Contact` automatically.** No flow-side Contact create — verified across the screen flow.
3. `Get_Contact_Created_by_Health_Cloud` recordLookup retrieves the auto-created Contact's Id.
4. The flow updates that Contact (`Update_Contact` step) with FirstName / MiddleName / LastName / Patient_Memo\_\_c that the user typed in.
5. Then `Create_Patient` inserts the `HealthCloudGA__EhrPatient__c` linked to both the Account and the Contact.

**Implication for the Apex service:** the `intake()` method must replicate this 5-step shape, not the 1-step "create Contact" assumption in §3. Health Cloud's automatic Contact-create is a managed-package side-effect we depend on; the service can't bypass it.

### `Contact_to_create` → `Contact` (output-stage SObject variable)

This is a Contact reference, but it's not directly created. It's a renamed/reused variable that holds whichever Contact (existing or HC-auto-created) ends up being the patient.

- Existing-patient branch (line 632): `Contact_to_create.Id = Case.ContactId`
- New-patient branch (line 704): `Contact_to_create.Id = Get_Contact_Created_by_Health_Cloud.Id`

The `Update_Contact` (line 4415) record-update writes `FirstName`, `MiddleName`, `LastName`, `Patient_Memo__c` to whichever Contact `Contact_to_create` points at. Service equivalent: the resolved Contact (via Health Cloud auto-create or existing-Contact lookup) gets a follow-up update.

### `ContactPointAddress` → `ContactPointAddress` (standard object)

| Field                                      | Source                                                                                | Notes                                                                                                     |
| ------------------------------------------ | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `Name`                                     | `'Default'`                                                                           |                                                                                                           |
| `Street, City, State, Country, PostalCode` | `AddressStreet`, `AddressCity`, `AddressState`, `AddressCountry`, `AddressPostalCode` | Standard address fields                                                                                   |
| `ParentId`                                 | `Account_to_create.Id`                                                                | **Master-Detail to Account, NOT Contact** — verified live: `ParentId = Master-Detail(Individual,Account)` |
| `Contact__c`                               | `Get_Contact_Created_by_Health_Cloud.Id`                                              | Custom lookup tracking which Contact the address belongs to                                               |
| `Primary__c`                               | `true`                                                                                | First/only address marked primary                                                                         |
| `Status__c`                                | `'Active'`                                                                            | Custom picklist                                                                                           |
| `Verification_Status__c`                   | `AddressVerificationStatus` (variable)                                                | From the screen-flow's address-validation gate                                                            |
| `Unverified_Reason__c`                     | `unverifiedAddressReason` (variable)                                                  | Captured user justification when validation failed                                                        |

Live schema: ContactPointAddress has 62 fields. The screen flow writes 11 of them. Other notable fields the schema has but the screen flow doesn't write: `AddressType` (picklist), `IsPrimary` (standard SF boolean — separate from the custom `Primary__c`), `IsActive` (standard SF boolean), `Country__c` (Lookup to a Country object — separate from the standard `Country` text field), `State__c` (Lookup to State), `Verification_Service__c` (picklist — likely "USPS", "Manual", etc.), `Verification_Accuracy__c`, `Verified_By__c`, `Verification_Date_Time__c`. **`pw_ccpro` (ProvenWorks) trigger likely populates the verification fields automatically** — the screen flow only sets the manually-driven `Verification_Status__c` + `Unverified_Reason__c` for the human-entered case.

### `New_Order_case` → `Case` (the new "New Order" Case)

| Field                              | Source                         | Notes                                                                                                                                                                                    |
| ---------------------------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `RecordTypeId`                     | hardcoded `0124W000000y8NBQAY` | **Customer_Service_New_Order DeveloperName per `Case.md`** — hardcoded ID                                                                                                                |
| `ContactId`                        | `Contact_to_create.Id`         |                                                                                                                                                                                          |
| `AccountId`                        | `Account_to_create.Id`         |                                                                                                                                                                                          |
| `Status`                           | `'New'`                        |                                                                                                                                                                                          |
| `Subject`                          | `'New Order'`                  | **Missed by §3**                                                                                                                                                                         |
| `HealthCloudGA__DueDate__c`        | `$Flow.CurrentDate`            | **Missed by §3** — Health Cloud due-date field on Case                                                                                                                                   |
| `Order__c`                         | `OrderId`                      | Custom lookup back to the new Order                                                                                                                                                      |
| `New_Prescription_Order_Status__c` | `'Contact Patient'`            | **Missed by §3** — initial CS workflow state                                                                                                                                             |
| `OwnerId`                          | `CS_Case_Queue`                | ⚠️ **§3 + §9 #5 RESOLUTION ERROR — NOT Data_Entry_Queue.** The screen flow uses the Customer Service queue for new-order Case ownership, not Data Entry. Correction needed in §3 and §9. |
| `EHR_Practitioner__c`              | `Get_Prescriber.Id`            | **Distinct from Original_Case's `Prescription_1.HealthCloudGA__Prescriber__r.Id`** — see §2 corrections #6                                                                               |
| `New_Patient__c`                   | `true`                         | **Missed by §3** — flags the Case as new-patient (vs. existing-patient new-order)                                                                                                        |

### `Prescription_1`, `Prescription_2`, `Prescription_3`, `Prescription_4`, `Prescription_5` → `HealthCloudGA__EhrMedicationPrescription__c`

Identical shape across all 5 slots (only the source-variable suffix differs: `Medication1.recordId`, `Medication1_0.recordId`, `Medication1_0_0.recordId`, etc.). 17 fields per Rx:

| Field                           | Source                         | §3 status                                                                                                                                                                                                       |
| ------------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `RecordTypeId`                  | hardcoded `0124W000000y8ebQAA` | Prescription RT — hardcoded ID                                                                                                                                                                                  |
| `HealthCloudGA__DateWritten__c` | `DateWrittenRxN` (per slot)    | In §3                                                                                                                                                                                                           |
| `Product__c`                    | `MedicationN.recordId`         | In §3                                                                                                                                                                                                           |
| `Sig__c`                        | `SigN.recordId`                | In §3                                                                                                                                                                                                           |
| `RefillsAuthorized__c`          | `Refills_Authorized_N`         | In §3                                                                                                                                                                                                           |
| `Quantity__c`                   | `Quantity_N`                   | In §3                                                                                                                                                                                                           |
| `Price__c`                      | `0.0` (literal)                | **Missed by §3** — initialized to zero, presumably set later by `B2BProductPricingService` flow                                                                                                                 |
| `Date_filled__c`                | `$Flow.CurrentDate`            | **Missed by §3** — note typo'd lowercase `d` (`Date_filled__c` per Case.md typo catalog)                                                                                                                        |
| `SF_Manually_Entered__c`        | `true`                         | In §3 (resolved §9 #1)                                                                                                                                                                                          |
| `HealthCloudGA__Account__c`     | `Account_to_create.Id`         | **Missed by §3** — Rx → Account lookup                                                                                                                                                                          |
| `HealthCloudGA__Patient__c`     | `PatientId` (variable)         | In §3 — points at the EhrPatient                                                                                                                                                                                |
| `HealthCloudGA__Prescriber__c`  | `Prescriber_N.recordId`        | In §3                                                                                                                                                                                                           |
| `Contact__c`                    | `Contact.Id`                   | **Missed by §3** — separate Contact lookup, not just `HealthCloudGA__Patient__c`                                                                                                                                |
| `Order__c`                      | `OrderId`                      | **Missed by §3** — Rx → Order custom lookup                                                                                                                                                                     |
| `Rx_Image__c`                   | `Case.Rx_Image__c`             | **Missed by §3** — Rx points back to staging image (in addition to Order pointing at it)                                                                                                                        |
| `Prescriber_ID__c`              | `Prescriber_N.recordId`        | **Missed by §3** — Text(255), separate from `HealthCloudGA__Prescriber__c` Lookup. Likely a denormalized cache field for reporting.                                                                             |
| (no field)                      | —                              | `Patient_Fill_Id__c` (External ID, unique) is NOT set by the screen flow — populated by `HashUtils` per `EhrMedicationPrescription.md`. The `New_Prescriptions_Manually_Entered` flow generates it post-insert. |

### `pharmacyNoteForCSCase` → `Pharmacy_Note__c`

Two distinct uses, both with hardcoded RT id `0124W000000y8inQAA` = **`Customer_Service`** RT (verified live 2026-05-06):

| Use              | Name                     | Full_Note\_\_c source                | Case\_\_c source    |
| ---------------- | ------------------------ | ------------------------------------ | ------------------- |
| Cart-active note | `'Active Portal Cart'`   | `pharmacyNoteCartForCS` (variable)   | `New_Order_case.Id` |
| Data-entry note  | `'Note from Data Input'` | `Note_for_New_Order_CAse` (variable) | `New_Order_case.Id` |

Plus `Duplicate_Rx_pharmacy_note` (separate inline create at line 3589) with same hardcoded `Customer_Service` RT id, `Name='Duplicate Order'`, `Case__c=Case.Id` (the original staging Case, not the new-order Case).

**All three Notes correctly route to the `Customer_Service` RT.** Live SOQL on `RecordType WHERE SobjectType='Pharmacy_Note__c'` confirms the object has only 2 RTs — `Customer_Service` (Id `0124W000000y8inQAA`) and `Pharmacist` (Id `0124W000000y8iiQAA`). For CS-bound Notes (vs. pharmacist-bound), `Customer_Service` is the right RT. Apex service replicates: `Schema.SObjectType.Pharmacy_Note__c.getRecordTypeInfosByDeveloperName().get('Customer_Service').getRecordTypeId()` — never the hardcoded Id.

## §2 — Corrections needed in the parent plan §3

In priority order (load-bearing first):

### 1. ⚠️ `Create_Patient` creates EhrPatient, not Contact

**§3 currently says:** the new-patient path creates a `Contact` (Patient RT) directly via `inputReference=PatientToCreate`.

**Reality:** the path is `Account` insert → Health Cloud package creates paired `Contact` automatically → flow looks up the auto-created Contact → flow updates it (FirstName/MiddleName/LastName/Patient_Memo**c) → flow inserts the `HealthCloudGA**EhrPatient\_\_c`via`inputReference=PatientToCreate`.

**Service implication:** `resolvePatient()` for a new patient is at least 4 SObject operations: insert Account, query for HC-auto-created Contact, update Contact, insert EhrPatient. NOT a single Contact insert.

**Cross-cut impact:**

- §3 schema for "Contact (Patient RT)" — Patient_Memo\_\_c is the only non-trivial AdvancedRx-added field set by the flow; everything else is standard.
- §3 was missing the EhrPatient row entirely.
- The `IntakeRequest.patient` block in §2 needs to map to BOTH Contact-update fields AND EhrPatient-create fields.

### 2. ⚠️ New-Order Case OwnerId = `CS_Case_Queue`, NOT `Data_Entry_Queue`

**§9 resolved-decision #5** says Cases route to Data Entry Queue. **The screen flow disagrees** — it routes to `CS_Case_Queue` (Customer Service queue) for the new-order Case.

**Why this matters:** Data Entry Queue and CS Queue are different teams. Data Entry transcribes inbound; CS handles patient outreach. The new-order Case is **CS work** ("Contact Patient" is its initial New_Prescription_Order_Status\_\_c) — DE has already done their part by the time this Case is created.

**Correction:** §3 should specify `OwnerId` = `CS_Case_Queue` lookup (`Group.DeveloperName = ?` — needs verification, see "Open questions"). Update §9 #5 resolution accordingly. The closed staging Case keeps DE-related ownership; the NEW-order Case routes to CS.

### 3. Account fields missed

§3 didn't enumerate these required-on-create fields:

- `HealthCloudGA__IndividualType__c='Group'`
- `HealthCloudGA__EnrollmentType__c='NonDual'`
- `SF_Manually_Entered__c=true`

The Health Cloud Individual-RT Account fields are managed-package fields with semantic meaning (the package may behave differently for non-Group / non-NonDual values). Service should set these to match the screen flow exactly until we have a reason to change.

### 4. Rx field surface is bigger than §3 documented

§3 listed 9 fields. Reality is 17. Fields to add:

- `Order__c` — Rx → Order custom lookup
- `Contact__c` — Rx → Contact (separate from `HealthCloudGA__Patient__c`)
- `HealthCloudGA__Account__c` — Rx → Account
- `Prescriber_ID__c` — Text(255), denormalized prescriber Id
- `Date_filled__c` — Date, $Flow.CurrentDate (note typo'd lowercase `d`)
- `Price__c` — Currency(16,2), initialized to 0.0
- `Rx_Image__c` — Rx → Rx_Image\_\_c custom lookup

### 5. New-Order Case fields missed

- `Subject='New Order'`
- `HealthCloudGA__DueDate__c=$Flow.CurrentDate`
- `New_Prescription_Order_Status__c='Contact Patient'` (initial CS workflow state)
- `New_Patient__c=true` (boolean flag for new-patient path)
- `EHR_Practitioner__c` from `Get_Prescriber.Id` (NOT `Prescription_1.HealthCloudGA__Prescriber__r.Id` — see correction #6)

### 6. ⚠️ `Case.EHR_Practitioner__c` source — TWO different values, not one

§3 says "from Rx 1's prescriber — preserve this convention." That's only half-right.

**The Original_Case (closed staging) update** (line 4287) sets `EHR_Practitioner__c = Prescription_1.HealthCloudGA__Prescriber__r.Id`. ✓ Matches §3.

**The new-order Case create** (line 1051) sets `EHR_Practitioner__c = Get_Prescriber.Id`. ✗ Different source — uses the prescriber lookup the user picked at intake (`Get_Prescriber` is a recordLookup against `HealthCloudGA__EhrPractitioner__c` filtered by some user-input variable), not the value pulled off Rx 1.

In single-prescriber cases these are the same value (resolved §9 #8). But the data-flow shape is different — the staging Case looks at the Rx after creation, the new-order Case looks at the prescriber selection directly. Service should make this explicit, not collapse them.

### 7. ContactPointAddress parents to Account, not Contact

§3 schema implied `ParentId` = Contact. **Live FieldDefinition confirms `ParentId = Master-Detail(Individual,Account)`.** The screen flow correctly sets `ParentId = Account_to_create.Id`. Custom `Contact__c` lookup is a separate field tracking which Contact the address relates to — but the Master-Detail parent IS the Account.

### 8. Pharmacy_Note "Active Portal Cart" path missed

§3 documented the "Duplicate Order" Note path only. The screen flow has TWO MORE Note paths (cart-active + data-entry-from-data) that §3 missed. All three correctly use the `Customer_Service` RT (verified — see resolved §6 #1).

## §3 — Live FieldDefinition findings (selective)

### Order required fields (IsNillable=false on user-supplied fields)

Live schema confirms the screen flow's writes cover the required surface:

- `EffectiveDate` — Date, required ✓ flow sets
- `Status` — Picklist, required ✓ flow sets
- `TotalAmount` — Currency, required (auto-rolled from OrderItems normally; 0 on draft Orders is fine)
- `SF_Direct_Rx__c` — Checkbox, required ✓ flow sets `true`
- `Skip_Quarantine_Check__c` — Checkbox, required ✓ flow sets `true`

No required Order field is being skipped by the screen flow. Phase A risk: low.

### Rx required fields

- `SF_Manually_Entered__c` — Checkbox, required ✓ flow sets `true`

That's the only required user-supplied field on Rx (all the FK lookups are nillable). Phase A risk: low.

### ContactPointAddress required fields (user-supplied)

- `Name` — Text(255), required ✓ flow sets `'Default'`

(All other required fields are system fields like `Id`, `OwnerId`, audit fields.)

### Cross-entity FieldDefinition queries failed

`SELECT … FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName IN (…)` returns "Disjunctions not supported" / "operation not yet supported by this sObject storage type". Each object must be queried individually. Per-object queries succeed.

For Phase A, if we want a complete required-field audit per object, run 9 separate queries (one per service-bound object). For now, spot-checks above are sufficient to validate §3.

## §4 — Hardcoded RT IDs catalog (for Phase A retrofit)

The screen flow hardcodes 4 RT IDs. All must be replaced with `Schema.SObjectType.X.getRecordTypeInfosByDeveloperName().get('...').getRecordTypeId()` lookups in the Apex service.

| Object                                      | RT ID (literal in flow) | DeveloperName                              | Source                                                         |
| ------------------------------------------- | ----------------------- | ------------------------------------------ | -------------------------------------------------------------- |
| Account                                     | `0124W0000011cqUQAQ`    | Individual (presumed)                      | Account_to_create assignment, line 304                         |
| Case                                        | `0124W000000y8NBQAY`    | `Customer_Service_New_Order` per `Case.md` | New_Order_case assignment, line 991                            |
| HealthCloudGA**EhrMedicationPrescription**c | `0124W000000y8ebQAA`    | Prescription                               | Prescription_1..5 assignments                                  |
| Pharmacy_Note\_\_c                          | `0124W000000y8inQAA`    | `Customer_Service` (verified §6 #1)        | pharmacyNoteForCSCase + Duplicate_Rx_pharmacy_note assignments |

## §5 — Risks surfaced by discovery (not in §8 of the parent plan)

### A. Health Cloud package automation is load-bearing for Contact creation

The Apex service depends on the Health Cloud managed package automatically creating a paired Contact when an Account (Individual RT) is inserted. **If the Health Cloud package version changes or this auto-create behavior changes, the entire patient-creation path breaks silently.** This needs to be:

- Explicitly noted in `business-context/integrations/azure-integration.md` Hazard list
- Pinned in the Phase A test plan — every test of the new-patient path must verify the Contact got auto-created within the same transaction

### B. `<runInMode>SystemModeWithoutSharing</runInMode>` may be load-bearing for HC auto-create

The screen flow runs in system mode without sharing. The Health Cloud package's Account-trigger automation that creates the Contact may rely on this — package code might check `UserInfo.getUserType()` or similar and skip the Contact create if the running user is integration-class with restricted profile.

**Phase A test:** insert an Account from the Apex service (`with sharing`, running as Azure Integration User profile) and verify the Contact gets auto-created. If it doesn't, either:

- (i) widen the Azure Integration User profile permissions
- (ii) flip the service to `without sharing` at the Account-insert step
- (iii) abandon the Health-Cloud-auto-create path and create the Contact explicitly (changes the contract)

This is a non-trivial design point. §8 risk #1 (sharing keyword decision) needs to fold this in.

### C. The `Prescriber_ID__c` Text(255) on Rx is undocumented

Why does Rx have BOTH `HealthCloudGA__Prescriber__c` (Lookup) and `Prescriber_ID__c` (Text(255)) holding the same Id? Likely a denormalized field for reporting — but if it's expected to stay in sync with the lookup, the service has to write both. Worth confirming with Marissa or grep for what reads this field.

### D. Multiple parallel relationships from Rx to the patient

Rx has THREE separate relationships pointing at patient-side records:

- `HealthCloudGA__Patient__c` → EhrPatient
- `HealthCloudGA__Account__c` → Account
- `Contact__c` → Contact

All three are populated on Rx insert. If they ever drift (Rx points at one Contact's EhrPatient but a different Contact's Contact), the data is inconsistent. The service must populate all three from the same patient-resolution result.

### E. Existing-patient reuse path branches Account_to_create

When the staging Case already has a `Case.ContactId` (existing-patient match — Phase 1 AI populated it OR DE selected an existing Contact), the screen flow sets `Account_to_create.Id = Case.Contact.AccountId`. The variable named "Account_to_create" then points at an EXISTING Account, not a to-be-created one. **Naming is misleading.** The Apex service should name the resolved-patient block clearly enough that this isn't ambiguous.

## §6 — Open questions surfaced

These don't block Phase A but should be answered before/during it.

### Resolved 2026-05-06 (live SOQL + grep)

1. ~~Pharmacy_Note\_\_c RT `0124W000000y8inQAA`~~ — **Resolved.** Live SOQL: `Pharmacy_Note__c` has only TWO record types — `Customer_Service` (Id `0124W000000y8inQAA`) and `Pharmacist` (Id `0124W000000y8iiQAA`). All three Note paths (Active Portal Cart, Note from Data Input, Duplicate Order) correctly route to the `Customer_Service` RT — that's the right RT for CS-bound Notes (vs. pharmacist-bound). **Synthesis-error correction:** §1 + §4 of this report previously called the RT "Duplicate Order" — that was wrong; "Duplicate Order" is just the Note's `Name` value, not the RT. The RT is `Customer_Service`. §1 + §4 corrected inline. The hardcoded-RT-Id is still an anti-pattern (use `RecordType.DeveloperName='Customer_Service'`), but the value is correct.
2. ~~What is `Prescriber_ID__c` on Rx for?~~ — **Resolved.** Grep finds 7 references: 6 active flows write or read it (`New_Patient_New_Order_New_Rx_New_Case_Launch_from_data_case`, `New_Prescriptions_and_New_Order_Case`, `New_Prescriptions_Manually_Entered`, `Fill_Prescription_s`, `Fill_Decrementing`, `Advanced_Rx_Prescription_Insert_Update_Same_Record`) plus 1 dead NewLeaf class (`RxJob.cls`). **Field is load-bearing**, not vestigial. Apex service must populate it on every Rx insert (matching the screen flow's behavior). What each downstream flow does with it is out of Phase A0 scope.
3. ~~Confirm `CS_Case_Queue` exact `DeveloperName`~~ — **Resolved.** `Group.DeveloperName = 'CS_Case'` (Name "CS Case"; Id `00G4W000005DwnpUAC`). **Worse-than-expected anti-pattern found:** the screen flow stores the queue Id in a `<constants>` block named `CS_Case_Queue` with hardcoded 15-char Id `00G4W000005Dwnp` (line 2307 of the flow XML) — `flow.md` §3.11 anti-pattern, missed-dedup variant. Apex service should look up the Group: `[SELECT Id FROM Group WHERE Type='Queue' AND DeveloperName='CS_Case' LIMIT 1]`, never hardcode the Id.
4. ~~Same for `Data_Entry_Queue`~~ — **Resolved.** `Group.DeveloperName = 'Data_Entry'` (Name "Data Entry"; Id `00G4W000005DwnuUAC`). **Note:** DeveloperName is `Data_Entry`, NOT `Data_Entry_Queue` — the screen flow's variable suffix `_Queue` is variable naming, not the underlying DeveloperName. Unlike the CS_Case case, the screen flow looks Data_Entry_Queue up via a recordLookup (line 3719), not a hardcoded constant — clean §3.11 reference.

### Still open

5. **Does the Health Cloud package auto-create the paired Contact in user mode?** Phase A test (§5 risk B above).
6. **`HealthCloudGA__IndividualType__c='Group'` and `HealthCloudGA__EnrollmentType__c='NonDual'` — what do these values mean?** Health Cloud managed-package picklists. Confirm these are the right values for AdvancedRx patient Accounts (likely yes, since the screen flow uses them in production).
7. **`OrderId` linkage on Rx — where is `OrderId` first set in the flow?** It's an output variable from `Create_Order`'s `assignRecordIdToReference=OrderId`. Apex equivalent: capture `Order.Id` after insert. Trivial; mentioned for completeness.

## §7 — Recommended next moves

1. **Update §3 of the parent plan** with corrections from §2 above. Major: replace "Contact" with "Account → Contact (HC auto-created) → EhrPatient" 5-step shape; correct OwnerId for new-order Case; add the 8 missed Rx fields, 4 missed Account fields, 4 missed Case fields, the CPA ParentId fact, and the second Pharmacy_Note path.
2. **Update §9 resolution #5** — split into "Cases-to-which-queue" by Case kind:
   - New-Order Case → CS_Case_Queue (Customer Service)
   - Closed staging Case → keep current Owner (or document as no-change)
   - Other records → Azure Integration User (unchanged)
3. **Add to §8 risks** — risks A and B from §5 above (Health Cloud auto-create dependency + sharing-mode interaction).
4. **Add a §3 sub-section** on "the existing-patient reuse path" — when `Case.ContactId` is non-null on Azure-written Case (Phase 1 AI match landed pre-populated), the patient-resolution branch reuses the existing Contact + Account, doesn't create new ones. The service must support both branches.
5. ~~Run the 5 SOQL queries~~ — **Done 2026-05-06.** Resolutions in §6 questions 1–4. Net new finding: the screen flow's `CS_Case_Queue` is hardcoded as a `<constants>` block with the literal Group Id (line 2307) — Apex service must look up `Group.DeveloperName='CS_Case'` to avoid propagating the anti-pattern.

## §8 — What this discovery did NOT cover

Out of scope for Phase A0; these become Phase A or Phase A1 tasks. **Round 2 (2026-05-06) closed many of these — see §9 below.**

- ~~OrderItem field surface~~ — **Resolved §9.1.**
- ~~Validation Rules per object~~ — **Resolved §9.2.**
- ~~Pricing-loop mechanics~~ — **Resolved §9.3.**
- ~~Cart-linkage path~~ — **Resolved §9.4.**
- ~~Account / ContactPointAddress trigger surface~~ — **Surveyed §9.5.**
- **EhrPractitioner create vs. lookup.** The screen flow always uses `Get_Prescriber` (existing-prescriber lookup). It does NOT create new prescribers. If the Apex service needs to handle "prescriber not in roster" — what's the fallback? **Still open.**
- **The 12 Case-flow + 4 Rx-flow record-update side effects.** Each flow is its own XML to crack open. Surface-level: `Automation_on_New_Refills` and `Fill_Decrementing` both contain 5+ `<recordUpdates>` (verified via grep), so they DO write fields on Rx insert. What fields, and to what records, is Phase A territory — flag at runtime via test failures rather than enumerate now.
- **Picklist value enumeration.** `Status__c` on CPA, `New_Prescription_Order_Status__c` on Case, `Status` on Order — the screen flow uses specific values; verifying they're valid picklist entries (not deactivated, restricted-picklist-allowed) is a Phase A deliverable.
- **`Pharmacy_Note__c` field surface beyond the 3 the flow sets.** Service may want to set additional Note metadata (e.g., visibility flags, type). Not blocking Phase A; can be tightened later.

## §9 — Round 2 findings (2026-05-06)

User pushback ("are you sure there's not more stones to be turned over?") was right — a second pass turned up substantial additional material. This section captures the round-2 deltas.

### §9.1 — OrderItem + Fill field contracts (extracted from `New_Prescriptions_Manually_Entered`)

The Apex service does NOT create OrderItems or Fill records directly. They're created by the downstream `New_Prescriptions_Manually_Entered` flow that fires post-Rx-insert when `SF_Manually_Entered__c=true` (resolved §9 #1). Reading that flow gives the full contract for both records.

**`Create_Fill` contract** (creates a Fill = `HealthCloudGA__EhrMedicationPrescription__c` RT=Fill — 17 fields):

| Field                              | Source                                                            | Notes                                                                                                                                                          |
| ---------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `RecordTypeId`                     | hardcoded `0124W000000y80wQAA`                                    | **5th hardcoded RT id surfaced — Fill RT**                                                                                                                     |
| `Contact__c`                       | `$Record.Contact__c` (the Master Rx)                              |                                                                                                                                                                |
| `HealthCloudGA__Account__c`        | `$Record.HealthCloudGA__Account__c`                               |                                                                                                                                                                |
| `HealthCloudGA__Patient__c`        | `$Record.HealthCloudGA__Patient__c`                               |                                                                                                                                                                |
| `HealthCloudGA__Prescriber__c`     | `$Record.HealthCloudGA__Prescriber__c`                            |                                                                                                                                                                |
| `HealthCloudGA__MedicationName__c` | `$Record.Product__r.Name`                                         | Cached Product name                                                                                                                                            |
| `Date_filled__c`                   | `$Record.Date_filled__c`                                          | Note typo                                                                                                                                                      |
| `Days_supply__c`                   | `$Record.Days_supply__c`                                          |                                                                                                                                                                |
| `Dosage_Form__c`                   | `$Record.Dosage_Form__c`                                          |                                                                                                                                                                |
| `NL_Prescription__c`               | `$Record.Id`                                                      | **Fill → Master Rx custom FK** — name suggests NewLeaf legacy but is in active use as the parent-pointer. Master Rx side has a corresponding lookup somewhere. |
| `Order__c`                         | `$Record.Order__c`                                                |                                                                                                                                                                |
| `Prescriber_ID__c`                 | `$Record.Prescriber_ID__c`                                        |                                                                                                                                                                |
| `Prescription_Number__c`           | `Rx_Number_Formula` (= `VALUE($Record.Rx_Number_Auto_Number__c)`) | Numeric Rx number                                                                                                                                              |
| `Product__c`                       | `$Record.Product__c`                                              |                                                                                                                                                                |
| `Quantity__c`                      | `$Record.Quantity__c`                                             |                                                                                                                                                                |
| `Sig__c`                           | `$Record.Sig__c`                                                  |                                                                                                                                                                |
| `Strength__c`                      | `$Record.Strength__c`                                             |                                                                                                                                                                |

**`Patient_Fill_Id__c` is populated separately**, by an Apex `HashUtils.recordIds` invocable called from `Generate_Prescription_ID` action — runs BEFORE the Fill insert and populates the master Rx's `Patient_Fill_Id__c` (the External ID per `EhrMedicationPrescription.md`).

**`Create_Order_Product` contract** (16 fields on OrderItem):

| Field                  | Source                                | Notes                                                                                |
| ---------------------- | ------------------------------------- | ------------------------------------------------------------------------------------ |
| `OrderId`              | `Get_Order.Id`                        |                                                                                      |
| `PricebookEntryId`     | `PriceBookEntryId` (variable)         | Either looked up from existing PricebookEntry or a freshly-created one               |
| `Product2Id`           | `$Record.Product__r.Id`               |                                                                                      |
| `Quantity`             | `$Record.Quantity__c`                 |                                                                                      |
| `UnitPrice`            | `1.0` (literal)                       | **Always 1.0** — actual price lives in `TotalLineAmount` and `ListPrice`             |
| `ListPrice`            | `ListPrice` (variable)                | From PricebookEntry's UnitPrice OR `$Record.Price__c` if creating new PricebookEntry |
| `TotalLineAmount`      | `$Record.Price__c`                    | **Per-Rx price set on Master Rx** is what flows through to OrderItem                 |
| `Sig__c`               | `$Record.Sig__c`                      |                                                                                      |
| `Full_Sig_New_Leaf__c` | `$Record.Full_Sig_New_Leaf__c`        | NewLeaf-named field                                                                  |
| `Prescription_Link__c` | `Create_Fill` (Fill record reference) | OrderItem → Fill custom FK                                                           |
| `RefillId__c`          | `Get_Fill.Patient_Fill_Id__c`         | OrderItem holds the Fill's External ID for cross-system correlation                  |
| `ServiceDate`          | `Get_Order.EffectiveDate`             |                                                                                      |
| `Type`                 | `'Order Product'`                     | Standard Salesforce OrderItem.Type                                                   |

**Side path: PricebookEntry auto-create** when none exists for the Product — flow inserts a fresh `PricebookEntry` with **hardcoded `Pricebook2Id = '01s4W000005JCZUQA4'`** (the default Standard Pricebook), `IsActive=true`, `UnitPrice=0.0`. Yet another hardcoded-Id anti-pattern; service must look up Pricebook by Name (typically "Standard Price Book") instead.

**Implication for the Apex service:** if we set `SF_Manually_Entered__c=true` (resolved §9 #1), this entire flow runs after each Rx insert and creates the Fill + OrderItem. The service does NOT need to replicate the contract — but anyone refactoring this path later (e.g., Phase E "service owns Fill+OrderItem creation directly") will need this material.

### §9.2 — Validation Rules audit

Live SOQL on the 11 service-bound objects, 2026-05-06. **38 active VRs total**; risk distribution:

| Object                                           | Active VRs | Phase A risk                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ------------------------------------------------ | ---------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Account                                          |          5 | **Medium** — `Phone_10_Characters` + `Fax_10_Characters` will fail Apex inserts if phone/fax aren't 10 chars. Owner-change VRs (CS Users, Sales Reps, Sales Mgr) don't block creation by integration user.                                                                                                                                                                                                                                         |
| Contact                                          |          7 | **HIGH** — five phone format VRs (`Primary_Phone_10_Characters`, `Mobile_Phone_10_Character_Limit`, `Home_Phone_10_Characters`, `Other_Phone_10_Character_Limit`, `Secondary_Phone_10_Characters`) + `Primary_Fax_10_Characters`. **Service must format phones to 10 chars before inserting/updating Contact.** Plus `Owner_Cannot_Be_Changed_For_B2B_Contact` and `Sales_Reps_Cannot_Change_Ownership` — owner restrictions, not insert blockers. |
| ContactPointAddress                              |          0 | None.                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Order                                            |          4 | **Low** — `Cannot_Revert_Status`, `Issue_Detected_Status_Restriction`, `Restrict_Shipped_PostedToTaxJar`, `Restrict_Shipping_Address_Updates`. None block Draft Order creation.                                                                                                                                                                                                                                                                    |
| OrderItem                                        |          1 | **HIGH** — **`Prevent_Manual_Edits`**. Bypass mechanism: set `Validation_Bypass_Date_Time__c = $Flow.CurrentDateTime` (or `Datetime.now()` in Apex) on every OrderItem update. **Without this, all OrderItem updates fail.** See §9.3.                                                                                                                                                                                                             |
| Case                                             |          1 | **Low** — `Restrict_Case_Ownership_Changes`. Restricts post-create owner change. Insert OK; subsequent OwnerId update via the staging-Case-finalize step might trip it. Test required.                                                                                                                                                                                                                                                             |
| HealthCloudGA**EhrMedicationPrescription**c (Rx) |          3 | **Low** for inserts — all three are "cannot change" VRs (`Can_not_change_prescription_record_type`, `Can_not_change_product_on_pres_rec_type`, `Total_Quantity_Filled_Exceed_Quantity`). The first has the User-Id-bypass anti-pattern (`$User.Id <> '0054W00000CIdd2QAD'` per `EhrMedicationPrescription.md`).                                                                                                                                    |
| HealthCloudGA**EhrPatient**c                     |          0 | None. Confirms `EhrPatient.md`.                                                                                                                                                                                                                                                                                                                                                                                                                    |
| HealthCloudGA**EhrPractitioner**c                |          3 | **Medium** — `NPI_Must_Be_10_Digits`, `Must_Be_10_Digits_or_Blank`, `Numbers_Only`. Service is currently always-lookup-not-create on EhrPractitioner (deferred per §8), so these don't fire for Phase A. If "prescriber not in roster" handling lands later, service must format/validate NPI.                                                                                                                                                     |
| Pharmacy_Note\_\_c                               |          0 | None.                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Rx_Image\_\_c                                    |          0 | None.                                                                                                                                                                                                                                                                                                                                                                                                                                              |

**Top action items for Phase A from this audit:**

1. **Phone formatting helper** — every phone field on Contact (5 of them) must be 10 chars. Build a helper, apply on all Contact inserts/updates.
2. **OrderItem Validation_Bypass_Date_Time\_\_c set on every OrderItem update.** Document this in the service contract.
3. Test the staging-Case OwnerId reassignment (resolved §9 #5 sets it to `CS_Case_Queue` Group; `Restrict_Case_Ownership_Changes` may fire — verify in test).

### §9.3 — Pricing-loop mechanics

The screen flow's pricing path (`Loop_Fills_for_Price` + nested `Loop_Order_Products`) computes prices via `B2BProductPricingService` (already known) and writes them to BOTH the Fill record AND the matching OrderItem.

**`Set_Price_on_Current_Fill_and_OP`** assigns to the looped record references — these become the `colFillsToUpdate` + `colOrderProductsToUpdate` collections that `Update_Fills` + `Update_Order_Products` then bulk-DML.

**Per-iteration assignments:**

| Target    | Field                                | Value                                                                                   |
| --------- | ------------------------------------ | --------------------------------------------------------------------------------------- | ---------------------------- |
| Fill      | `Calculated_Price__c`                | `calcCalculatedPriceforFill` (computed from `B2BProductPricingService`)                 |
| Fill      | `Price__c`                           | `calcPriceforFill` (= per-Rx price, possibly different from Calculated when overridden) |
| OrderItem | `ListPrice`                          | `calcPriceforOrderProduct`                                                              |
| OrderItem | `UnitPrice`                          | `1.0` (literal — always)                                                                |
| OrderItem | `TotalLineAmount`                    | `calcPriceforOrderProduct`                                                              |
| OrderItem | **`Validation_Bypass_Date_Time__c`** | `$Flow.CurrentDateTime`                                                                 | **VR bypass — load-bearing** |

**The pricing-recalc-skip path** (`Fill_Has_Custom_Pricing` decision): if `Loop_Fills.Price__c != Loop_Fills.Calculated_Price__c` OR `skipPricingRecalculation=true`, **skip the recalculation for that Fill**. This is an explicit "respect the user's manual price override" path. The Apex service must honor it — when Master Rx `Price__c` is set to a value other than the freshly-computed Calculated_Price\_\_c, leave it alone.

**Implication for the Apex service:** `applyPricing(orderId)` must:

1. Query Fills + OrderItems on the Order.
2. Call `B2BProductPricingService` to compute fresh prices.
3. For each Fill, decide skip-vs-update based on the override-detection logic above.
4. Update Fill (`Calculated_Price__c`, `Price__c`) and matching OrderItem (`ListPrice`, `UnitPrice=1.0`, `TotalLineAmount`, `Validation_Bypass_Date_Time__c=Datetime.now()`).

### §9.4 — Cart-linkage mechanics

When patient already has an active WebCart with prescription CartItems, the screen flow does NOT modify the cart. It produces a `Pharmacy_Note__c` describing the cart contents for CS visibility, then continues.

**Flow** (`Get_Active_Cart` → `Has_Cart` → `Get_Prescription_Cart_Items` → `Has_Prescription_Cart_Items` → `Loop_Rx_Cart_Items` → `Cart_Disclaimer` screen → `Initialize_Cart_Note` → `Create_Pharmacy_Note_for_Cart`):

- `Get_Active_Cart`: `WebCart WHERE AccountId = Contact.AccountId AND Status IN ('Active', 'Checkout') LIMIT 1`. Filter logic: `1 AND (2 OR 3)`.
- `Get_Prescription_Cart_Items`: `CartItem WHERE CartId = Get_Active_Cart.Id AND Prescription_Link__c != null`.
- `Loop_Rx_Cart_Items` body: builds a text template (`textCartItems`) by appending each cart item's `Name`. No DML in the loop body.
- After loop: `Cart_Disclaimer` screen — DE user types a `pharmacyNoteCartForCS` note describing the cart situation (default text: "At the time this order was created or updated, this patient had the following prescription(s) in their cart, but had not paid for them yet: {!textCartItems}").
- `Create_Pharmacy_Note_for_Cart` inserts a Pharmacy_Note (`Customer_Service` RT — resolved §6 #1) with `Name='Active Portal Cart'`, `Full_Note__c=pharmacyNoteCartForCS`, `Case__c=New_Order_case.Id`.

**Apex service equivalent:**

1. Query active WebCart.
2. If cart exists with prescription CartItems: build the note text from cart-item names, create a `Pharmacy_Note__c` with `Name='Active Portal Cart'` and a payload-supplied (or default-templated) `Full_Note__c`. Do NOT modify cart items.
3. If no cart or no Rx CartItems: skip cleanly.

The DE-team-typed `pharmacyNoteCartForCS` becomes a payload-optional field on the new `IntakeRequest.notes` block. If Azure-driven path doesn't supply it, use the templated default.

### §9.5 — Account + ContactPointAddress trigger surface (Gap 6)

**Account triggers:** zero AdvancedRx-authored triggers. One DLRS-managed trigger (`dlrs_AccountTrigger`). All Account-side custom logic is flow-driven.

**Account record-triggered flows** (4 active):

- `Account_Insert_Update_Same_Record` (BeforeSave canonical)
- `Account_Insert_Update_Related_Records` (AfterSave canonical)
- `Account_Address_Updates_Contact_Address` (likely cross-syncs Account billing address to Contact mailing address — Account doesn't have an address in this flow's writes, so likely benign for the service's Account-Individual-RT case)
- `Account_Change_Ownership` (presumably entry-criteria-gated on owner change — service inserts as integration-user, doesn't change owner, should be benign)

**ContactPointAddress triggers:** `ContactPointAddressTrigger` (AdvancedRx-authored, calls `pw_ccpro.CountryValidator2.Validate` per CLAUDE.md) + `dlrs_ContactPointAddressTrigger` (DLRS managed).

**ContactPointAddress record-triggered flows** (2 active): `Contact_Point_Address_Insert_Update_Same_Record` + `_Related_Records` (canonical pair).

**The Health Cloud package's auto-Contact-create** (the 5-step chain) is package-managed code — not a flow or trigger we author. Documented in `business-context/object-purpose-map.md` per the prior business-context PR.

**Implication for the Apex service:** the side effects of inserting Account → Health Cloud auto-creates Contact → service then queries for Contact, updates it, inserts EhrPatient + ContactPointAddress + Order + Rxes. Each of these inserts fires its own canonical Same/Related pair. Most are benign; the Account-side address-cross-sync might update the (HC-auto-created) Contact's mailing address to match Account billing — confirm in Phase A test.

### §9.6 — New corrections / hazards / risks

**Corrections to §3 of the parent plan README** (in addition to those already enumerated in §2 of this report):

- **Add OrderItem to the `IntakeResponse.recordIds` list.** Service doesn't create them directly but downstream flow does; consumers will want the Ids.
- **Add Fill to the response.** Same reasoning. Plus: querying for Fills + OrderItems post-insert is required for the pricing-loop step.
- **Add `Validation_Bypass_Date_Time__c` to OrderItem update contract** — load-bearing for VR bypass.
- **Add Pricebook2Id lookup** to the service's prerequisites — should be `[SELECT Id FROM Pricebook2 WHERE Name = 'Standard Price Book' LIMIT 1].Id`, not hardcoded `01s4W000005JCZUQA4`.
- **Add 5th hardcoded RT id to §4 catalog** — Fill RT `0124W000000y80wQAA` set by `New_Prescriptions_Manually_Entered.Create_Fill`.

**New hazards (additions to §5):**

- **Phone format VRs on Contact are HIGH-impact.** Five phone fields, all 10-char-required. Service must format/validate phones before insert. Stripping non-digits then verifying length 10 is sufficient based on VR names. Build a helper.
- **OrderItem `Prevent_Manual_Edits` VR is HIGH-impact for any post-pricing OrderItem update.** Service must set `Validation_Bypass_Date_Time__c = Datetime.now()` on every OrderItem update.
- **Post-create staging-Case OwnerId reassignment** may trip `Restrict_Case_Ownership_Changes`. Test.
- **Hardcoded Pricebook2Id** in `New_Prescriptions_Manually_Entered.PricebookEntry` — same anti-pattern as the RT IDs. Outside the new Apex service's direct concern (the flow does this, not us) but worth documenting for Phase E cleanup.
- **NL_Prescription\_\_c is a Fill→Master FK** despite the NewLeaf-suggesting name. Don't assume it's NewLeaf-legacy and try to drop it.

**New cross-references for §11:**

- `force-app/main/default/flows/New_Prescriptions_Manually_Entered.flow-meta.xml` — Fill + OrderItem + PricebookEntry contracts.
- `business-context/objects/EhrMedicationPrescription.md` Multi-relationship hazard already documents the three-FK pattern that Round-1 surfaced.

### §9.7 — Updated open-question summary

**Closed in Round 2** (in addition to Round 1's 1–4): 5. ~~OrderItem field surface~~ — done (§9.1). 6. ~~Validation Rules~~ — done (§9.2). 7. ~~Pricing-loop mechanics~~ — done (§9.3). 8. ~~Cart-linkage path~~ — done (§9.4). 9. ~~Account + CPA trigger surface~~ — done (§9.5).

**Still open (genuinely Phase A territory):**

- 12 Case-flow + 4 Rx-flow record-update side effects on the new-order Case + Apex-created Rxes. Each flow is its own XML; comprehensive enumeration is multi-hour and yields lower marginal value than just running tests in Phase A and surfacing failures empirically.
- EhrPractitioner not-in-roster fallback (no current path).
- Picklist value enumeration on `Status__c` / `New_Prescription_Order_Status__c`.
- Health Cloud auto-Contact-create in user mode (sandbox test required).
- Health Cloud `IndividualType='Group'` + `EnrollmentType='NonDual'` semantic confirmation.

## §10 — Round 3 findings (2026-05-06) — final round

User pushback (#3): "more stones to turn?" → yes, several. Round 3 closes them. After this, Phase A0 is complete with the remaining items declared as Phase A territory.

### §10.1 — `HashUtils.cls` (Item 4)

14-line class. `with sharing`. `@InvocableMethod` named `Generate Unique Hexidecimal ID`. Generates an MD5 hex of `(recordId + Datetime.now().formatGMT('yyyy-MM-dd HH:mm:ss.SSS'))`. **Deterministic, side-effect-free, no edge cases worth handling** — MD5 collision probability is astronomically low; null-recordId path uses literal `'1000'` as the ID-prefix fallback.

**Apex service can call directly:**

```apex
List<String> hashes = HashUtils.generateUniqueIds(new List<Id>{rxId});
```

Used by the downstream `New_Prescriptions_Manually_Entered` flow's `Generate_Prescription_ID` action, but writes the result to **`Prescription_Id__c`** on the Master Rx — NOT `Patient_Fill_Id__c` as the parent plan's §3 suggested. See §10.2.

### §10.2 — `Update_Prescription` denormalization step (Item 5)

After `Generate_Prescription_ID` runs, `New_Prescriptions_Manually_Entered.Update_Prescription` updates the Master Rx with **11 denormalized / computed fields:**

| Field                                    | Source                                                                                                            | Notes                                                                |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `Days_supply__c`                         | `DaysSupply` formula = `Quantity__c / Sig__r.Frequency_as_Number_Daily__c`                                        | Null if frequency is 0 or blank                                      |
| `Dosage_Form__c`                         | `Product__r.Dosage_Form__c`                                                                                       | Cached from Product                                                  |
| `Full_Sig_New_Leaf__c`                   | `Sig__r.Full_Sig__c`                                                                                              | Cached from Sig                                                      |
| `HealthCloudGA__MedicationExpiration__c` | `Z1_year` formula = DateWritten + 1 year (with leap-year adjustments for 2023-2024, 2027-2028, 2031-2032 windows) | The 367-day branches handle leap years; complex formula              |
| `HealthCloudGA__MedicationName__c`       | `Product__r.Name`                                                                                                 | Cached                                                               |
| `Ingredients__c`                         | `Product__r.Ingredients__c`                                                                                       | Cached                                                               |
| `Prescription_Id__c`                     | `Generate_Prescription_ID` (HashUtils MD5 hex)                                                                    | **NOT `Patient_Fill_Id__c` — different field on Master Rx vs. Fill** |
| `Prescription_Number__c`                 | `RX_NUMBER_TEXT_FINAL` = `TEXT(Rx_Number_Auto_Number__c)`                                                         | Stringified Rx number                                                |
| `RefillsRemaining__c`                    | `RefillsAuthorized__c`                                                                                            | Initialized = authorized; presumably decremented on each fill        |
| `Rx_Number_Unique_Rx_Only__c`            | `Rx_Number_Formula` = `VALUE(Rx_Number_Auto_Number__c)`                                                           | Numeric Rx number                                                    |
| `Strength__c`                            | `Product__r.Strength__c`                                                                                          | Cached                                                               |

**Implication for the Apex service:** since the service sets `SF_Manually_Entered__c=true` (resolved §9 #1), this entire 11-field denormalization happens automatically post-insert. Service does NOT need to set these. **But:** `Prescription_Id__c` (the hash) and `Patient_Fill_Id__c` (per `EhrMedicationPrescription.md`) are SEPARATE fields. The Master Rx gets a hash; the Fill record gets a different hash via the same HashUtils call (presumably called for the Fill's own `Patient_Fill_Id__c` somewhere — unverified, but observable post-Phase-A by querying both fields).

**Correction to a §3 implication:** the parent plan's §3 conflated `Prescription_Id__c` with `Patient_Fill_Id__c`. They're different fields with different lifecycles.

### §10.3 — Quarantine logic (Item 6) — gated by ISNEW

`Case_Insert_Update_Same_Record` (the canonical BeforeSave on Case) contains the auto-quarantine path:

```
Get_Cases_Open_with_Quarantine_Refill_Request:
  AccountId = $Record.AccountId
  AND IsClosed = false
  AND (RecordTypeId = Quarantined_Order
       OR RecordTypeId = Refill_Request_Case)

Has_Open_Quarantine_or_Refill_Request decision:
  IF Get_Cases_Open_... is NOT NULL
  AND ISNEW = true                    ← gating condition
  → set OwnerId = Advanced Rx Admin user
  → set RecordTypeId = Quarantined_Order
```

**Translation:** when a NEW Case is inserted, if the patient (Account) already has any open Case with RT=`Quarantined_Order` OR RT=`Refill_Request_Case`, **the new Case auto-converts to Quarantined_Order RT and re-owns to the Advanced Rx Admin user.** This OVERRIDES whatever RT and OwnerId the inserter set.

**`ISNEW=true` gate is critical:** it means the canonical BeforeSave does NOT re-quarantine on Updates. Service's "close staging Case" step (Update, not Insert) is safe.

**Service implication:**

- For SOME patients, the new-order Case the service creates will land in **Quarantined_Order** RT with **Advanced Rx Admin** owner — NOT `Customer_Service_New_Order` RT and `CS_Case_Queue` owner. **This is by design** (patient has an existing concern, route to admin not CS) and is NOT a bug.
- The service's `IntakeResponse.newOrderCaseId` should still be returned, but consumers should expect that `Case.RecordType.DeveloperName` may be `Quarantined_Order` instead of `Customer_Service_New_Order` for some payloads.
- The Order's `Skip_Quarantine_Check__c=true` is a SEPARATE Order-side mechanism (unread, lives in `Order_Insert_Update_Related_Records` line 191). Two quarantine systems exist; preserving `Skip_Quarantine_Check__c=true` on Order doesn't bypass the Case-side quarantine.

**`Case_Insert_Update_Related_Records`** (canonical AfterSave, 249 lines): does Holiday + TimeZone (`pw_ccpro__TimeZone__c`) lookups and updates the Case. Likely sets scheduled-date fields (Next_Fax_Date_Time**c / Auto_Close_Date_Time**c / Next_Text_Message_Date_Time\_\_c) based on holidays + patient timezone. **Detail-level enumeration deferred to Phase A test surfacing.**

### §10.4 — `B2BProductPricingService` edge cases (Item 7)

Three failure modes the Apex service must handle when calling this:

| Edge case                                                                                     | Behavior                                                                                                                                          | Service mitigation                                                                                                                                                                                                                                                                   |
| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **No matching `Custom_Product_Price__c` row** for the (category, tier, quantity) tuple        | `getPrice()` returns `null`. Caller `getPriceAny()` returns `null` for that Rx. `OutputPrices.priceN = null`.                                     | Null-check the returned `priceN` before applying to OrderItem; surface as a `warning` in `IntakeResponse` (intake succeeds, pricing flagged for human review).                                                                                                                       |
| **All Rxes are STANDARD-category but none have `Product__r.Count_Towards_Total_Qty__c=true`** | `getTotalQuantity()` returns 0. `getPriceAny()` for STANDARD does `tempPrice / totalQuantity = X / 0` → `System.MathException("Divide by zero")`. | Defensive: before calling the pricing service, count Rxes that contribute to total. If 0 STANDARD-category contributors, skip the pricing call OR pass `0.0` price to all Rxes and surface as warning. **Latent bug in the existing flow path too** — flag for reporting separately. |
| **Product has no `Pricing_Category__c` or `Pricing_Tier__c`**                                 | The `Custom_Product_Price__c` lookup filters fail to find matches → `null` price (same as case 1).                                                | Same as case 1 — null-check + warning.                                                                                                                                                                                                                                               |

**Hardcoded `totalQuantity` cap at 900** (line 138-140 of `B2BProductPricingService.cls`): if total exceeds 900, capped at 900. Magic number; service should preserve the cap when calling.

### §10.5 — `Get_Sales_Channel` filter (Item 8)

```
SELECT Id FROM SalesChannel
WHERE SalesChannelName = 'AdvancedRx'
LIMIT 1
```

The service must look up SalesChannel by `SalesChannelName='AdvancedRx'`. **Sandbox seeding requirement:** the test factory must verify this SalesChannel exists in ClaudeTest before tests can run; if not, seed it.

### §10.6 — New corrections / hazards / risks (Round 3 additions)

**New hazards:**

- **Auto-quarantine override.** Service's RT + OwnerId on the new-order Case can be silently overwritten by the Case canonical BeforeSave's auto-quarantine logic. Per §10.3. Acknowledge in the service's response handling and in any DE-team workflow assumption.
- **`B2BProductPricingService` divide-by-zero latent bug.** §10.4 case 2. Service must defend; flag for separate cleanup.
- **`Prescription_Id__c` vs. `Patient_Fill_Id__c` confusion.** Different fields, different records, both populated via HashUtils. Plan §3 conflated them. Cleanup in plan §3 rewrite at Phase A start.

**New cross-references:**

- `force-app/main/default/classes/HashUtils.cls` — 14-line MD5 ID generator, `with sharing`, no edge cases.
- `force-app/main/default/flows/Case_Insert_Update_Same_Record.flow-meta.xml` lines 597–628 + 1162–1202 — quarantine logic + the `ISNEW=true` gate.

### §10.7 — Final-state declaration

**Phase A0 is now declared complete.**

What's been delivered across three rounds:

- Round 1 (initial): screen-flow `<recordCreates>` extraction, live `FieldDefinition` SOQL, contract delta vs. plan §3, 8+ corrections.
- Round 1 follow-up: closed §6 questions 1–4 (Pharmacy_Note RT verified `Customer_Service`, Prescriber_ID\_\_c is load-bearing, CS_Case_Queue / Data_Entry_Queue DeveloperNames).
- Round 2: gaps 1–7 from user pushback. OrderItem + Fill contracts, full VR audit, pricing-loop mechanics, cart-linkage mechanics, Account-side trigger surface.
- Round 3 (this section): items 1, 4, 5, 6, 7, 8 from the second pushback. HashUtils, Update_Prescription denormalization, quarantine logic + ISNEW gate, B2BProductPricingService edge cases, Get_Sales_Channel filter.

**Explicitly deferred to Phase A** (with documented reasons in §8):

- 12 Case-flow + 4 Rx-flow per-flow `<recordUpdates>` enumeration.
- EhrPractitioner not-in-roster fallback (no current path; out of v1 scope).
- Picklist value enumeration.
- Health Cloud auto-Contact-create in user mode (sandbox-test required).
- Health Cloud picklist semantic confirmation.

The honest meta-finding: every round of pushback uncovered material. The marginal cost of more rounds is now rising fast; remaining items are either (a) already documented as deferrals or (b) require sandbox testing. Phase A authoring will surface the residual unknowns through test failures, which is the appropriate trigger.

## Cross-references

- `docs/plans/azure-structured-intake-writes/plan.md` — parent plan; §3 is what this discovery validates against
- `business-context/objects/EhrMedicationPrescription.md` — Rx managed-object reference; `Patient_Fill_Id__c` HashUtils note
- `business-context/objects/Case.md` — Case RT inventory; `Customer_Service_New_Order` DeveloperName
- `business-context/objects/Rx_Image.md` — staging-record schema (the Rx custom `Rx_Image__c` lookup target)
- `business-context/object-purpose-map.md` — Account "Individual" RT, Contact-Patient RT framing
- `force-app/main/default/flows/New_Patient_New_Order_New_Rx_New_Case_Launch_from_data_case.flow-meta.xml` — source of all the assignment-node extractions
- `.claude/rules/flow.md` §3.11 — RecordType.DeveloperName rule (4 hardcoded IDs to retrofit)
