"""In-memory test doubles for the customers application layer (no database).""" from dataclasses import replace from apps.customers.domain.entities import BillingUnit, Contact, Customer from apps.customers.domain.exceptions import CustomerInUse from apps.customers.domain.value_objects import BusinessId, PersonalIdentityCode class InMemoryCustomerRepository: def __init__(self) -> None: self.customers: dict[int, Customer] = {} self.personal_ids: dict[int, str] = {} self.references: set[int] = set() # customer ids that something refers to self._next = 1 def get(self, customer_id: int) -> Customer | None: return self.customers.get(customer_id) def save(self, customer: Customer) -> Customer: if customer.id is None: customer = customer.with_id(self._next) self._next += 1 assert customer.id is not None if not customer.has_personal_id: self.personal_ids.pop(customer.id, None) self.customers[customer.id] = customer return customer def set_personal_id(self, customer_id: int, code: PersonalIdentityCode) -> None: self.personal_ids[customer_id] = code.value self.customers[customer_id] = replace(self.customers[customer_id], has_personal_id=True) def is_business_id_taken( self, business_id: BusinessId, *, exclude_id: int | None = None ) -> bool: return any( c.business_id == business_id and c.id != exclude_id for c in self.customers.values() ) def is_personal_id_taken( self, code: PersonalIdentityCode, *, exclude_id: int | None = None ) -> bool: return any(v == code.value and k != exclude_id for k, v in self.personal_ids.items()) def delete(self, customer_id: int) -> None: if customer_id in self.references: raise CustomerInUse() del self.customers[customer_id] class InMemoryContactRepository: def __init__(self) -> None: self.items: dict[int, Contact] = {} self._next = 1 def get(self, contact_id: int) -> Contact | None: return self.items.get(contact_id) def save(self, contact: Contact) -> Contact: if contact.id is None: contact = contact.with_id(self._next) self._next += 1 assert contact.id is not None self.items[contact.id] = contact return contact def delete(self, contact_id: int) -> None: del self.items[contact_id] class InMemoryBillingUnitRepository: def __init__(self) -> None: self.items: dict[int, BillingUnit] = {} self._next = 1 def get(self, billing_unit_id: int) -> BillingUnit | None: return self.items.get(billing_unit_id) def save(self, billing_unit: BillingUnit) -> BillingUnit: if billing_unit.id is None: billing_unit = billing_unit.with_id(self._next) self._next += 1 assert billing_unit.id is not None self.items[billing_unit.id] = billing_unit return billing_unit def delete(self, billing_unit_id: int) -> None: del self.items[billing_unit_id]