Skip to content

Update sync code for unified-accounting #290

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 4, 2025
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
13 changes: 12 additions & 1 deletion connectors/connector-plaid/def.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,13 @@ export const plaidSchemas = {
})
.default({}),
sourceOutputEntities: R.mapToObj(
['transaction', 'account', 'investment_transaction', 'holding'] as const,
[
'transaction',
'account',
'investment_transaction',
'holding',
'merchant',
] as const,
(e) => [e, z.unknown()],
),
sourceOutputEntity: z.discriminatedUnion('entityName', [
Expand All @@ -114,6 +120,11 @@ export const plaidSchemas = {
entityName: z.literal('transaction'),
entity: zCast<plaid.Transaction | plaid.InvestmentTransaction>(),
}),
z.object({
id: z.string(),
entityName: z.literal('merchant'),
entity: zCast<{merchant_entity_id: string; name: string}>(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider stricter validation (e.g. .strict()) for the 'merchant' entity if extra props aren’t allowed.

Suggested change
entity: zCast<{merchant_entity_id: string; name: string}>(),
entity: zCast<{merchant_entity_id: string; name: string}>().strict(),

}),
]),
webhookInput: zWebhookInput,

Expand Down
25 changes: 22 additions & 3 deletions connectors/connector-plaid/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,29 @@ export const plaidServerConnector = {
}

cursor = res.next_cursor
const filteredTxns = [...res.added, ...res.modified].filter(
(t) => !accountIds || accountIds.includes(t.account_id),
)
const merchantNameById = Object.fromEntries(
filteredTxns
.map((t) =>
'merchant_entity_id' in t && t.merchant_entity_id
? ([
t.merchant_entity_id as string,
t.merchant_name!,
] as const)
: null,
)
.filter((i) => !!i),
)

