@fincuratech/sikka-sdk-js 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib/client.js
CHANGED
|
@@ -20,7 +20,7 @@ export class SikkaClient {
|
|
|
20
20
|
let offset = params.offset ?? 0;
|
|
21
21
|
let limit = params.limit ?? AUTHORIZED_PRACTICES_PAGE_SIZE;
|
|
22
22
|
for (;;) {
|
|
23
|
-
const response = await this.
|
|
23
|
+
const response = await this.appAuthGet('/v4/authorized_practices', { ...params, limit, offset });
|
|
24
24
|
const pageItems = response.items ?? [];
|
|
25
25
|
items.push(...pageItems);
|
|
26
26
|
const totalCount = Number.parseInt(response.total_count, 10);
|
|
@@ -119,6 +119,40 @@ export class SikkaClient {
|
|
|
119
119
|
this.baseUrl = config.baseUrl ?? SIKKA_BASE_URL;
|
|
120
120
|
this.credentials = config.credentials;
|
|
121
121
|
}
|
|
122
|
+
async appAuthGet(endpoint, params) {
|
|
123
|
+
const log = getLogger();
|
|
124
|
+
const url = new URL(`${this.baseUrl}${endpoint}`);
|
|
125
|
+
if (params) {
|
|
126
|
+
for (const [key, value] of Object.entries(params)) {
|
|
127
|
+
if (value !== null && value !== undefined) {
|
|
128
|
+
url.searchParams.set(key, String(value));
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
log.debug('Sikka API app-auth GET request', { endpoint, params });
|
|
133
|
+
const response = await fetch(url.toString(), {
|
|
134
|
+
headers: {
|
|
135
|
+
'App-Id': this.credentials.appId,
|
|
136
|
+
'App-Key': this.credentials.appKey,
|
|
137
|
+
'Content-Type': 'application/json',
|
|
138
|
+
},
|
|
139
|
+
method: 'GET',
|
|
140
|
+
});
|
|
141
|
+
if (!response.ok) {
|
|
142
|
+
const errorBody = await response.text();
|
|
143
|
+
throw new Error(`Sikka API GET ${endpoint} failed: ${response.status} ${response.statusText} - ${errorBody}`);
|
|
144
|
+
}
|
|
145
|
+
const text = await response.text();
|
|
146
|
+
if (!text || text.trim() === '') {
|
|
147
|
+
return { items: [] };
|
|
148
|
+
}
|
|
149
|
+
const data = JSON.parse(text);
|
|
150
|
+
log.debug('Sikka API app-auth GET response', {
|
|
151
|
+
endpoint,
|
|
152
|
+
status: response.status,
|
|
153
|
+
});
|
|
154
|
+
return data;
|
|
155
|
+
}
|
|
122
156
|
async authenticate() {
|
|
123
157
|
const log = getLogger();
|
|
124
158
|
log.debug('Sikka API: Authenticating');
|
package/dist/lib/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/lib/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAyCxC,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAEnD,MAAM,oBAAoB,GAAG,aAAa,CAAC;AAK3C,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAM3C,MAAM,gBAAgB,GAAG,CAAC,WAA+B,EAAiB,EAAE;IAC1E,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,KAAK,GAAG,oBAAoB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACrD,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;AAC5B,CAAC,CAAC;AAuBF,MAAM,OAAO,WAAW;IAMN,mBAAmB,GAAG;QAsBpC,aAAa,EAAE,KAAK,EAClB,QAAgB,EACyB,EAAE;YAC3C,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;YACvE,OAAO,CACL,SAAS,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,SAAS,KAAK,QAAQ,CAAC,IAAI,IAAI,CACtE,CAAC;QACJ,CAAC;QAmCD,I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CAAC,GAAG,IAAI,CAAC,OAAO,iBAAiB,EAAE;YAC7D,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC;YACjC,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;YAC/C,MAAM,EAAE,MAAM;SACf,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,IAAI,YAAY,GAAG,GAAG,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;YAC/D,IAAI,CAAC;gBACH,MAAM,SAAS,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAkB,CAAC;gBAC3D,YAAY;oBACV,SAAS,CAAC,iBAAiB;wBAC3B,SAAS,CAAC,KAAK;wBACf,SAAS,CAAC,OAAO;wBACjB,YAAY,CAAC;YACjB,CAAC;YAAC,MAAM,CAAC;YAET,CAAC;YAED,MAAM,IAAI,KAAK,CAAC,gCAAgC,YAAY,EAAE,CAAC,CAAC;QAClE,CAAC;QAED,OAAO,QAAQ,CAAC,IAAI,EAAsC,CAAC;IAC7D,CAAC;CACF;AAqBD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAC/B,WAAmC,EACnC,OAAgB,EACH,EAAE;IACf,OAAO,IAAI,WAAW,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;AACnD,CAAC,CAAC","sourcesContent":["import { getLogger } from './logger.js';\nimport {\n type SikkaApiError,\n type SikkaAuthorizedPractice,\n type SikkaAuthorizedPracticeListParams,\n type SikkaAuthorizedPracticeListResponse,\n type SikkaClaim,\n type SikkaClaimListParams,\n type SikkaClaimListResponse,\n type SikkaClaimPaymentRequest,\n type SikkaClaimPaymentResponse,\n type SikkaClaimPaymentResult,\n type SikkaClaimUpdateRequest,\n type SikkaClaimUpdateResponse,\n type SikkaClaimUpdateResult,\n type SikkaClientConfig,\n type SikkaClientCredentials,\n type SikkaInsuranceCompanyDetail,\n type SikkaInsuranceCompanyDetailListParams,\n type SikkaInsuranceCompanyDetailListResponse,\n type SikkaPatient,\n type SikkaPatientListParams,\n type SikkaPatientListResponse,\n type SikkaPaymentType,\n type SikkaPaymentTypeListParams,\n type SikkaPaymentTypeListResponse,\n type SikkaPracticeVariable,\n type SikkaPracticeVariableListParams,\n type SikkaPracticeVariableListResponse,\n type SikkaRequestKeyRequest,\n type SikkaRequestKeyResponse,\n type SikkaSubscriber,\n type SikkaSubscriberListParams,\n type SikkaSubscriberListResponse,\n type SikkaTransaction,\n type SikkaTransactionListParams,\n type SikkaTransactionListResponse,\n type SikkaWritebackStatusItem,\n type SikkaWritebackStatusResponse,\n} from './types.js';\n\nconst SIKKA_BASE_URL = 'https://api.sikkasoft.com';\n\nconst WRITEBACK_ID_PATTERN = /^Id:(\\d+)$/u;\n\n/**\n * Page size used when auto-paginating the authorized_practices endpoint.\n */\nconst AUTHORIZED_PRACTICES_PAGE_SIZE = 500;\n\n/**\n * Extract the numeric writeback tracking ID from the long_message field.\n * Expected format: \"Id:3809955\"\n */\nconst parseWritebackId = (longMessage: string | undefined): string | null => {\n if (!longMessage) {\n return null;\n }\n\n const match = WRITEBACK_ID_PATTERN.exec(longMessage);\n return match?.[1] ?? null;\n};\n\n/**\n * Sikka API Client\n *\n * Provides authenticated access to Sikka's ONE API for a specific practice/office.\n *\n * @example\n * ```typescript\n * const client = new SikkaClient({\n * credentials: {\n * appId: 'your-app-id',\n * appKey: 'your-app-key',\n * officeId: 'practice-office-id',\n * secretKey: 'practice-secret-key',\n * },\n * });\n *\n * await client.authenticate();\n *\n * const patients = await client.patients.list({ firstname: 'John' });\n * ```\n */\nexport class SikkaClient {\n /**\n * Authorized practices endpoints.\n * Returns your authorized practices with the Sikka practice utility last\n * refresh and data insert times.\n */\n public readonly authorizedPractices = {\n /**\n * Get a single authorized practice by its office ID.\n *\n * This is the primary access pattern for resolving \"what PMS does this\n * office run\", since `office_id` (e.g. \"D13303\") is the unique identifier\n * for a practice/office. Matching is a case-sensitive exact match.\n *\n * Internally this lists all authorized practices (`show: 'all'`, with\n * auto-pagination) and returns the first record whose `office_id` matches.\n *\n * @param officeId - The unique office ID to look up\n * @returns The matching authorized practice, or `null` if none matches\n *\n * @example\n * ```typescript\n * const practice = await client.authorizedPractices.getByOfficeId('D13303');\n * if (practice) {\n * console.log(practice.practice_management_system);\n * }\n * ```\n */\n getByOfficeId: async (\n officeId: string,\n ): Promise<SikkaAuthorizedPractice | null> => {\n const practices = await this.authorizedPractices.list({ show: 'all' });\n return (\n practices.find((practice) => practice.office_id === officeId) ?? null\n );\n },\n\n /**\n * List your authorized practices, auto-paginating to completion.\n *\n * By default the API returns only practice id 1. Pass `show: 'all'` to\n * retrieve every authorized office. This method follows the response\n * pagination (offset/limit + `pagination.next`) and accumulates all pages,\n * so the returned array contains every matching record.\n *\n * Items are returned RAW: no normalization, filtering, or coercion is\n * applied. In particular, `practice_management_system` values are\n * inconsistent in case/spelling across records — callers should normalize\n * themselves.\n *\n * WARNING: `practice_id` is NOT unique across offices — the live API can\n * return the same `practice_id` (e.g. \"1\") for every authorized office. Key\n * off `office_id` (e.g. \"D13303\") instead. See `getByOfficeId()`.\n *\n * @param params - Optional filter, sort, and pagination parameters. A\n * caller-supplied `offset`/`limit` controls the starting page and page\n * size; pagination then continues from there until all items are fetched.\n * @returns List of all authorized practices across every page\n *\n * @example\n * ```typescript\n * // Get the default practice\n * const practices = await client.authorizedPractices.list();\n *\n * // Get all authorized practices (across all pages)\n * const allPractices = await client.authorizedPractices.list({\n * show: 'all',\n * });\n * ```\n */\n list: async (\n params: SikkaAuthorizedPracticeListParams = {},\n ): Promise<SikkaAuthorizedPractice[]> => {\n const items: SikkaAuthorizedPractice[] = [];\n\n // Sikka's `offset` is a 0-indexed PAGE NUMBER (not a record offset): the\n // next page is `offset + 1` with `limit` held constant. To stay correct\n // regardless of those semantics, we never compute the next offset\n // ourselves — we follow the `pagination.next` URL's query params verbatim.\n let offset: number | string = params.offset ?? 0;\n let limit: number | string =\n params.limit ?? AUTHORIZED_PRACTICES_PAGE_SIZE;\n\n for (;;) {\n const response: SikkaAuthorizedPracticeListResponse =\n await this.get<SikkaAuthorizedPracticeListResponse>(\n '/v4/authorized_practices',\n { ...params, limit, offset },\n );\n\n const pageItems = response.items ?? [];\n items.push(...pageItems);\n\n const totalCount = Number.parseInt(response.total_count, 10);\n const pageSize = Number.parseInt(String(limit), 10);\n const nextUrl = response.pagination?.next;\n\n // Stop when the page came back empty, we've reached the reported\n // total, the API reported no next page, or the page was not full\n // (a reliable \"last page\" signal that guards against infinite loops).\n if (\n pageItems.length === 0 ||\n (!Number.isNaN(totalCount) && items.length >= totalCount) ||\n !nextUrl ||\n (!Number.isNaN(pageSize) && pageItems.length < pageSize)\n ) {\n break;\n }\n\n // Advance strictly by what the API tells us, rather than doing\n // `offset += limit` arithmetic (which would be wrong for page-number\n // semantics).\n const nextSearch = new URL(nextUrl).searchParams;\n offset = nextSearch.get('offset') ?? offset;\n limit = nextSearch.get('limit') ?? limit;\n }\n\n return items;\n },\n };\n\n /**\n * Claim payment endpoints.\n */\n public readonly claimPayment = {\n /**\n * Post a payment to a claim.\n *\n * The Sikka API accepts the request (201) but the actual PMS writeback\n * is asynchronous. The returned `writeback_id` can be used with\n * `writebackStatus.get()` to poll for completion.\n *\n * @param request - Payment details\n * @returns Payment response with parsed writeback tracking ID\n *\n * @example\n * ```typescript\n * const result = await client.claimPayment.post({\n * claim_sr_no: '123456',\n * practice_id: 'practice-id',\n * payment_amount: '100.00|50.00',\n * transaction_sr_no: '789|790',\n * deductible: '0.00|0.00',\n * write_off: '0.00|0.00',\n * claim_payment_date: '2024-01-15',\n * payment_mode: 'EFT',\n * is_payment_by_procedure_code: 'true',\n * note: 'Insurance payment',\n * });\n *\n * if (result.writeback_id) {\n * const status = await client.writebackStatus.get(result.writeback_id);\n * }\n * ```\n */\n post: async (\n request: SikkaClaimPaymentRequest,\n ): Promise<SikkaClaimPaymentResult> => {\n const response = await this.post<SikkaClaimPaymentResponse>(\n '/v4/claim_payment',\n request as unknown as Record<string, unknown>,\n );\n const writebackId = parseWritebackId(response.long_message);\n return { ...response, writeback_id: writebackId };\n },\n };\n\n /**\n * Claims management endpoints.\n */\n public readonly claims = {\n /**\n * List claims matching the given criteria.\n *\n * @param params - Search parameters\n * @returns List of matching claims\n *\n * @example\n * ```typescript\n * const claims = await client.claims.list({\n * patient_id: '12345',\n * status: 'Pending',\n * start_date: '2024-01-01',\n * end_date: '2024-12-31',\n * });\n * ```\n */\n list: async (params: SikkaClaimListParams): Promise<SikkaClaim[]> => {\n const response = await this.get<SikkaClaimListResponse>(\n '/v4/claims',\n params,\n );\n return response.items;\n },\n\n /**\n * Update a claim's status and/or note.\n *\n * The Sikka API accepts the request but the actual PMS writeback\n * is asynchronous. The returned `writeback_id` can be used with\n * `writebackStatus.get()` to poll for completion.\n *\n * At least one of `status` or `note` must be provided.\n *\n * @param request - Claim update details including claim_sr_no\n * @returns Update response with parsed writeback tracking ID\n *\n * @example\n * ```typescript\n * const result = await client.claims.update({\n * claim_sr_no: '123456',\n * practice_id: 'practice-id',\n * status: 'Received',\n * note: 'Claim received and under review',\n * });\n *\n * if (result.writeback_id) {\n * const status = await client.writebackStatus.get(result.writeback_id);\n * }\n * ```\n */\n update: async (\n request: SikkaClaimUpdateRequest,\n ): Promise<SikkaClaimUpdateResult> => {\n const { claim_sr_no: claimSrNo, ...body } = request;\n const response = await this.patch<SikkaClaimUpdateResponse>(\n `/v4/claims/${claimSrNo}`,\n body as unknown as Record<string, unknown>,\n );\n const writebackId = parseWritebackId(response.long_message);\n return { ...response, writeback_id: writebackId };\n },\n };\n\n /**\n * Insurance company details endpoints.\n * Returns insurance company information associated with practices.\n */\n public readonly insuranceCompanyDetails = {\n /**\n * List insurance company details, optionally filtered by practice or company.\n *\n * @param params - Optional filter, sort, and pagination parameters\n * @returns List of insurance company details\n *\n * @example\n * ```typescript\n * // Get all insurance companies\n * const companies = await client.insuranceCompanyDetails.list();\n *\n * // Get insurance companies for a specific practice\n * const practiceCompanies = await client.insuranceCompanyDetails.list({\n * practice_id: '1',\n * });\n * ```\n */\n list: async (\n params: SikkaInsuranceCompanyDetailListParams = {},\n ): Promise<SikkaInsuranceCompanyDetail[]> => {\n const response = await this.get<SikkaInsuranceCompanyDetailListResponse>(\n '/v4/insurance_company_details',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Patient management endpoints.\n */\n public readonly patients = {\n /**\n * List patients matching the given criteria.\n *\n * @param params - Search parameters\n * @returns List of matching patients\n *\n * @example\n * ```typescript\n * const patients = await client.patients.list({\n * firstname: 'John',\n * lastname: 'Doe',\n * });\n * ```\n */\n list: async (params: SikkaPatientListParams): Promise<SikkaPatient[]> => {\n const response = await this.get<SikkaPatientListResponse>(\n '/v4/patients',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Payment types management endpoints.\n * Payment types represent the different methods a practice accepts for payments.\n */\n public readonly paymentTypes = {\n /**\n * List payment types for the practice.\n *\n * @param params - Optional filter and pagination parameters\n * @returns List of payment types\n *\n * @example\n * ```typescript\n * // Get all payment types\n * const types = await client.paymentTypes.list();\n *\n * // Get only insurance payment types\n * const insuranceTypes = await client.paymentTypes.list({\n * is_insurance_type: true,\n * });\n * ```\n */\n list: async (\n params: SikkaPaymentTypeListParams = {},\n ): Promise<SikkaPaymentType[]> => {\n const response = await this.get<SikkaPaymentTypeListResponse>(\n '/v4/payment_types',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Practice variables endpoints.\n * Returns configurable values from the practice management system such as\n * appointment statuses, claim statuses, and patient statuses.\n */\n public readonly practiceVariables = {\n /**\n * List practice variables, optionally filtered by service name.\n *\n * @param params - Optional filter and pagination parameters\n * @returns List of practice variables\n *\n * @example\n * ```typescript\n * // Get all claim statuses\n * const claimStatuses = await client.practiceVariables.list({\n * service_name: 'Claim Status',\n * });\n *\n * // Use the value field for claims.update()\n * const validStatuses = claimStatuses.map(v => v.value);\n * ```\n */\n list: async (\n params: SikkaPracticeVariableListParams = {},\n ): Promise<SikkaPracticeVariable[]> => {\n const response = await this.get<SikkaPracticeVariableListResponse>(\n '/v4/practice_variables',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Subscribers endpoints.\n * Returns insurance subscriber data associated with patients in practices.\n */\n public readonly subscribers = {\n /**\n * List subscribers, optionally filtered by patient, practice, or subscriber ID.\n *\n * @param params - Optional filter, sort, and pagination parameters\n * @returns List of subscribers\n *\n * @example\n * ```typescript\n * // Get all subscribers\n * const subscribers = await client.subscribers.list();\n *\n * // Get subscribers for a specific patient\n * const patientSubscribers = await client.subscribers.list({\n * patient_id: '994',\n * });\n * ```\n */\n list: async (\n params: SikkaSubscriberListParams = {},\n ): Promise<SikkaSubscriber[]> => {\n const response = await this.get<SikkaSubscriberListResponse>(\n '/v4/subscribers',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Transactions management endpoints.\n * Transactions include both procedures (service line items) and payments.\n */\n public readonly transactions = {\n /**\n * List transactions matching the given criteria.\n *\n * @param params - Search parameters\n * @returns List of matching transactions\n *\n * @example\n * ```typescript\n * const transactions = await client.transactions.list({\n * claim_sr_no: '123456',\n * });\n * ```\n */\n list: async (\n params: SikkaTransactionListParams,\n ): Promise<SikkaTransaction[]> => {\n const response = await this.get<SikkaTransactionListResponse>(\n '/v4/transactions',\n params,\n );\n return response.items;\n },\n\n /**\n * List only procedure transactions for a specific claim.\n *\n * @param claimSrNo - The claim serial number\n * @returns List of procedure transactions\n */\n listProcedures: async (claimSrNo: string): Promise<SikkaTransaction[]> => {\n const transactions = await this.transactions.list({\n claim_sr_no: claimSrNo,\n });\n return transactions.filter((txn) => txn.transaction_type === 'Procedure');\n },\n };\n\n /**\n * Writeback status endpoints.\n * Used to poll for the result of asynchronous PMS writeback operations\n * (e.g., after posting a claim payment).\n */\n public readonly writebackStatus = {\n /**\n * Get the status of a writeback operation.\n *\n * @param id - The writeback tracking ID (returned from claimPayment.post as writeback_id)\n * @returns The writeback status record\n *\n * @example\n * ```typescript\n * const result = await client.claimPayment.post({ ... });\n * if (result.writeback_id) {\n * const status = await client.writebackStatus.get(result.writeback_id);\n * console.log(status.status, status.is_completed);\n * }\n * ```\n */\n get: async (id: string): Promise<SikkaWritebackStatusItem> => {\n const response = await this.get<SikkaWritebackStatusResponse>(\n '/v4/writeback_status',\n { id },\n );\n const item = response.items[0];\n if (!item) {\n throw new Error(`No writeback status found for id: ${id}`);\n }\n\n return item;\n },\n };\n\n private readonly baseUrl: string;\n\n private readonly credentials: SikkaClientCredentials;\n\n private refreshKey: string | null = null;\n\n private requestKey: string | null = null;\n\n private requestKeyExpiresAt: Date | null = null;\n\n constructor(config: SikkaClientConfig) {\n this.baseUrl = config.baseUrl ?? SIKKA_BASE_URL;\n this.credentials = config.credentials;\n }\n\n /**\n * Authenticate with the Sikka API.\n * Must be called before making any other API requests.\n * The request key is valid for 24 hours.\n */\n async authenticate(): Promise<void> {\n const log = getLogger();\n\n log.debug('Sikka API: Authenticating');\n\n const requestBody: SikkaRequestKeyRequest = {\n app_id: this.credentials.appId,\n app_key: this.credentials.appKey,\n grant_type: 'request_key',\n office_id: this.credentials.officeId,\n secret_key: this.credentials.secretKey,\n };\n\n const response = await this.requestNewKey(requestBody);\n this.requestKey = response.request_key;\n this.refreshKey = response.refresh_key;\n this.requestKeyExpiresAt = new Date(response.end_time);\n\n log.debug('Sikka API: Authenticated successfully', {\n expiresAt: this.requestKeyExpiresAt.toISOString(),\n });\n }\n\n /**\n * Clear the current authentication state.\n */\n clearAuth(): void {\n this.requestKey = null;\n this.refreshKey = null;\n this.requestKeyExpiresAt = null;\n }\n\n /**\n * Ensure the client is authenticated, refreshing if necessary.\n * Automatically refreshes if token expires within 1 hour.\n */\n async ensureAuthenticated(): Promise<void> {\n if (!this.requestKey) {\n throw new Error('Not authenticated. Call authenticate() first.');\n }\n\n const oneHourFromNow = new Date(Date.now() + 60 * 60 * 1_000);\n if (this.requestKeyExpiresAt && this.requestKeyExpiresAt < oneHourFromNow) {\n await this.refreshAuthentication();\n }\n }\n\n /**\n * Make an authenticated GET request to the Sikka API.\n */\n async get<T>(endpoint: string, params?: Record<string, unknown>): Promise<T> {\n const log = getLogger();\n\n await this.ensureAuthenticated();\n\n const requestKey = this.getRequestKey();\n const url = new URL(`${this.baseUrl}${endpoint}`);\n url.searchParams.set('request_key', requestKey);\n\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== null && value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n log.debug('Sikka API GET request', { endpoint, params });\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n 'Request-Key': requestKey,\n },\n method: 'GET',\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n throw new Error(\n `Sikka API GET ${endpoint} failed: ${response.status} ${response.statusText} - ${errorBody}`,\n );\n }\n\n const text = await response.text();\n if (!text || text.trim() === '') {\n return { items: [] } as T;\n }\n\n const data = JSON.parse(text) as T;\n\n log.debug('Sikka API GET response', { endpoint, status: response.status });\n\n return data;\n }\n\n /**\n * Get the current request key.\n *\n * @throws Error if not authenticated\n */\n getRequestKey(): string {\n if (!this.requestKey) {\n throw new Error('Not authenticated. Call authenticate() first.');\n }\n\n return this.requestKey;\n }\n\n // -------------------------------------------------------------------------\n // API Modules\n\n /**\n * Check if the client is currently authenticated with a valid token.\n */\n isAuthenticated(): boolean {\n if (!this.requestKey || !this.requestKeyExpiresAt) {\n return false;\n }\n\n return this.requestKeyExpiresAt > new Date();\n }\n\n /**\n * Make an authenticated PATCH request to the Sikka API.\n */\n async patch<T>(endpoint: string, body: Record<string, unknown>): Promise<T> {\n const log = getLogger();\n\n await this.ensureAuthenticated();\n\n const requestKey = this.getRequestKey();\n const url = new URL(`${this.baseUrl}${endpoint}`);\n url.searchParams.set('request_key', requestKey);\n\n log.debug('Sikka API PATCH request', { body, endpoint });\n\n const response = await fetch(url.toString(), {\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': 'application/json',\n 'Request-Key': requestKey,\n },\n method: 'PATCH',\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n throw new Error(\n `Sikka API PATCH ${endpoint} failed: ${response.status} ${response.statusText} - ${errorBody}`,\n );\n }\n\n const data = (await response.json()) as T;\n\n log.debug('Sikka API PATCH response', {\n endpoint,\n status: response.status,\n });\n\n return data;\n }\n\n /**\n * Make an authenticated POST request to the Sikka API.\n */\n async post<T>(endpoint: string, body: Record<string, unknown>): Promise<T> {\n const log = getLogger();\n\n await this.ensureAuthenticated();\n\n const requestKey = this.getRequestKey();\n const url = new URL(`${this.baseUrl}${endpoint}`);\n url.searchParams.set('request_key', requestKey);\n\n log.debug('Sikka API POST request', { body, endpoint });\n\n const response = await fetch(url.toString(), {\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': 'application/json',\n 'Request-Key': requestKey,\n },\n method: 'POST',\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n throw new Error(\n `Sikka API POST ${endpoint} failed: ${response.status} ${response.statusText} - ${errorBody}`,\n );\n }\n\n const data = (await response.json()) as T;\n\n log.debug('Sikka API POST response', { endpoint, status: response.status });\n\n return data;\n }\n\n /**\n * Refresh the authentication token using the refresh key.\n * Called automatically when token is near expiration.\n */\n async refreshAuthentication(): Promise<void> {\n const log = getLogger();\n\n if (!this.refreshKey) {\n throw new Error('No refresh key available. Call authenticate() first.');\n }\n\n log.debug('Sikka API: Refreshing authentication');\n\n const requestBody: SikkaRequestKeyRequest = {\n app_id: this.credentials.appId,\n app_key: this.credentials.appKey,\n grant_type: 'refresh_key',\n refresh_key: this.refreshKey,\n };\n\n const response = await this.requestNewKey(requestBody);\n this.requestKey = response.request_key;\n this.refreshKey = response.refresh_key;\n this.requestKeyExpiresAt = new Date(response.end_time);\n\n log.debug('Sikka API: Authentication refreshed', {\n expiresAt: this.requestKeyExpiresAt.toISOString(),\n });\n }\n\n private async requestNewKey(\n requestBody: SikkaRequestKeyRequest,\n ): Promise<SikkaRequestKeyResponse> {\n const response = await fetch(`${this.baseUrl}/v4/request_key`, {\n body: JSON.stringify(requestBody),\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n });\n\n if (!response.ok) {\n let errorMessage = `${response.status} ${response.statusText}`;\n try {\n const errorBody = (await response.json()) as SikkaApiError;\n errorMessage =\n errorBody.error_description ??\n errorBody.error ??\n errorBody.message ??\n errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n\n throw new Error(`Sikka authentication failed: ${errorMessage}`);\n }\n\n return response.json() as Promise<SikkaRequestKeyResponse>;\n }\n}\n\n/**\n * Create a new Sikka client instance.\n *\n * @param credentials - Office-level credentials\n * @param baseUrl - Optional base URL override\n * @returns A new SikkaClient instance\n *\n * @example\n * ```typescript\n * const client = createSikkaClient({\n * appId: 'your-app-id',\n * appKey: 'your-app-key',\n * officeId: 'practice-office-id',\n * secretKey: 'practice-secret-key',\n * });\n *\n * await client.authenticate();\n * ```\n */\nexport const createSikkaClient = (\n credentials: SikkaClientCredentials,\n baseUrl?: string,\n): SikkaClient => {\n return new SikkaClient({ baseUrl, credentials });\n};\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/lib/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAyCxC,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAEnD,MAAM,oBAAoB,GAAG,aAAa,CAAC;AAK3C,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAM3C,MAAM,gBAAgB,GAAG,CAAC,WAA+B,EAAiB,EAAE;IAC1E,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,KAAK,GAAG,oBAAoB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACrD,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;AAC5B,CAAC,CAAC;AAuBF,MAAM,OAAO,WAAW;IAUN,mBAAmB,GAAG;QAuBpC,aAAa,EAAE,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C;QAClE,CAAC;QAED,OAAO,QAAQ,CAAC,IAAI,EAAsC,CAAC;IAC7D,CAAC;CACF;AAqBD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAC/B,WAAmC,EACnC,OAAgB,EACH,EAAE;IACf,OAAO,IAAI,WAAW,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;AACnD,CAAC,CAAC","sourcesContent":["import { getLogger } from './logger.js';\nimport {\n type SikkaApiError,\n type SikkaAuthorizedPractice,\n type SikkaAuthorizedPracticeListParams,\n type SikkaAuthorizedPracticeListResponse,\n type SikkaClaim,\n type SikkaClaimListParams,\n type SikkaClaimListResponse,\n type SikkaClaimPaymentRequest,\n type SikkaClaimPaymentResponse,\n type SikkaClaimPaymentResult,\n type SikkaClaimUpdateRequest,\n type SikkaClaimUpdateResponse,\n type SikkaClaimUpdateResult,\n type SikkaClientConfig,\n type SikkaClientCredentials,\n type SikkaInsuranceCompanyDetail,\n type SikkaInsuranceCompanyDetailListParams,\n type SikkaInsuranceCompanyDetailListResponse,\n type SikkaPatient,\n type SikkaPatientListParams,\n type SikkaPatientListResponse,\n type SikkaPaymentType,\n type SikkaPaymentTypeListParams,\n type SikkaPaymentTypeListResponse,\n type SikkaPracticeVariable,\n type SikkaPracticeVariableListParams,\n type SikkaPracticeVariableListResponse,\n type SikkaRequestKeyRequest,\n type SikkaRequestKeyResponse,\n type SikkaSubscriber,\n type SikkaSubscriberListParams,\n type SikkaSubscriberListResponse,\n type SikkaTransaction,\n type SikkaTransactionListParams,\n type SikkaTransactionListResponse,\n type SikkaWritebackStatusItem,\n type SikkaWritebackStatusResponse,\n} from './types.js';\n\nconst SIKKA_BASE_URL = 'https://api.sikkasoft.com';\n\nconst WRITEBACK_ID_PATTERN = /^Id:(\\d+)$/u;\n\n/**\n * Page size used when auto-paginating the authorized_practices endpoint.\n */\nconst AUTHORIZED_PRACTICES_PAGE_SIZE = 500;\n\n/**\n * Extract the numeric writeback tracking ID from the long_message field.\n * Expected format: \"Id:3809955\"\n */\nconst parseWritebackId = (longMessage: string | undefined): string | null => {\n if (!longMessage) {\n return null;\n }\n\n const match = WRITEBACK_ID_PATTERN.exec(longMessage);\n return match?.[1] ?? null;\n};\n\n/**\n * Sikka API Client\n *\n * Provides authenticated access to Sikka's ONE API for a specific practice/office.\n *\n * @example\n * ```typescript\n * const client = new SikkaClient({\n * credentials: {\n * appId: 'your-app-id',\n * appKey: 'your-app-key',\n * officeId: 'practice-office-id',\n * secretKey: 'practice-secret-key',\n * },\n * });\n *\n * await client.authenticate();\n *\n * const patients = await client.patients.list({ firstname: 'John' });\n * ```\n */\nexport class SikkaClient {\n /**\n * Authorized practices endpoints.\n * Returns your authorized practices with the Sikka practice utility last\n * refresh and data insert times.\n *\n * This is an application-scoped resource: requests authenticate with the\n * application credentials (`App-Id` / `App-Key` headers), so no prior\n * `authenticate()` call is required.\n */\n public readonly authorizedPractices = {\n /**\n * Get a single authorized practice by its office ID.\n *\n * This is the primary access pattern for resolving \"what PMS does this\n * office run\", since `office_id` (e.g. \"D13303\") is the unique identifier\n * for a practice/office. Matching is a case-sensitive exact match.\n *\n * Internally this lists all authorized practices (`show: 'all'`, with\n * auto-pagination) and returns the first record whose `office_id` matches.\n * Application-scoped: no prior `authenticate()` call is required.\n *\n * @param officeId - The unique office ID to look up\n * @returns The matching authorized practice, or `null` if none matches\n *\n * @example\n * ```typescript\n * const practice = await client.authorizedPractices.getByOfficeId('D13303');\n * if (practice) {\n * console.log(practice.practice_management_system);\n * }\n * ```\n */\n getByOfficeId: async (\n officeId: string,\n ): Promise<SikkaAuthorizedPractice | null> => {\n const practices = await this.authorizedPractices.list({ show: 'all' });\n return (\n practices.find((practice) => practice.office_id === officeId) ?? null\n );\n },\n\n /**\n * List your authorized practices, auto-paginating to completion.\n *\n * By default the API returns only practice id 1. Pass `show: 'all'` to\n * retrieve every authorized office. This method follows the response\n * pagination (offset/limit + `pagination.next`) and accumulates all pages,\n * so the returned array contains every matching record.\n *\n * Application-scoped: requests use the `App-Id` / `App-Key` headers, so no\n * prior `authenticate()` call is required.\n *\n * Items are returned RAW: no normalization, filtering, or coercion is\n * applied. In particular, `practice_management_system` values are\n * inconsistent in case/spelling across records — callers should normalize\n * themselves.\n *\n * WARNING: `practice_id` is NOT unique across offices — the live API can\n * return the same `practice_id` (e.g. \"1\") for every authorized office. Key\n * off `office_id` (e.g. \"D13303\") instead. See `getByOfficeId()`.\n *\n * @param params - Optional filter, sort, and pagination parameters. A\n * caller-supplied `offset`/`limit` controls the starting page and page\n * size; pagination then continues from there until all items are fetched.\n * @returns List of all authorized practices across every page\n *\n * @example\n * ```typescript\n * // Get the default practice\n * const practices = await client.authorizedPractices.list();\n *\n * // Get all authorized practices (across all pages)\n * const allPractices = await client.authorizedPractices.list({\n * show: 'all',\n * });\n * ```\n */\n list: async (\n params: SikkaAuthorizedPracticeListParams = {},\n ): Promise<SikkaAuthorizedPractice[]> => {\n const items: SikkaAuthorizedPractice[] = [];\n\n // Sikka's `offset` is a 0-indexed PAGE NUMBER (not a record offset): the\n // next page is `offset + 1` with `limit` held constant. To stay correct\n // regardless of those semantics, we never compute the next offset\n // ourselves — we follow the `pagination.next` URL's query params verbatim.\n let offset: number | string = params.offset ?? 0;\n let limit: number | string =\n params.limit ?? AUTHORIZED_PRACTICES_PAGE_SIZE;\n\n for (;;) {\n const response: SikkaAuthorizedPracticeListResponse =\n await this.appAuthGet<SikkaAuthorizedPracticeListResponse>(\n '/v4/authorized_practices',\n { ...params, limit, offset },\n );\n\n const pageItems = response.items ?? [];\n items.push(...pageItems);\n\n const totalCount = Number.parseInt(response.total_count, 10);\n const pageSize = Number.parseInt(String(limit), 10);\n const nextUrl = response.pagination?.next;\n\n // Stop when the page came back empty, we've reached the reported\n // total, the API reported no next page, or the page was not full\n // (a reliable \"last page\" signal that guards against infinite loops).\n if (\n pageItems.length === 0 ||\n (!Number.isNaN(totalCount) && items.length >= totalCount) ||\n !nextUrl ||\n (!Number.isNaN(pageSize) && pageItems.length < pageSize)\n ) {\n break;\n }\n\n // Advance strictly by what the API tells us, rather than doing\n // `offset += limit` arithmetic (which would be wrong for page-number\n // semantics).\n const nextSearch = new URL(nextUrl).searchParams;\n offset = nextSearch.get('offset') ?? offset;\n limit = nextSearch.get('limit') ?? limit;\n }\n\n return items;\n },\n };\n\n /**\n * Claim payment endpoints.\n */\n public readonly claimPayment = {\n /**\n * Post a payment to a claim.\n *\n * The Sikka API accepts the request (201) but the actual PMS writeback\n * is asynchronous. The returned `writeback_id` can be used with\n * `writebackStatus.get()` to poll for completion.\n *\n * @param request - Payment details\n * @returns Payment response with parsed writeback tracking ID\n *\n * @example\n * ```typescript\n * const result = await client.claimPayment.post({\n * claim_sr_no: '123456',\n * practice_id: 'practice-id',\n * payment_amount: '100.00|50.00',\n * transaction_sr_no: '789|790',\n * deductible: '0.00|0.00',\n * write_off: '0.00|0.00',\n * claim_payment_date: '2024-01-15',\n * payment_mode: 'EFT',\n * is_payment_by_procedure_code: 'true',\n * note: 'Insurance payment',\n * });\n *\n * if (result.writeback_id) {\n * const status = await client.writebackStatus.get(result.writeback_id);\n * }\n * ```\n */\n post: async (\n request: SikkaClaimPaymentRequest,\n ): Promise<SikkaClaimPaymentResult> => {\n const response = await this.post<SikkaClaimPaymentResponse>(\n '/v4/claim_payment',\n request as unknown as Record<string, unknown>,\n );\n const writebackId = parseWritebackId(response.long_message);\n return { ...response, writeback_id: writebackId };\n },\n };\n\n /**\n * Claims management endpoints.\n */\n public readonly claims = {\n /**\n * List claims matching the given criteria.\n *\n * @param params - Search parameters\n * @returns List of matching claims\n *\n * @example\n * ```typescript\n * const claims = await client.claims.list({\n * patient_id: '12345',\n * status: 'Pending',\n * start_date: '2024-01-01',\n * end_date: '2024-12-31',\n * });\n * ```\n */\n list: async (params: SikkaClaimListParams): Promise<SikkaClaim[]> => {\n const response = await this.get<SikkaClaimListResponse>(\n '/v4/claims',\n params,\n );\n return response.items;\n },\n\n /**\n * Update a claim's status and/or note.\n *\n * The Sikka API accepts the request but the actual PMS writeback\n * is asynchronous. The returned `writeback_id` can be used with\n * `writebackStatus.get()` to poll for completion.\n *\n * At least one of `status` or `note` must be provided.\n *\n * @param request - Claim update details including claim_sr_no\n * @returns Update response with parsed writeback tracking ID\n *\n * @example\n * ```typescript\n * const result = await client.claims.update({\n * claim_sr_no: '123456',\n * practice_id: 'practice-id',\n * status: 'Received',\n * note: 'Claim received and under review',\n * });\n *\n * if (result.writeback_id) {\n * const status = await client.writebackStatus.get(result.writeback_id);\n * }\n * ```\n */\n update: async (\n request: SikkaClaimUpdateRequest,\n ): Promise<SikkaClaimUpdateResult> => {\n const { claim_sr_no: claimSrNo, ...body } = request;\n const response = await this.patch<SikkaClaimUpdateResponse>(\n `/v4/claims/${claimSrNo}`,\n body as unknown as Record<string, unknown>,\n );\n const writebackId = parseWritebackId(response.long_message);\n return { ...response, writeback_id: writebackId };\n },\n };\n\n /**\n * Insurance company details endpoints.\n * Returns insurance company information associated with practices.\n */\n public readonly insuranceCompanyDetails = {\n /**\n * List insurance company details, optionally filtered by practice or company.\n *\n * @param params - Optional filter, sort, and pagination parameters\n * @returns List of insurance company details\n *\n * @example\n * ```typescript\n * // Get all insurance companies\n * const companies = await client.insuranceCompanyDetails.list();\n *\n * // Get insurance companies for a specific practice\n * const practiceCompanies = await client.insuranceCompanyDetails.list({\n * practice_id: '1',\n * });\n * ```\n */\n list: async (\n params: SikkaInsuranceCompanyDetailListParams = {},\n ): Promise<SikkaInsuranceCompanyDetail[]> => {\n const response = await this.get<SikkaInsuranceCompanyDetailListResponse>(\n '/v4/insurance_company_details',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Patient management endpoints.\n */\n public readonly patients = {\n /**\n * List patients matching the given criteria.\n *\n * @param params - Search parameters\n * @returns List of matching patients\n *\n * @example\n * ```typescript\n * const patients = await client.patients.list({\n * firstname: 'John',\n * lastname: 'Doe',\n * });\n * ```\n */\n list: async (params: SikkaPatientListParams): Promise<SikkaPatient[]> => {\n const response = await this.get<SikkaPatientListResponse>(\n '/v4/patients',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Payment types management endpoints.\n * Payment types represent the different methods a practice accepts for payments.\n */\n public readonly paymentTypes = {\n /**\n * List payment types for the practice.\n *\n * @param params - Optional filter and pagination parameters\n * @returns List of payment types\n *\n * @example\n * ```typescript\n * // Get all payment types\n * const types = await client.paymentTypes.list();\n *\n * // Get only insurance payment types\n * const insuranceTypes = await client.paymentTypes.list({\n * is_insurance_type: true,\n * });\n * ```\n */\n list: async (\n params: SikkaPaymentTypeListParams = {},\n ): Promise<SikkaPaymentType[]> => {\n const response = await this.get<SikkaPaymentTypeListResponse>(\n '/v4/payment_types',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Practice variables endpoints.\n * Returns configurable values from the practice management system such as\n * appointment statuses, claim statuses, and patient statuses.\n */\n public readonly practiceVariables = {\n /**\n * List practice variables, optionally filtered by service name.\n *\n * @param params - Optional filter and pagination parameters\n * @returns List of practice variables\n *\n * @example\n * ```typescript\n * // Get all claim statuses\n * const claimStatuses = await client.practiceVariables.list({\n * service_name: 'Claim Status',\n * });\n *\n * // Use the value field for claims.update()\n * const validStatuses = claimStatuses.map(v => v.value);\n * ```\n */\n list: async (\n params: SikkaPracticeVariableListParams = {},\n ): Promise<SikkaPracticeVariable[]> => {\n const response = await this.get<SikkaPracticeVariableListResponse>(\n '/v4/practice_variables',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Subscribers endpoints.\n * Returns insurance subscriber data associated with patients in practices.\n */\n public readonly subscribers = {\n /**\n * List subscribers, optionally filtered by patient, practice, or subscriber ID.\n *\n * @param params - Optional filter, sort, and pagination parameters\n * @returns List of subscribers\n *\n * @example\n * ```typescript\n * // Get all subscribers\n * const subscribers = await client.subscribers.list();\n *\n * // Get subscribers for a specific patient\n * const patientSubscribers = await client.subscribers.list({\n * patient_id: '994',\n * });\n * ```\n */\n list: async (\n params: SikkaSubscriberListParams = {},\n ): Promise<SikkaSubscriber[]> => {\n const response = await this.get<SikkaSubscriberListResponse>(\n '/v4/subscribers',\n params,\n );\n return response.items;\n },\n };\n\n /**\n * Transactions management endpoints.\n * Transactions include both procedures (service line items) and payments.\n */\n public readonly transactions = {\n /**\n * List transactions matching the given criteria.\n *\n * @param params - Search parameters\n * @returns List of matching transactions\n *\n * @example\n * ```typescript\n * const transactions = await client.transactions.list({\n * claim_sr_no: '123456',\n * });\n * ```\n */\n list: async (\n params: SikkaTransactionListParams,\n ): Promise<SikkaTransaction[]> => {\n const response = await this.get<SikkaTransactionListResponse>(\n '/v4/transactions',\n params,\n );\n return response.items;\n },\n\n /**\n * List only procedure transactions for a specific claim.\n *\n * @param claimSrNo - The claim serial number\n * @returns List of procedure transactions\n */\n listProcedures: async (claimSrNo: string): Promise<SikkaTransaction[]> => {\n const transactions = await this.transactions.list({\n claim_sr_no: claimSrNo,\n });\n return transactions.filter((txn) => txn.transaction_type === 'Procedure');\n },\n };\n\n /**\n * Writeback status endpoints.\n * Used to poll for the result of asynchronous PMS writeback operations\n * (e.g., after posting a claim payment).\n */\n public readonly writebackStatus = {\n /**\n * Get the status of a writeback operation.\n *\n * @param id - The writeback tracking ID (returned from claimPayment.post as writeback_id)\n * @returns The writeback status record\n *\n * @example\n * ```typescript\n * const result = await client.claimPayment.post({ ... });\n * if (result.writeback_id) {\n * const status = await client.writebackStatus.get(result.writeback_id);\n * console.log(status.status, status.is_completed);\n * }\n * ```\n */\n get: async (id: string): Promise<SikkaWritebackStatusItem> => {\n const response = await this.get<SikkaWritebackStatusResponse>(\n '/v4/writeback_status',\n { id },\n );\n const item = response.items[0];\n if (!item) {\n throw new Error(`No writeback status found for id: ${id}`);\n }\n\n return item;\n },\n };\n\n private readonly baseUrl: string;\n\n private readonly credentials: SikkaClientCredentials;\n\n private refreshKey: string | null = null;\n\n private requestKey: string | null = null;\n\n private requestKeyExpiresAt: Date | null = null;\n\n constructor(config: SikkaClientConfig) {\n this.baseUrl = config.baseUrl ?? SIKKA_BASE_URL;\n this.credentials = config.credentials;\n }\n\n /**\n * Make an application-scoped GET request to the Sikka API.\n *\n * Used for endpoints that authenticate with the application credentials\n * (`App-Id` / `App-Key` headers) rather than the per-office request_key\n * scheme — e.g. `/v4/authorized_practices`. This does NOT require a prior\n * `authenticate()` call and does NOT set the `request_key` query param.\n */\n async appAuthGet<T>(\n endpoint: string,\n params?: Record<string, unknown>,\n ): Promise<T> {\n const log = getLogger();\n\n const url = new URL(`${this.baseUrl}${endpoint}`);\n\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== null && value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n log.debug('Sikka API app-auth GET request', { endpoint, params });\n\n const response = await fetch(url.toString(), {\n headers: {\n 'App-Id': this.credentials.appId,\n 'App-Key': this.credentials.appKey,\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n throw new Error(\n `Sikka API GET ${endpoint} failed: ${response.status} ${response.statusText} - ${errorBody}`,\n );\n }\n\n const text = await response.text();\n if (!text || text.trim() === '') {\n return { items: [] } as T;\n }\n\n const data = JSON.parse(text) as T;\n\n log.debug('Sikka API app-auth GET response', {\n endpoint,\n status: response.status,\n });\n\n return data;\n }\n\n /**\n * Authenticate with the Sikka API.\n * Must be called before making any other API requests.\n * The request key is valid for 24 hours.\n */\n async authenticate(): Promise<void> {\n const log = getLogger();\n\n log.debug('Sikka API: Authenticating');\n\n const requestBody: SikkaRequestKeyRequest = {\n app_id: this.credentials.appId,\n app_key: this.credentials.appKey,\n grant_type: 'request_key',\n office_id: this.credentials.officeId,\n secret_key: this.credentials.secretKey,\n };\n\n const response = await this.requestNewKey(requestBody);\n this.requestKey = response.request_key;\n this.refreshKey = response.refresh_key;\n this.requestKeyExpiresAt = new Date(response.end_time);\n\n log.debug('Sikka API: Authenticated successfully', {\n expiresAt: this.requestKeyExpiresAt.toISOString(),\n });\n }\n\n /**\n * Clear the current authentication state.\n */\n clearAuth(): void {\n this.requestKey = null;\n this.refreshKey = null;\n this.requestKeyExpiresAt = null;\n }\n\n /**\n * Ensure the client is authenticated, refreshing if necessary.\n * Automatically refreshes if token expires within 1 hour.\n */\n async ensureAuthenticated(): Promise<void> {\n if (!this.requestKey) {\n throw new Error('Not authenticated. Call authenticate() first.');\n }\n\n const oneHourFromNow = new Date(Date.now() + 60 * 60 * 1_000);\n if (this.requestKeyExpiresAt && this.requestKeyExpiresAt < oneHourFromNow) {\n await this.refreshAuthentication();\n }\n }\n\n /**\n * Make an authenticated GET request to the Sikka API.\n */\n async get<T>(endpoint: string, params?: Record<string, unknown>): Promise<T> {\n const log = getLogger();\n\n await this.ensureAuthenticated();\n\n const requestKey = this.getRequestKey();\n const url = new URL(`${this.baseUrl}${endpoint}`);\n url.searchParams.set('request_key', requestKey);\n\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n if (value !== null && value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n log.debug('Sikka API GET request', { endpoint, params });\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n 'Request-Key': requestKey,\n },\n method: 'GET',\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n throw new Error(\n `Sikka API GET ${endpoint} failed: ${response.status} ${response.statusText} - ${errorBody}`,\n );\n }\n\n const text = await response.text();\n if (!text || text.trim() === '') {\n return { items: [] } as T;\n }\n\n const data = JSON.parse(text) as T;\n\n log.debug('Sikka API GET response', { endpoint, status: response.status });\n\n return data;\n }\n\n /**\n * Get the current request key.\n *\n * @throws Error if not authenticated\n */\n getRequestKey(): string {\n if (!this.requestKey) {\n throw new Error('Not authenticated. Call authenticate() first.');\n }\n\n return this.requestKey;\n }\n\n // -------------------------------------------------------------------------\n // API Modules\n\n /**\n * Check if the client is currently authenticated with a valid token.\n */\n isAuthenticated(): boolean {\n if (!this.requestKey || !this.requestKeyExpiresAt) {\n return false;\n }\n\n return this.requestKeyExpiresAt > new Date();\n }\n\n /**\n * Make an authenticated PATCH request to the Sikka API.\n */\n async patch<T>(endpoint: string, body: Record<string, unknown>): Promise<T> {\n const log = getLogger();\n\n await this.ensureAuthenticated();\n\n const requestKey = this.getRequestKey();\n const url = new URL(`${this.baseUrl}${endpoint}`);\n url.searchParams.set('request_key', requestKey);\n\n log.debug('Sikka API PATCH request', { body, endpoint });\n\n const response = await fetch(url.toString(), {\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': 'application/json',\n 'Request-Key': requestKey,\n },\n method: 'PATCH',\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n throw new Error(\n `Sikka API PATCH ${endpoint} failed: ${response.status} ${response.statusText} - ${errorBody}`,\n );\n }\n\n const data = (await response.json()) as T;\n\n log.debug('Sikka API PATCH response', {\n endpoint,\n status: response.status,\n });\n\n return data;\n }\n\n /**\n * Make an authenticated POST request to the Sikka API.\n */\n async post<T>(endpoint: string, body: Record<string, unknown>): Promise<T> {\n const log = getLogger();\n\n await this.ensureAuthenticated();\n\n const requestKey = this.getRequestKey();\n const url = new URL(`${this.baseUrl}${endpoint}`);\n url.searchParams.set('request_key', requestKey);\n\n log.debug('Sikka API POST request', { body, endpoint });\n\n const response = await fetch(url.toString(), {\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': 'application/json',\n 'Request-Key': requestKey,\n },\n method: 'POST',\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n throw new Error(\n `Sikka API POST ${endpoint} failed: ${response.status} ${response.statusText} - ${errorBody}`,\n );\n }\n\n const data = (await response.json()) as T;\n\n log.debug('Sikka API POST response', { endpoint, status: response.status });\n\n return data;\n }\n\n /**\n * Refresh the authentication token using the refresh key.\n * Called automatically when token is near expiration.\n */\n async refreshAuthentication(): Promise<void> {\n const log = getLogger();\n\n if (!this.refreshKey) {\n throw new Error('No refresh key available. Call authenticate() first.');\n }\n\n log.debug('Sikka API: Refreshing authentication');\n\n const requestBody: SikkaRequestKeyRequest = {\n app_id: this.credentials.appId,\n app_key: this.credentials.appKey,\n grant_type: 'refresh_key',\n refresh_key: this.refreshKey,\n };\n\n const response = await this.requestNewKey(requestBody);\n this.requestKey = response.request_key;\n this.refreshKey = response.refresh_key;\n this.requestKeyExpiresAt = new Date(response.end_time);\n\n log.debug('Sikka API: Authentication refreshed', {\n expiresAt: this.requestKeyExpiresAt.toISOString(),\n });\n }\n\n private async requestNewKey(\n requestBody: SikkaRequestKeyRequest,\n ): Promise<SikkaRequestKeyResponse> {\n const response = await fetch(`${this.baseUrl}/v4/request_key`, {\n body: JSON.stringify(requestBody),\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n });\n\n if (!response.ok) {\n let errorMessage = `${response.status} ${response.statusText}`;\n try {\n const errorBody = (await response.json()) as SikkaApiError;\n errorMessage =\n errorBody.error_description ??\n errorBody.error ??\n errorBody.message ??\n errorMessage;\n } catch {\n // Ignore JSON parse errors\n }\n\n throw new Error(`Sikka authentication failed: ${errorMessage}`);\n }\n\n return response.json() as Promise<SikkaRequestKeyResponse>;\n }\n}\n\n/**\n * Create a new Sikka client instance.\n *\n * @param credentials - Office-level credentials\n * @param baseUrl - Optional base URL override\n * @returns A new SikkaClient instance\n *\n * @example\n * ```typescript\n * const client = createSikkaClient({\n * appId: 'your-app-id',\n * appKey: 'your-app-key',\n * officeId: 'practice-office-id',\n * secretKey: 'practice-secret-key',\n * });\n *\n * await client.authenticate();\n * ```\n */\nexport const createSikkaClient = (\n credentials: SikkaClientCredentials,\n baseUrl?: string,\n): SikkaClient => {\n return new SikkaClient({ baseUrl, credentials });\n};\n"]}
|
|
@@ -39,6 +39,7 @@ export declare class SikkaClient {
|
|
|
39
39
|
private requestKey;
|
|
40
40
|
private requestKeyExpiresAt;
|
|
41
41
|
constructor(config: SikkaClientConfig);
|
|
42
|
+
appAuthGet<T>(endpoint: string, params?: Record<string, unknown>): Promise<T>;
|
|
42
43
|
authenticate(): Promise<void>;
|
|
43
44
|
clearAuth(): void;
|
|
44
45
|
ensureAuthenticated(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/lib/client.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,uBAAuB,EAC5B,KAAK,iCAAiC,EAEtC,KAAK,UAAU,EACf,KAAK,oBAAoB,EAEzB,KAAK,wBAAwB,EAE7B,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAE5B,KAAK,sBAAsB,EAC3B,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,KAAK,2BAA2B,EAChC,KAAK,qCAAqC,EAE1C,KAAK,YAAY,EACjB,KAAK,sBAAsB,EAE3B,KAAK,gBAAgB,EACrB,KAAK,0BAA0B,EAE/B,KAAK,qBAAqB,EAC1B,KAAK,+BAA+B,EAIpC,KAAK,eAAe,EACpB,KAAK,yBAAyB,EAE9B,KAAK,gBAAgB,EACrB,KAAK,0BAA0B,EAE/B,KAAK,wBAAwB,EAE9B,MAAM,YAAY,CAAC;AA6CpB,qBAAa,WAAW;
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/lib/client.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,uBAAuB,EAC5B,KAAK,iCAAiC,EAEtC,KAAK,UAAU,EACf,KAAK,oBAAoB,EAEzB,KAAK,wBAAwB,EAE7B,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAE5B,KAAK,sBAAsB,EAC3B,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,KAAK,2BAA2B,EAChC,KAAK,qCAAqC,EAE1C,KAAK,YAAY,EACjB,KAAK,sBAAsB,EAE3B,KAAK,gBAAgB,EACrB,KAAK,0BAA0B,EAE/B,KAAK,qBAAqB,EAC1B,KAAK,+BAA+B,EAIpC,KAAK,eAAe,EACpB,KAAK,yBAAyB,EAE9B,KAAK,gBAAgB,EACrB,KAAK,0BAA0B,EAE/B,KAAK,wBAAwB,EAE9B,MAAM,YAAY,CAAC;AA6CpB,qBAAa,W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