Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 28 additions & 17 deletions src/features/invoice-sync/lib/SyncedContacts.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { SyncedContactUserType, syncedContacts } from '@/db/schema/syncedContact
import { SyncEntityType, SyncEventType, SyncStatus } from '@/db/schema/syncLogs.schema'
import APIError from '@/errors/APIError'
import type { ClientResponse, CompanyResponse } from '@/lib/copilot/types'
import { buildClientName } from '@/lib/copilot/utils'
import { buildClientName, getEarliestActiveClient } from '@/lib/copilot/utils'
import logger from '@/lib/logger'
import AuthenticatedXeroService from '@/lib/xero/AuthenticatedXero.service'
import type { ContactCreatePayload, ValidContact } from '@/lib/xero/types'
Expand All @@ -27,22 +27,33 @@ class SyncedContactsService extends AuthenticatedXeroService {
const settingsService = new SettingsService(this.user, this.connection)
const { useCompanyName } = await settingsService.getOrCreateSettings()

const client = clientId ? await this.copilot.getClient(clientId) : undefined
let client = clientId ? await this.copilot.getClient(clientId) : undefined
let billedClientId = clientId

let company: CompanyResponse | undefined
// If useCompanyName is true or clientId is undefined, then the invoice is billed to a company
// `company` variable will be populated then.
if (useCompanyName || !clientId) {
company = await this.copilot.getCompany(companyId)
}
let useNonPlaceholderCompanyName = false

const useNonPlaceholderCompanyName = useCompanyName && !company?.isPlaceholder
// Case where an invoice is billed to a company.
// If an invoice is billed to a client, this whole if else block is skipped.
if (!useCompanyName && !clientId) {
// Billed to company but useCompanyName is off: bill the earliest active client of the company.
const clients = await this.copilot.getCompanyClients(companyId)
client = getEarliestActiveClient(clients)

if (!useNonPlaceholderCompanyName && !clientId)
throw new APIError(
'Cannot use company name of place holder company for invoice',
status.BAD_REQUEST,
)
if (!client) throw new APIError('No active client found for company', status.BAD_REQUEST)
billedClientId = client.id
} else if (!clientId) {
// Billed to company with useCompanyName on: use the company name (unless it's a placeholder).
company = await this.copilot.getCompany(companyId)

if (company?.isPlaceholder)
throw new APIError(
'Cannot use company name of place holder company for invoice',
status.BAD_REQUEST,
)
useNonPlaceholderCompanyName = true
}
// Otherwise (clientId present), the invoice is billed directly to that client.

const query = this.db
.select({ contactID: syncedContacts.contactId })
Expand All @@ -53,11 +64,11 @@ class SyncedContactsService extends AuthenticatedXeroService {
eq(syncedContacts.tenantId, this.connection.tenantId),
eq(
syncedContacts.clientOrCompanyId,
useNonPlaceholderCompanyName || !clientId ? companyId : clientId,
useNonPlaceholderCompanyName || !billedClientId ? companyId : billedClientId,
),
eq(
syncedContacts.userType,
useNonPlaceholderCompanyName || !clientId
useNonPlaceholderCompanyName || !billedClientId
? SyncedContactUserType.COMPANY
: SyncedContactUserType.CLIENT,
),
Expand All @@ -82,14 +93,14 @@ class SyncedContactsService extends AuthenticatedXeroService {
eq(syncedContacts.tenantId, this.connection.tenantId),
eq(
syncedContacts.clientOrCompanyId,
useNonPlaceholderCompanyName || !clientId ? companyId : clientId,
useNonPlaceholderCompanyName || !billedClientId ? companyId : billedClientId,
),
),
)
Comment thread
SandipBajracharya marked this conversation as resolved.
}

logger.info(
`SyncedContactsService#createContact :: Couldn't find existing client... creating a new one for ${clientId}`,
`SyncedContactsService#createContact :: Couldn't find existing client... creating a new one for ${billedClientId}`,
)
contact = await this.createContact(client, company)

Expand Down
15 changes: 15 additions & 0 deletions src/lib/copilot/utils.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,17 @@
import type { ClientResponse } from './types'

export const buildClientName = (client: { givenName: string; familyName: string }) =>
`${client.givenName} ${client.familyName}`

const ACTIVE_CLIENT_STATUS = 'active'

// Returns the earliest-created active client, or undefined if none are active.
export const getEarliestActiveClient = (clients: ClientResponse[]): ClientResponse | undefined =>
clients.reduce<ClientResponse | undefined>(
(earliest, client) =>
client.status === ACTIVE_CLIENT_STATUS &&
(!earliest || new Date(client.createdAt) < new Date(earliest.createdAt))
? client
: earliest,
undefined,
)
Loading