yield [
...[...res.added, ...res.modified]
.filter((t) => !accountIds || accountIds.includes(t.account_id))
.map((t) => def._opData('transaction', t.transaction_id, t)),
...filteredTxns.map((t) =>
def._opData('transaction', t.transaction_id, t),
),
...Object.entries(merchantNameById).map(([id, name]) =>
def._opData('merchant', id, {merchant_entity_id: id, name}),
),
...R.pipe(
res.removed,
R.map((t) => t.transaction_id),
Expand Down
21 changes: 17 additions & 4 deletions packages/db/lib/upsert-sql.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ test('upsert query with inferred table', async () => {
data: {hello: 'world'},
arr: ['a', 'b'],
date,
null_value: null,
}
const table = inferTableForUpsert('test_user', row)
const createTableSql = await generateMigration(
Expand All @@ -230,7 +231,8 @@ test('upsert query with inferred table', async () => {
"count" text,
"data" jsonb,
"arr" jsonb,
"date" text
"date" text,
"null_value" text
);
"
`)
Expand All @@ -243,27 +245,38 @@ test('upsert query with inferred table', async () => {
'{"hello":"world"}',
'["a","b"]',
date,
null,
])
expect(await formatSql(query.toSQL().sql)).toMatchInlineSnapshot(`
"insert into
"test_user" ("id", "name", "count", "data", "arr", "date")
"test_user" (
"id",
"name",
"count",
"data",
"arr",
"date",
"null_value"
)
values
($1, $2, $3, $4, $5, $6)
($1, $2, $3, $4, $5, $6, $7)
on conflict ("id") do
update
set
"name" = excluded."name",
"count" = excluded."count",
"data" = excluded."data",
"arr" = excluded."arr",
"date" = excluded."date"
"date" = excluded."date",
"null_value" = excluded."null_value"
where
(
"test_user"."name" IS DISTINCT FROM excluded."name"
or "test_user"."count" IS DISTINCT FROM excluded."count"
or "test_user"."data" IS DISTINCT FROM excluded."data"
or "test_user"."arr" IS DISTINCT FROM excluded."arr"
or "test_user"."date" IS DISTINCT FROM excluded."date"
or "test_user"."null_value" IS DISTINCT FROM excluded."null_value"
)
"
`)
Expand Down
18 changes: 17 additions & 1 deletion unified/unified-accounting/adapters/plaid-adapter/mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export const mappers = {
transaction: mapper(zCast<Plaid['Transaction']>(), unified.transaction, {
id: 'transaction_id',
date: 'date',
vendor_id: 'merchant_entity_id',
account_id: 'account_id',
amount: 'amount',
currency: 'iso_currency_code',
Expand All @@ -55,8 +56,23 @@ export const mappers = {
// Plaid transactions are single entry and therefore unbalanced
// We should probably not set any "lines" at all in this case.
// Would also need some semantic to communicate set if null, aka set default value,
lines: () => [],
lines: (t) => [
{
account_id: '',
amount: t.amount * -1,
currency: t.iso_currency_code ?? t.unofficial_currency_code ?? 'USD',
},
],
// created_at: (t) => t.datetime ?? new Date().toISOString(),
// updated_at: (t) => t.datetime ?? new Date().toISOString(),
}),
merchant: mapper(
zCast<{merchant_entity_id: string; name: string}>(),
unified.vendor,
{
id: 'merchant_entity_id',
name: 'name',
url: () => null,
},
),
}
44 changes: 32 additions & 12 deletions unified/unified-accounting/adapters/qbo-adapter/mapper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type {QBO_ENTITY_NAME} from '@openint/connector-qbo'
import {type QBOSDKTypes} from '@openint/connector-qbo'
import {snakeCase, type z} from '@openint/util'
import {R, snakeCase, type z} from '@openint/util'
import {mapper, zCast} from '@openint/vdk'
import * as unified from '../../unifiedModels'

Expand Down Expand Up @@ -36,6 +36,10 @@ const tranactionMappers = {
}))
},
bank_category: () => 'Purchase',
vendor_id: (t) =>
t.EntityRef?.type === 'Vendor' && t.EntityRef?.value
? makeQboId('Vendor', t.EntityRef.value)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No null check on t.EntityRef.value before using it in makeQboId. If value is undefined/null but type is 'Vendor', this will create an invalid ID. Should add null check for value property.


React with 👍 to tell me that this comment was useful, or 👎 if not (and I'll stop posting more comments like this in the future)

: '', // for some reason `null` causes vendor_id to be quoted, probably encoded as json, does not add up but...
created_at: 'MetaData.CreateTime',
updated_at: 'MetaData.LastUpdatedTime',
}),
Expand All @@ -46,17 +50,33 @@ const tranactionMappers = {
currency: 'CurrencyRef.value',
memo: 'PrivateNote',
amount: 'TotalAmt',
lines: (p) =>
p.Line.map((line) => ({
id: line.Id,
memo: line.Description,
amount: -1 * line.Amount,
currency: p.CurrencyRef.value,
account_id: makeQboId(
'Account',
line.DepositLineDetail?.AccountRef?.value ?? '',
),
})),
lines: (_t) => {
const t = _t as typeof _t & {
CashBack?: {
Amount: number
Memo: string
AccountRef: {value: string; name: string}
}
}
return R.compact([
...t.Line.map((line) => ({
id: line.Id,
memo: line.Description,
amount: -1 * line.Amount,
currency: t.CurrencyRef.value,
account_id: makeQboId(
'Account',
line.DepositLineDetail?.AccountRef?.value ?? '',
),
})),
t.CashBack && {
amount: t.CashBack.Amount,
currency: t.CurrencyRef.value,
memo: t.CashBack.Memo,
account_id: makeQboId('Account', t.CashBack.AccountRef.value),
},
])
},
bank_category: () => 'Deposit',
created_at: 'MetaData.CreateTime',
updated_at: 'MetaData.LastUpdatedTime',
Expand Down
22 changes: 19 additions & 3 deletions unified/unified-accounting/unifiedAccountingLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export function unifiedAccountingLink(ctx: {
// TODO: Should build this into the mapper itself
const stream =
{
// QBO
Purchase: 'transaction',
JournalEntry: 'transaction',
Deposit: 'transaction',
Expand All @@ -55,25 +56,40 @@ export function unifiedAccountingLink(ctx: {
Vendor: 'vendor',
Customer: 'customer',
Attachable: 'attachment',
// Plaid
merchant: 'vendor',
}[op.data.entityName] ?? op.data.entityName

const mapped = applyMapper(mapper, op.data.entity, {
remote_data_key: 'remote_data',
})
if ('lines' in mapped) {
const txn = mapped as {
amount?: number
lines: {amount: number}[]
id: string
}
const trialBalance = txn.lines?.reduce((acc, line) => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The optional chaining operator (?.) on txn.lines could lead to undefined being passed to reduce(), which would cause a runtime error. Should add a null check or provide default empty array: txn.lines?.reduce(...) ?? 0


React with 👍 to tell me that this comment was useful, or 👎 if not (and I'll stop posting more comments like this in the future)

return acc + line.amount
}, txn.amount ?? 0)
if (trialBalance !== 0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The trial balance check uses strict equality to zero, which may be error‐prone due to floating‐point rounding. Consider comparing with a small epsilon tolerance.

Suggested change
if (trialBalance !== 0) {
if (Math.abs(trialBalance) > Number.EPSILON) {

console.warn(`Transaction does not balance: ${trialBalance} ${txn.id}`)
}
}

return rxjs.of({
...op,
data: {
stream,
data: {
...mapped,
connection_id: ctx.source.id, // Should this be the default somehow?
_openint_connection_id: ctx.source.id, // Should this be the default somehow?
// Denormalize customer_id onto entities for now, though may be better
// to just sync connection also?
customer_id: ctx.source.customerId,
_openint_customer_id: ctx.source.customerId,
},
upsert: {
key_columns: ['connection_id', 'id'],
key_columns: ['_openint_connection_id', 'id'],
insert_only_columns: ['created_at'],
no_diff_columns: ['updated_at'],
},
Expand Down
5 changes: 3 additions & 2 deletions unified/unified-accounting/unifiedModels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const transaction_line = z.object({
memo: z.string().nullable().optional().describe('Private line note'),
amount: z.number().describe('(positive) debit or (negative) credit'),
currency: currency_code,
account_id: z.string(),
account_id: z.string().describe('Empty means uncategorized'),
})

// MARK: - Models
Expand All @@ -37,6 +37,7 @@ export const transaction = z
description:
'Posted date for accounting purpose, may not be the same as transaction date',
}),
vendor_id: z.string().nullish(),
account_id: z.string().nullish(),
amount: z.number().nullish(),
currency: currency_code.nullish(),
Expand Down Expand Up @@ -78,7 +79,7 @@ export const vendor = z
.object({
...commonFields,
name: z.string(),
url: z.string(),
url: z.string().nullish(),
})
.openapi({ref: 'accounting.vendor'})

Expand Down