|
| 1 | +import { IAddress, Person } from '@leavittsoftware/lg-core-typescript'; |
| 2 | +import { html, TemplateResult } from 'lit'; |
| 3 | +import { join } from 'lit/directives/join.js'; |
| 4 | +import { getCountryName } from './get-country-name'; |
| 5 | + |
| 6 | +export function formatAddressParts(address: Partial<IAddress> | Partial<Person>, options: formatAddressOptions = {}) { |
| 7 | + if (!address) { |
| 8 | + return {}; |
| 9 | + } |
| 10 | + |
| 11 | + const street1 = 'Street1' in address ? address.Street1?.trim() : 'CompanyAddressStreet1' in address ? address.CompanyAddressStreet1?.trim() : ''; |
| 12 | + const street2 = 'Street2' in address ? address.Street2?.trim() : 'CompanyAddressStreet2' in address ? address.CompanyAddressStreet2?.trim() : ''; |
| 13 | + const city = 'City' in address ? address.City?.trim() : 'CompanyAddressCity' in address ? address.CompanyAddressCity?.trim() : ''; |
| 14 | + const state = 'State' in address ? address.State?.trim() : 'CompanyAddressState' in address ? address.CompanyAddressState?.trim() : ''; |
| 15 | + const zip = 'Zip' in address ? address.Zip?.trim() : 'CompanyAddressZip' in address ? address.CompanyAddressZip?.trim() : ''; |
| 16 | + const country = 'Country' in address ? address.Country?.trim() : 'CompanyAddressCountry' in address ? address.CompanyAddressCountry?.trim() : ''; |
| 17 | + |
| 18 | + const line1 = street1; |
| 19 | + const line2 = street2; |
| 20 | + const line3 = `${[[city, state].join(' ').trim(), zip].filter((o) => o).join(', ')}`; |
| 21 | + const line4 = getCountryName(country, options?.excludeCountryIfUSA); |
| 22 | + |
| 23 | + return { |
| 24 | + line1: line1 && !options?.excludeLine1 ? line1 : undefined, |
| 25 | + line2: line2 && !options?.excludeLine2 ? line2 : undefined, |
| 26 | + line3: line3 && !options?.excludeLine3 ? line3 : undefined, |
| 27 | + line4: line4 && !options?.excludeLine4 ? line4 : undefined, |
| 28 | + }; |
| 29 | +} |
| 30 | + |
| 31 | +export function formatAddress( |
| 32 | + address: Partial<IAddress> | Partial<Person>, |
| 33 | + options: formatAddressOptions = {}, |
| 34 | + joiner: TemplateResult | string = html`<br />` |
| 35 | +) { |
| 36 | + const parts = formatAddressParts(address, options); |
| 37 | + const partsArray = Object.values(parts).filter((part) => part !== undefined && part !== ''); |
| 38 | + |
| 39 | + if (partsArray.length === 0) { |
| 40 | + return null; |
| 41 | + } |
| 42 | + return join(partsArray, joiner); |
| 43 | +} |
| 44 | + |
| 45 | +export type formatAddressOptions = { |
| 46 | + excludeCountryIfUSA?: boolean; |
| 47 | + excludeLine1?: boolean; |
| 48 | + excludeLine2?: boolean; |
| 49 | + excludeLine3?: boolean; |
| 50 | + excludeLine4?: boolean; |
| 51 | +}; |
0 commit comments