Happy House - Ecommerce Docs
Developer ResourcesAddress

Address Features and Flows

Complete feature list, actor journeys, state flows, business rules, edge cases, and diagrams for the Address module.

Address Features and Flows

Use this page for the address-book domain: what it does for customers and systems, and how each flow behaves from start to finish.

1. Documentation Evidence

Source TypeFiles or DocsWhat Was Extracted
APIapps/api/src/modules/address/customer/address-customer.controller.tsRoutes, guards, idempotency scopes, status codes
Backendaddress-customer.service.tsDefault handling, advisory lock, serviceability-on-read
Schemapackages/db/src/schema/address/customer-address.tsWard/coordinate CHECKs, partial unique default, CASCADE
Phoneapps/api/src/utils/phone/phone.util.tsNP region, E.164 normalization
Error registryapps/api/src/common/types/error-codes.ts (// CUSTOMER ADDRESS)CUSTOMER_ADDRESS_* codes

2. Feature Summary

FieldValue
Moduleaddress
SubmoduleN/A
Primary user valueA customer's own delivery addresses with one default, restorable archive, and live serviceability
ActorsCustomer (signed in), internal systems (shipping serviceability, future orders)
Main entry points/api/mobile/addresses (7 routes)
Main outputsAddress responses with grouped recipient/location/status
Related docsAPI, Backend

3. Actor Matrix

ActorCan DoCannot DoAuth RequirementNotes
CustomerCreate, list, read, update, archive, restore, set-default their own addressesTouch another customer's address (404, never 403 — no existence oracle), write to an archived address (409)JWTCUSTOMER_READ 60/min, CUSTOMER_WRITE 20/min — both keyed on the account
AdminRead or write any addressNo admin surface, by design (PII)
Orders (future)Read an address at checkout to snapshot itHold a foreign key to itInternalSnapshot rule — see backend §2

4. Capability Matrix

CapabilitySurfaceActorRoute/TriggerState ReadState WrittenLinked API Section
Create addressCustomerCustomerPOST /api/mobile/addressesactive count, defaultaddress rowAPI §4
List addressesCustomerCustomerGET /api/mobile/addressesown rowsAPI
Read oneCustomerCustomerGET /:idany stateAPI
UpdateCustomerCustomerPATCH /:idactive rowfieldsAPI
ArchiveCustomerCustomerDELETE /:idactive rowarchived_atAPI
RestoreCustomerCustomerPOST /:id/restorearchived rowarchived_at clearedAPI
Set defaultCustomerCustomerPUT /:id/defaultactive rowsdefault flagAPI

5. User-Facing Flows

5.1 Create an address

Summary

A customer adds a delivery address. The first address becomes the default automatically; the response includes live serviceability computed from the shipping configuration.

Sequence Diagram

Branches and Edge Cases

BranchConditionBehaviorError/Result
First addressNo active rowsBecomes default automaticallystatus.default: true
20 active alreadyCap reachedReject409 CUSTOMER_ADDRESS_LIMIT_REACHED
Local phone9812345678Normalized to +977…E.164 in response
Bad phoneWill not normalizeReject400 CUSTOMER_ADDRESS_RECIPIENT_PHONE_INVALID
Swapped coordinatesLongitude in latitude's rangeReject400 CUSTOMER_ADDRESS_COORDINATES_OUT_OF_RANGE
Retry after timeoutSame Idempotency-KeyNo duplicateSame response (idempotency interceptor)

5.2 Set the default

Summary

PUT /:id/default clears the previous default and sets the new one in the same transaction. Concurrent calls are serialized per customer so two set-defaults cannot race.

Branches and Edge Cases

BranchConditionBehaviorError/Result
Archived targetRow archived409CUSTOMER_ADDRESS_ALREADY_ARCHIVED
Concurrent set-defaultTwo callsSerialized per customerSecond sees committed state
No previous defaultZero activeNew one becomes defaultLegal state

5.3 Archive and restore

Archiving the default promotes the newest remaining active address. Restore never restores the old default flag — the flag is recomputed (default only if the customer has no active addresses).

6. Admin Flows

None. There is no admin surface over the address table — it holds PII, and a cross-customer read path should not exist until something concretely needs one.

7. Lifecycle and State Transitions

EntityFromEvent/ActionToGuard ConditionSide Effects
customer_addresscreateactive< 20 active; district resolvesAuto-default if first; serviceability computed
customer_addressactivearchivearchivedMust be active (409 otherwise)If it was default: newest active promoted
customer_addressarchivedrestoreactiveMust be archived (409 otherwise)Default only if no other active
customer_addressactiveset-defaultactiveMust be activePrevious default cleared, same tx

9. Data and Side Effects by Flow

FlowDB WritesCache EffectsJobsRealtimeAnalyticsNotifications
Createaddress row
Updatefields
Archive/restorearchived_at (+ default promotion)
Set defaultdefault flags
Any readshipping serviceability cache (read)

10. Error and Recovery Flows

ScenarioTriggerUser/System ExperienceRecoverySource
Address cap20 active409Archive one firstservice
Write on archivedPATCH/DELETE/default409Offer restoreservice
Restore on activeRestore active row409Refreshservice
Someone else's idCross-customer404 (no existence oracle)Refresh listservice WHERE
Idempotent retryClient retrySame responseinterceptor
Serviceability changeAdmin edits districtNext read reflects itcomputed on read

11. Diagrams Required Per Module

  • Actor capability diagram — §3/§4.
  • Sequence diagram per major flow — §5.1/§5.2.
  • State machine diagram — §5.3/§7.
  • Data side-effect diagram — §9.
  • Error branch diagram — §10.

12. Mandatory Feature and Flow Deep-Dive Pack

12.1 Feature Inventory With Minor Behaviors

FeatureMinor BehaviorActorTriggerUser/System ResultBackend Side EffectSource
CreateAuto-default firstCustomerPOSTdefault trueservice
CreateIdempotencyCustomerRetry with keyNo duplicateinterceptor
CreateLocal phoneCustomer9812345678E.164 storedNP regionphone util
CreateCoordinates pair ruleCustomerOne coordinate400both-or-neitherdto
ListDefault first orderingCustomerGETOrderingservice
ListStatus filterCustomer?status=archivedSubsetdto
ReadArchived readableCustomerGET archivedRestore discoveryservice
ArchiveDefault promotionCustomerArchive defaultNewest active defaultservice
RestoreFlag recomputeCustomerRestoreNot default unless aloneservice
Set defaultConcurrent safetyCustomerParallel callsSerializedadvisory lockservice
All readsServiceability liveCustomerAny readCurrent flagshipping readservice

12.2 Business Process Diagram Pack

12.3 Business Rules and Policy Traceability

RuleBusiness ReasonActor ImpactEnforced InAPI ImpactBackend ImpactTests
At most one default per customerOne unambiguous delivery targetUI shows one defaultPartial unique indexPUT /defaultindex + advisory lockspec
Zero active = no default legalArchive-all is fineUI must not assume defaultServicespec
Restore never restores flagDefault is a choice, not historyRestored address not defaultServicerecomputespec
CASCADE from customersPII must not outlive ownerAddresses vanish with customerSchema FKOrders must snapshotschema
Ward 1–40Generous boundValidation error beyondCHECK400probe
Coordinates in NepalSwap detection400 on swapCHECK/dtoprobe
Cap 20 activeBounded list409Servicearchived don't countspec
Serviceability never storedLive truthReads reflect editsService designshipping readspec

12.4 Tradeoffs and Product Rationale

Product DecisionUser BenefitEngineering BenefitAlternativeTradeoffRisk
CASCADE + snapshot rulePrivacy by deletionOrders stay truthfulNo-cascade ruleOrders must copy fieldsSnapshot contract documented
Municipality id nullFree-text nameNo 753-row memory gameFull referenceNo idsDocumented
Advisory lock per customerSafe concurrent defaultsSerialized writesOptimistic retryRare contentionAccepted
Serviceability computedAlways currentNo sync jobStored flagRead costBatched + cached
Local phone acceptedEasy entryNP default regionStrict E.164 onlyAmbiguityDocumented

12.5 Flow Edge-Case Matrix

FlowEdge CaseTriggerExpected BehaviorUser/System FeedbackSource
Create21st activeCap409LIMIT_REACHED
CreateUnknown districtBad uuid404DISTRICT_NOT_FOUND
CreateOne coordinateMissing pair400COORDINATES_INCOMPLETE
CreateOut-of-range pairSwapped400COORDINATES_OUT_OF_RANGE
UpdateArchived rowPATCH409ALREADY_ARCHIVED
UpdateNull clearexplicit nullField cleareddto
DefaultArchived rowPUT409ALREADY_ARCHIVED
RestoreActive rowPOST409NOT_ARCHIVED
ReadOthers' addressAny404NOT_FOUND (no oracle)
Any writeDuplicate idempotentRetrySame response

12.6 Flow-to-Data Trace

FlowReadsWritesCacheJobs/EventsResponse Fields
Createcount, districtaddress rowgrouped response
List/readaddress rows + shippingshipping (read)grouped array
Updaterowfieldsgrouped
Archive/restorerowarchived_at (+ default)message / grouped
Set defaultrowsdefault flagsgrouped

12.7 Experience Quality Checklist

  • The doc explains what the actor is trying to accomplish.
  • The doc explains what the backend does that the actor does not see (normalization, advisory lock, live serviceability).
  • The doc covers every minor flow and branch.
  • The doc includes user and system flows.
  • The doc explains business logic, tradeoffs, and rationale.
  • The doc maps every flow to API routes and backend side effects.
  • The doc includes diagrams appropriate to each flow type.
  • The doc covers edge cases and failure recovery.

13. Completion Checklist

  • Every feature, minor action, and submodule capability is listed.
  • Every actor has allowed and forbidden behavior.
  • Every major and minor flow includes steps, branches, and diagrams.
  • Every lifecycle has a transition table and state diagram.
  • Every flow links to the API and backend docs.
  • TDD dependencies are called out where they shape behavior (no TDD pages published yet).

See Also