/** * Didox SDK configuration interface */ interface DidoxConfig { /** * Partner token provided by Didox for API access * Contact Didox representative to obtain this token */ partnerToken: string; /** * Environment to use for API calls * - development: https://stage.goodsign.biz/ * - production: https://api-partners.didox.uz/ */ environment: 'development' | 'production'; /** * Request timeout in milliseconds * @default 10000 */ timeout?: number; } /** * Internal configuration with resolved values */ interface ResolvedDidoxConfig { partnerToken: string; baseUrl: string; timeout: number; } /** * HTTP response interface */ interface HttpResponse { data: T; status: number; headers: Record; } /** * HTTP request options */ interface HttpRequestOptions { method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; headers?: Record; body?: unknown; timeout?: number; } /** * HTTP client configuration */ interface HttpClientConfig { baseUrl: string; timeout: number; defaultHeaders: Record; } /** * Internal HTTP client for Didox API * Uses native fetch API for minimal dependencies */ declare class HttpClient { private config; private accessToken; private partnerToken; constructor(config: HttpClientConfig); /** * Set the partner token for Partner-Authorization header */ setPartnerToken(token: string): void; /** * Set the access token for authenticated requests */ setAccessToken(token: string): void; /** * Clear the access token */ clearAccessToken(): void; /** * Make an HTTP request */ request(endpoint: string, options?: HttpRequestOptions): Promise>; /** * GET request */ get(endpoint: string, options?: Omit): Promise>; /** * POST request */ post(endpoint: string, body?: unknown, options?: Omit): Promise>; /** * PUT request */ put(endpoint: string, body?: unknown, options?: Omit): Promise>; /** * DELETE request */ delete(endpoint: string, options?: Omit): Promise>; } /** * Locale type for API requests */ type DidoxLocale = 'ru' | 'uz'; /** * Legal entity login request */ interface LegalEntityLoginRequest { /** * Tax Identification Number (exactly 9 or 14 digits) */ taxId: string; /** * Password (minimum 8 characters) */ password: string; /** * Locale for the response * @default 'ru' */ locale?: DidoxLocale; } /** * Related company information */ interface RelatedCompany { /** * Tax Identification Number */ tin: string; /** * Company name */ name: string; /** * Array of permission codes */ permissions: number[]; } /** * Legal entity login response */ interface LegalEntityLoginResponse { /** * Access token (UUID format) * Valid for 360 minutes */ token: string; /** * Related companies that this user can access */ related_companies: RelatedCompany[] | null; } /** * Company login as individual request */ interface CompanyLoginRequest { /** * Company Tax Identification Number (exactly 9 or 14 digits) */ companyTaxId: string; /** * User access token from individual login */ userToken: string; /** * Locale for the response * @default 'ru' */ locale?: DidoxLocale; } /** * User permissions for a company */ interface UserPermissions { /** * Tax Identification Number */ tin: string; /** * Array of role codes */ roles: number[]; } /** * Company login response */ interface CompanyLoginResponse { /** * Access token for the company context */ token: string; /** * User permissions within this company */ permissions: UserPermissions; } /** * Authentication API implementation */ declare class AuthApi { private readonly httpClient; constructor(httpClient: HttpClient); /** * Login as a legal entity * * Authenticates a legal entity using Tax ID and password. * Returns an access token valid for 360 minutes. * * @param request - Login request parameters * @returns Promise resolving to login response with token and related companies * * @throws {DidoxValidationError} When input validation fails * @throws {DidoxAuthError} When authentication fails (422 status) * @throws {DidoxApiError} When API returns other error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const result = await didox.auth.loginLegalEntity({ * taxId: '123456789', * password: 'securePassword123', * locale: 'ru' * }); * * console.log('Access token:', result.token); * console.log('Related companies:', result.related_companies); * } catch (error) { * if (error instanceof DidoxAuthError) { * console.error('Authentication failed:', error.message); * } * } * ``` */ loginLegalEntity(request: LegalEntityLoginRequest): Promise; /** * Login to a company as an individual * * Allows an individual user to access a company's context using their personal token. * The user must have permissions to access the specified company. * * @param request - Company login request parameters * @returns Promise resolving to company login response with token and permissions * * @throws {DidoxValidationError} When input validation fails * @throws {DidoxAuthError} When authentication fails (422 status) * @throws {DidoxApiError} When API returns other error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const result = await didox.auth.loginCompanyAsIndividual({ * companyTaxId: '987654321', * userToken: 'user-access-token-uuid', * locale: 'uz' * }); * * console.log('Company access token:', result.token); * console.log('User permissions:', result.permissions); * } catch (error) { * if (error instanceof DidoxAuthError) { * console.error('Company access denied:', error.message); * } * } * ``` */ loginCompanyAsIndividual(request: CompanyLoginRequest): Promise; } /** * Account profile information */ interface AccountProfile { /** * Mobile phone number in format 998XXXXXXXXX */ mobile: string; /** * Email address */ email: string; /** * Notifications enabled flag * 1 - notifications enabled * 0 - notifications disabled */ notifications: 0 | 1; /** * Array of messenger identifiers */ messengers: string[]; } /** * Profile update request */ interface UpdateProfileRequest { /** * Mobile phone number in format 998XXXXXXXXX */ mobile: string; /** * Email address */ email: string; /** * New password (optional, minimum 8 characters) */ password?: string; /** * Notifications setting * 1 - enabled, 0 - disabled */ notifications: 0 | 1; } /** * Profile update response */ interface UpdateProfileResponse { /** * Updated mobile phone number */ mobile: string; /** * Updated email address */ email: string; /** * Updated notifications setting */ notifications: 0 | 1; /** * Password confirmation (optional, returned if password was updated) */ password?: string; } /** * Account API implementation */ declare class AccountApi { private readonly httpClient; constructor(httpClient: HttpClient); /** * Get current account profile * * Retrieves the profile information for the currently authenticated user. * Requires valid access token obtained via Auth module. * * @returns Promise resolving to account profile information * * @throws {DidoxAuthError} When authentication fails (401/403 status) * @throws {DidoxApiError} When API returns other error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const profile = await didox.account.getProfile(); * * console.log('Mobile:', profile.mobile); * console.log('Email:', profile.email); * console.log('Notifications:', profile.notifications ? 'Enabled' : 'Disabled'); * console.log('Messengers:', profile.messengers); * } catch (error) { * if (error instanceof DidoxAuthError) { * console.error('Authentication required:', error.message); * } * } * ``` */ getProfile(): Promise; /** * Update current account profile * * Updates the profile information for the currently authenticated user. * All fields are required except password. Password is optional but if provided * must meet minimum requirements. * * @param request - Profile update request parameters * @returns Promise resolving to updated profile information * * @throws {DidoxValidationError} When input validation fails * @throws {DidoxAuthError} When authentication fails (401/403 status) * @throws {DidoxApiError} When API returns other error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const updatedProfile = await didox.account.updateProfile({ * mobile: '998901234567', * email: 'user@example.com', * password: 'newSecurePassword123', // optional * notifications: 1 // enable notifications * }); * * console.log('Profile updated:', updatedProfile); * } catch (error) { * if (error instanceof DidoxValidationError) { * console.error('Validation failed:', error.message, 'Field:', error.field); * } * } * ``` */ updateProfile(request: UpdateProfileRequest): Promise; } /** * Company users and permissions related types for Didox API */ interface UpdateCompanyUsersPermissionsRequest { gnkpermissions: string; internalpermissions: string; is_director: 0 | 1; } interface UpdateCompanyUsersPermissionsResponse { status: 'success'; } /** * GNK (Tax Committee) Role Codes: * 11 - Отправка / отмена ЭСФ * 12 - Подтверждение / отклонение ЭСФ * 21 - Отправка / отмена доверенностей * 22 - Подтверждение / отклонение доверенностей * 41 - Отправка / отмена актов * 42 - Подтверждение / отклонение актов * 51 - Отправка / отмена договоров (НК) * 52 - Подтверждение / отклонение договоров (НК) * 61 - Отправка / отмена актов сверки * 62 - Подтверждение / отклонение актов сверки * 91 - Отправка / отмена актов приема-передачи * 92 - Подтверждение / отклонение актов приема-передачи * 101 - Отправка / отмена ТТН (новый) * 102 - Подтверждение / отклонение ТТН (новый) */ declare enum GNKRoleCode { SEND_ESF = 11, CONFIRM_ESF = 12, SEND_POWER_OF_ATTORNEY = 21, CONFIRM_POWER_OF_ATTORNEY = 22, SEND_ACTS = 41, CONFIRM_ACTS = 42, SEND_CONTRACTS_NK = 51, CONFIRM_CONTRACTS_NK = 52, SEND_RECONCILIATION_ACTS = 61, CONFIRM_RECONCILIATION_ACTS = 62, SEND_TRANSFER_ACTS = 91, CONFIRM_TRANSFER_ACTS = 92, SEND_TTN_NEW = 101, CONFIRM_TTN_NEW = 102 } /** * Didox Internal Role Codes (partial list) * 191 - Отправка / отмена заказов * 192 - Подтверждение / отклонение заказов * 59 - Создание договоров * 199 - Создание заказов * 58 - Просмотр договоров * 198 - Просмотр заказов * 89 - Создание произвольных документов * 88 - Просмотр произвольных документов * 81 - Отправка / отмена произвольных документов * 82 - Подтверждение / отклонение произвольных документов * ... and more */ declare enum DidoxRoleCode { SEND_ORDERS = 191, CONFIRM_ORDERS = 192, CREATE_CONTRACTS = 59, CREATE_ORDERS = 199, VIEW_CONTRACTS = 58, VIEW_ORDERS = 198, CREATE_ARBITRARY_DOCS = 89, VIEW_ARBITRARY_DOCS = 88, SEND_ARBITRARY_DOCS = 81, CONFIRM_ARBITRARY_DOCS = 82, CONFIRM_EPOS_REQUESTS = 2, VIEW_EPOS_REQUESTS = 8, VIEW_UZBAT_CONTRACTS = 118, SEND_UZBAT_CONTRACTS = 111, CREATE_UZBAT_CONTRACTS = 119, VIEW_ESF = 18, VIEW_ACTS = 48, CREATE_ACTS = 49, VIEW_POWER_OF_ATTORNEY = 28, VIEW_TTN = 38, VIEW_GROSS_ACTS = 128, SEND_MULTILATERAL_ARBITRARY_DOCS = 131, CONFIRM_MULTILATERAL_ARBITRARY_DOCS = 132, VIEW_MULTILATERAL_ARBITRARY_DOCS = 138, CREATE_MULTILATERAL_ARBITRARY_DOCS = 139, VIEW_TTN_NEW = 108, SEND_MEETING_PROTOCOL = 151, CONFIRM_MEETING_PROTOCOL = 152, VIEW_MEETING_PROTOCOL = 158, CREATE_MEETING_PROTOCOL = 159, VIEW_RECONCILIATION_ACTS = 68 } /** * Warehouses related types for Didox API */ interface Warehouse { id: number; warehouseNumber: number; warehouseName: string; warehouseAddress: string; } type WarehousesResponse = Warehouse[]; /** * VAT and taxpayer related types for Didox API */ interface VatRegStatusResponse { status: 'success'; vatRegCode: string; vatRegStatus: number; } interface TaxpayerTypeResponse { code: number; name: string; } /** * VAT Registration Status Codes: * 10 - Плательщик НДС * 20 - Плательщик НДС+ (сертификат активный) * 21 - Плательщик НДС+ (сертификат неактивный) * 22 - Плательщик НДС+ (сертификат временно неактивный) * 30 - Плательщик налога с оборота * 40 - Некоммерческое юридическое лицо * 50 - Индивидуальный предприниматель * 60 - Физическое лицо */ declare enum VatRegStatus { VAT_PAYER = 10, VAT_PLUS_ACTIVE = 20, VAT_PLUS_INACTIVE = 21, VAT_PLUS_TEMP_INACTIVE = 22, TURNOVER_TAX = 30, NON_COMMERCIAL = 40, INDIVIDUAL_ENTREPRENEUR = 50, PHYSICAL_PERSON = 60 } type SupportedLanguage = 'ru' | 'uz'; /** * Product Classes (ИКПУ) related types for Didox API */ interface ProductClassPackage { code: string; name: string; name_ru: string; } interface ProductClassOrigin { id: number; name: string; } interface ProductClass { classCode: string; internationalCode: string | null; className: string; className_ru: string; usePackage: 0 | 1; packages: ProductClassPackage[]; origin: ProductClassOrigin; } interface ProductClassCodesResponse { current_page: number; data: ProductClass[]; } interface ProductClassSearchResponse { current_page: number; data: ProductClass[]; first_page_url: string; from: number; last_page: number; last_page_url: string; next_page_url: string | null; path: string; per_page: number; prev_page_url: string | null; to: number; total: number; } interface AddProductClassRequest { classCode: string; } interface AddProductClassResponse { success: true; error: any[]; } interface ProductClassSearchParams { page?: number; search?: string; lang?: 'ru' | 'uz'; } interface ProductClassesCodeCheckResponse { code: string; name: string; } type RemoveProductClassResponse = AddProductClassResponse; /** * Company profile information * Contains only fields marked as "Отобразить" in the API specification */ interface CompanyProfile { /** * VAT rate */ vatRate: number | null; /** * Full company name */ fullName: string; /** * Short company name */ shortName: string; /** * Item released person FIO */ itemReleasedFio: string; /** * VAT value */ vat: number; /** * Excise flag */ excise: boolean; /** * Bank account */ account: string; /** * Bank code */ bankCode: string; /** * OKED code */ oked: string; /** * Company address */ address: string; /** * Region ID */ regionId: number; /** * District ID */ districtId: string; /** * Phone number */ phone: string; /** * Email address */ email: string; /** * Accountant name */ accountant: string; /** * Director name */ director: string; /** * Director TIN */ directorTin: string; /** * Director PINFL */ directorPinfl: string; /** * Notifications setting */ notifications: 0 | 1; /** * Premium account flag */ isPremium: 0 | 1; /** * Additional accounts */ additionalAccounts: any[]; /** * Personal identification number (PINFL) */ pinfl: string | null; /** * Company type */ type: string | null; /** * Account balance */ balance: string; /** * Tax identification number (TIN) */ tin: string; /** * Company name */ name: string; /** * VAT registration status */ VATRegStatus: number; /** * VAT code */ vatCode: string; /** * Offer signed flag */ offerSigned: 0 | 1; /** * Configured messengers */ messengers: { telegram?: string; [key: string]: string | undefined; }; } /** * Profile update request */ interface ProfileUpdateRequest { firstName?: string; lastName?: string; phone?: string; mobile?: string; notifications?: 0 | 1; mfo?: string; account?: string; oked?: string; director?: string; accountant?: string; districtId?: string; regionId?: number; vatRegCode?: string; vatRate?: number | null; itemReleasedFio?: string; itemReleasedPinfl?: string | null; vat?: number; excise?: boolean; address?: string; directorTin?: string; offerDocumentId?: string; offerSigned?: 0 | 1; additionalAccounts?: any[]; pinfl?: string | null; directorPinfl?: string; companyTaxId?: string; companyName?: string; name?: string; bankId?: string; tin?: string; regCode?: string; vatCode?: string; bankAccount?: string; bankCode?: string; additionalMfos?: any[]; } /** * Profile update response */ interface ProfileUpdateResponse { id: number; taxId: string; company: string; firstName: string; lastName: string; phone: string; mobile: string; email: string; admin: string; updated: string; created: string; notifications: 0 | 1; mfo: string; account: string; oked: string; director: string; accountant: string; districtId: string; regionId: number; vatRegCode: string; status: number; isPremium: 0 | 1; vatRate: number | null; itemReleasedFio: string; itemReleasedPinfl: string | null; vat: number; excise: boolean; address: string; fullName: string; shortName: string; uzcardSignDate: string | null; directorTin: string; offerDocumentId: string; offerSigned: 0 | 1; additionalAccounts: any[]; pinfl: string | null; directorPinfl: string; partner: string | null; origin: string | null; categorySeller: string | null; realizationPurpose: string | null; incomingDraftsVisibility: string | null; autofillDocThruContractId: boolean; type: string | null; useCodesFromDb: boolean; user_id: number; companyTaxId: string; companyName: string; name: string; bankId: string; tin: string; shortname: string; fullname: string; regCode: string; vatCode: string; bankAccount: string; bankCode: string; additionalMfos: any[]; } /** * Profile operators response */ type ProfileOperators = Record; /** * Product Classes (ИКПУ) API module */ declare class ProductClassesApi { private httpClient; constructor(httpClient: HttpClient); /** * Get attached product class codes for current profile * @returns Promise * @example * ```typescript * const result = await didox.profile.getProductClassCodes(); * console.log('Attached codes:', result.data.length); * ``` */ getProductClassCodes(): Promise; /** * Search available product class codes * @param params Search parameters * @returns Promise * @example * ```typescript * const result = await didox.profile.searchProductClasses({ * search: 'фото', * lang: 'ru', * page: 1 * }); * console.log('Found classes:', result.data.length); * ``` */ searchProductClasses(params?: ProductClassSearchParams): Promise; /** * Add product class code to current profile * @param classCode Class code (digits only) * @returns Promise * @example * ```typescript * await didox.profile.addProductClass('08418001001013043'); * console.log('Product class added successfully'); * ``` */ addProductClass(classCode: string): Promise; /** * Remove product class code from current profile * @param classCode Class code to remove * @returns Promise * @example * ```typescript * await didox.profile.removeProductClass('08418001001013043'); * console.log('Product class removed successfully'); * ``` */ removeProductClass(classCode: string): Promise; /** * Check product class code packages for specific TIN and code * @param taxId TIN of the company * @param code ИКПУ code * @param lang Language (ru or uz) * @returns Promise * @example * ```typescript * const packages = await didox.profile.checkProductClassCode('123456789', '11703002001000000', 'ru'); * console.log('Available packages:', packages); * ``` */ checkProductClassCode(taxId: string, code: string, lang: 'ru' | 'uz'): Promise; } /** * VAT and taxpayer information API module */ declare class VatApi { private httpClient; constructor(httpClient: HttpClient); /** * Get VAT registration status by TIN or PINFL * @param taxIdOrPinfl TIN (9 digits) or PINFL (14 digits) * @param documentDate Optional date in YYYY-MM-DD format * @returns Promise * @example * ```typescript * const status = await didox.profile.getVatRegStatus('123456789'); * console.log('VAT status:', status.vatRegStatus); * * // With specific date * const statusOnDate = await didox.profile.getVatRegStatus('123456789', '2021-12-22'); * ``` */ getVatRegStatus(taxIdOrPinfl: string, documentDate?: string): Promise; /** * Get taxpayer type by TIN * @param tin TIN (9 digits) * @param lang Language (ru or uz) * @param date Optional date in DD.MM.YYYY format * @returns Promise * @example * ```typescript * const type = await didox.profile.getTaxpayerType('123456789', 'ru'); * console.log('Taxpayer type:', type.name); * * // With specific date * const typeOnDate = await didox.profile.getTaxpayerType('123456789', 'ru', '17.01.2022'); * ``` */ getTaxpayerType(tin: string, lang: SupportedLanguage, date?: string): Promise; } /** * Warehouses API module */ declare class WarehousesApi { private httpClient; constructor(httpClient: HttpClient); /** * Get warehouses by TIN or PINFL * @param taxIdOrPinfl TIN (9 digits) or PINFL (14 digits) * @returns Promise * @example * ```typescript * const warehouses = await didox.profile.getWarehouses('123456789'); * console.log('Warehouses found:', warehouses.length); * * warehouses.forEach(wh => { * console.log(`Warehouse #${wh.warehouseNumber}: ${wh.warehouseName}`); * console.log(`Address: ${wh.warehouseAddress}`); * }); * ``` */ getWarehouses(taxIdOrPinfl: string): Promise; } /** * Company users and permissions API module */ declare class UsersApi { private httpClient; constructor(httpClient: HttpClient); /** * Update company users permissions * @param permissions Permissions data with signed tokens * @returns Promise * @example * ```typescript * await didox.profile.updateCompanyUsersPermissions({ * gnkpermissions: 'base64SignedToken1', * internalpermissions: 'base64SignedToken2', * is_director: 1 * }); * console.log('Permissions updated successfully'); * ``` * * @note This API requires externally signed tokens. The SDK does not generate signatures. * You must prepare and sign the role JSONs externally before calling this method. */ updateCompanyUsersPermissions(permissions: UpdateCompanyUsersPermissionsRequest): Promise; } /** * Profile API implementation */ declare class ProfileApi { private readonly httpClient; readonly productClasses: ProductClassesApi; readonly vat: VatApi; readonly warehouses: WarehousesApi; readonly users: UsersApi; constructor(httpClient: HttpClient); /** * Get current company profile * * Retrieves detailed profile information for the currently authenticated company. * Returns comprehensive company data including financial and contact information. * * @returns Promise resolving to company profile information * * @throws {DidoxAuthError} When authentication fails (401 status) * @throws {DidoxApiError} When API returns other error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const profile = await didox.profile.getProfile(); * * console.log('Company name:', profile.fullName); * console.log('TIN:', profile.tin); * console.log('Balance:', profile.balance); * console.log('Director:', profile.director); * console.log('Messengers:', profile.messengers); * } catch (error) { * if (error instanceof DidoxAuthError) { * console.error('Authentication required:', error.message); * } * } * ``` */ getProfile(): Promise; /** * Update current company profile * * Updates the profile information for the currently authenticated company. * All fields are optional. Only provided fields will be updated. * * @param request - Profile update request parameters * @returns Promise resolving to updated profile information * * @throws {DidoxValidationError} When input validation fails * @throws {DidoxApiError} When profile update fails (422 status) * @throws {DidoxAuthError} When authentication fails * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const updatedProfile = await didox.profile.updateProfile({ * phone: '998901234567', * email: 'company@example.com', * notifications: 1, * regionId: 26, * directorTin: '123456789' * }); * * console.log('Profile updated:', updatedProfile); * } catch (error) { * if (error instanceof DidoxValidationError) { * console.error('Validation failed:', error.message, 'Field:', error.field); * } else if (error instanceof DidoxApiError && error.statusCode === 422) { * console.error('Update failed:', error.message); * } * } * ``` */ updateProfile(request: ProfileUpdateRequest): Promise; /** * Get profile operators * * Retrieves the list of operators associated with the current profile. * Returns a mapping of operator IDs to their corresponding platform names. * * @returns Promise resolving to operators mapping * * @throws {DidoxAuthError} When authentication fails * @throws {DidoxApiError} When API returns error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const operators = await didox.profile.getOperators(); * * Object.entries(operators).forEach(([id, name]) => { * console.log(`Operator ${id}: ${name}`); * }); * * // Example output: * // Operator 202530465: soliqservis.uz * // Operator 302563857: Faktura.uz * // Operator 302936161: Didox.uz * } catch (error) { * console.error('Failed to get operators:', error.message); * } * ``` */ getOperators(): Promise; /** * Get attached product class codes for current profile * @returns Promise */ getProductClassCodes(): Promise; /** * Search available product class codes * @param params Search parameters */ searchProductClasses(params?: Parameters[0]): Promise; /** * Add product class code to current profile * @param classCode Class code (digits only) */ addProductClass(classCode: string): Promise; /** * Remove product class code from current profile * @param classCode Class code to remove */ removeProductClass(classCode: string): Promise; /** * Get VAT registration status by TIN or PINFL * @param taxIdOrPinfl TIN (9 digits) or PINFL (14 digits) * @param documentDate Optional date in YYYY-MM-DD format */ getVatRegStatus(taxIdOrPinfl: string, documentDate?: string): Promise; /** * Get taxpayer type by TIN * @param tin TIN (9 digits) * @param lang Language (ru or uz) * @param date Optional date in DD.MM.YYYY format */ getTaxpayerType(tin: string, lang: 'ru' | 'uz', date?: string): Promise; /** * Get warehouses by TIN or PINFL * @param taxIdOrPinfl TIN (9 digits) or PINFL (14 digits) */ getWarehouses(taxIdOrPinfl: string): Promise; /** * Update company users permissions * @param permissions Permissions data with signed tokens */ updateCompanyUsersPermissions(permissions: Parameters[0]): Promise; } /** * Company branch information */ interface CompanyBranch { /** * Branch ID */ id: number; /** * NS10 code */ ns10Code: number; /** * NS10 name (region) */ ns10Name: string; /** * NS11 code */ ns11Code: number; /** * NS11 name (district) */ ns11Name: string; /** * Tax identification number */ tin: string; /** * Company name */ name: string; /** * Branch name */ branchName: string; /** * Branch number */ branchNum: string; /** * Deletion status */ isDeleted: 0 | 1; /** * Creation date */ createdDate: string; /** * Deletion date (if deleted) */ deletedDate: string | null; /** * Director TIN */ directorTin: string; /** * Director full name */ directorName: string; /** * Director PINFL */ directorPinfl: number; /** * Company PINFL (if applicable) */ pinfl: string | null; /** * Accountant TIN */ accountantTin: string; /** * Accountant full name */ accountantName: string; /** * Accountant PINFL */ accountantPinfl: number; /** * Bank MFO code */ mfo: string; /** * Bank account number */ account: string; /** * Geographic latitude */ latitude: string; /** * Geographic longitude */ longitude: string; /** * Branch address */ address: string; /** * Client IP (if available) */ clientIp?: string | null; /** * Branch URL (if available) */ url?: string | null; /** * Language preference (if available) */ lang?: string | null; /** * Data source (if available) */ source?: string | null; } /** * Request parameters for getting branches by TIN */ interface GetBranchesByTinRequest { /** * Company Tax Identification Number (exactly 9 or 14 digits) */ tin: string; } /** * Legal entity information by TIN response */ interface LegalEntityInfo { /** * Region code */ ns10Code: number; /** * District code */ ns11Code: number; /** * Short organization name */ shortName: string; /** * Tax Identification Number (TIN) */ tin: string; /** * Full organization name */ name: string; /** * Legal form code */ na1Code: number; /** * Legal form name */ na1Name: string; /** * Organization status code */ statusCode: number; /** * Organization status name */ statusName: string; /** * Bank MFO code */ mfo: string; /** * Bank account number */ account: string; /** * Legal address */ address: string; /** * OKED classification code */ oked: string; /** * Director TIN */ directorTin: string; /** * Director PINFL */ directorPinfl: string; /** * Director full name */ director: string; /** * Accountant name (nullable) */ accountant: string | null; /** * Budget organization flag */ isBudget: 0 | 1; /** * ITD flag */ isItd: boolean; /** * Personal number (nullable) */ personalNum: string | null; /** * Self employment flag */ selfEmployment: boolean; /** * Private notary flag */ privateNotary: boolean; /** * Peasant farm flag */ peasantFarm: boolean; /** * VAT registration code */ VATRegCode: string; /** * VAT registration status */ VATRegStatus: number; /** * Bank account (duplicate) */ bankAccount: string; /** * Bank code (duplicate MFO) */ bankCode: string; /** * Short name (duplicate) */ shortname: string; /** * Full name (duplicate) */ fullname: string; /** * Full name (another duplicate) */ fullName: string; } /** * Utilities API implementation */ declare class UtilitiesApi { private readonly httpClient; constructor(httpClient: HttpClient); /** * Get branches by TIN * * Retrieves a list of company branches associated with the specified Tax Identification Number. * Returns detailed information about each branch including location, management, and banking details. * * @param request - Request containing the TIN to search for * @returns Promise resolving to array of company branches * * @throws {DidoxValidationError} When TIN validation fails * @throws {DidoxAuthError} When authentication fails * @throws {DidoxApiError} When API returns error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const branches = await didox.utilities.getBranchesByTin({ * tin: '123456789' * }); * * branches.forEach(branch => { * console.log(`Branch: ${branch.branchName}`); * console.log(`Location: ${branch.address}`); * console.log(`Director: ${branch.directorName}`); * console.log(`Status: ${branch.isDeleted ? 'Deleted' : 'Active'}`); * }); * } catch (error) { * if (error instanceof DidoxValidationError) { * console.error('Invalid TIN:', error.message); * } * } * ``` */ getBranchesByTin(request: GetBranchesByTinRequest): Promise; /** * Get legal entity information by TIN * * Retrieves detailed legal entity (company) information by Tax Identification Number. * Returns comprehensive company data including legal form, director info, banking details, * address, and various organizational flags. * * @param taxId - Tax Identification Number (exactly 9 or 14 digits) * @returns Promise resolving to legal entity information * * @throws {DidoxValidationError} When TIN validation fails * @throws {DidoxAuthError} When authentication fails (401 status) * @throws {DidoxApiError} When API returns other error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const entityInfo = await didox.utilities.getLegalEntityInfoByTin('306915557'); * * console.log('Organization:', entityInfo.name); * console.log('Short name:', entityInfo.shortName); * console.log('Director:', entityInfo.director); * console.log('Legal form:', entityInfo.na1Name); * console.log('Address:', entityInfo.address); * console.log('VAT status:', entityInfo.VATRegStatus); * console.log('OKED:', entityInfo.oked); * } catch (error) { * if (error instanceof DidoxValidationError) { * console.error('Invalid TIN format:', error.message); * } else if (error instanceof DidoxAuthError) { * console.error('Authentication required:', error.message); * } * } * ``` */ getLegalEntityInfoByTin(taxId: string): Promise; } /** * Base Document Builder Infrastructure * * Provides the foundational architecture for all document builders in the Didox SDK. * This class serves as the universal base that all specific document builders extend from. */ /** * Abstract base class for all document builders * * Provides common functionality for building document payloads in a fluent, * chainable API pattern. All document builders inherit from this class to ensure * consistent behavior and IDE support across the SDK. * * @template TPayload - The final document payload type that this builder produces * * @example * ```typescript * // Example usage pattern (actual builders will extend this) * const payload = builder * .someMethod(value) * .anotherMethod(data) * .raw({ customField: 'value' }) // Escape hatch for advanced cases * .build(); // Returns TPayload * ``` */ declare abstract class BaseDocumentBuilder { /** * Internal payload state * * Contains the document data being built. Subclasses should manipulate * this object through their specific methods to construct valid documents. * * @protected */ protected payload: Partial; /** * Initialize builder with optional initial data * * @param initial - Optional initial payload data to seed the builder * * @example * ```typescript * // Start with empty payload * const builder = new ConcreteBuilder(); * * // Start with some initial data * const builder = new ConcreteBuilder({ * existingField: 'value', * anotherField: 123 * }); * ``` */ constructor(initial?: Partial); /** * Raw data merge (escape hatch) * * Allows merging arbitrary JSON data directly into the payload. * This is useful for edge cases, advanced scenarios, or when working * with undocumented API fields that aren't covered by typed methods. * * @param data - Raw data to merge into the current payload * @returns This builder instance for method chaining * * @example * ```typescript * // Merge raw data for advanced use cases * const payload = builder * .standardMethod(value) * .raw({ * customField: 'special value', * undocumentedFlag: true, * nestedObject: { * property: 'data' * } * }) * .build(); * * // Override specific fields if needed * const payload = builder * .setAmount(1000) * .raw({ amount: 2000 }) // Override the amount * .build(); * ``` */ raw(data: Partial): this; /** * Build final document payload * * Returns the constructed document payload. This method should be called * after all desired builder methods have been chained to get the final * document structure ready for API submission. * * @returns The complete document payload of type TPayload * * @example * ```typescript * // Build the final payload * const documentPayload = builder * .setCompany(companyInfo) * .addItem(item1) * .addItem(item2) * .build(); * * // Use with createDraft * await client.documents.createDraft('002', documentPayload); * ``` */ build(): TPayload; } /** * Document Builder Factory Type * * Defines the standard interface for all document builder factories. * Each builder factory should conform to this signature to ensure * consistency across the SDK. * * @template T - The payload type that the builder produces * * @example * ```typescript * // Example factory implementation * const invoiceBuilder: DocumentBuilderFactory = * (initial?) => new InvoiceBuilder(initial); * * // Usage * const builder = invoiceBuilder({ existingData: 'value' }); * const payload = builder.someMethod().build(); * ``` */ type DocumentBuilderFactory = (initial?: Partial) => BaseDocumentBuilder; /** * API payload for Multi-Party Arbitrary Document (doctype 010) * * This interface represents the exact JSON structure required by the Didox API * for multi-party arbitrary documents. The builder's build() method transforms * the DX-friendly MultiPartyDocumentDraft into this format. */ interface ApiMultiPartyDocumentPayload { /** Document data structure */ data: { /** Document information */ Document: { /** Document number */ DocumentNo: string; /** Document date in YYYY-MM-DD format */ DocumentDate: string; /** Document name/title */ DocumentName?: string; }; /** Optional contract information */ ContractDoc?: { /** Contract number */ ContractNo: string; /** Contract date in YYYY-MM-DD format */ ContractDate: string; }; /** Owner organization information */ Owner: { /** Owner TIN */ Tin: string; /** Company name */ Name: string; /** Branch code (empty string if not provided) */ BranchCode: string; /** Branch name (empty string if not provided) */ BranchName: string; /** Company address */ Address: string; }; /** Array of client organizations */ Clients: Array<{ /** Client TIN */ Tin: string; /** Company name */ Name: string; /** Company address */ Address: string; }>; }; /** PDF document in base64 data URL format */ document: string; } /** * Letter NK Builder (Stage 3.2.8) * * Builder for creating letters to tax committee (doctype 013 - Письмо НК). * Provides DX-friendly fluent API with transformation to API-compliant payload. * * @module letter-nk */ /** * DX-friendly interface for letter head information (optional) */ interface LetterHeadDraft { /** * Branch code (optional) */ branchCode?: string; /** * Branch name (optional) */ branchName?: string; /** * Email address (optional) */ email?: string; /** * Website URL (optional, null in API if not provided) */ website?: string; /** * Logo as base64-encoded string (optional) */ logoBase64?: string; /** * Phone numbers array (optional) */ phones?: string[]; } /** * DX-friendly interface for sender information */ interface LetterSenderDraft { /** * Company or person name */ name: string; /** * TIN (БИН/ИИН) */ tin: string; /** * Optional head information (branch, email, website, logo, phones) */ head?: LetterHeadDraft; } /** * DX-friendly interface for recipient information */ interface LetterRecipientDraft { /** * Company or person name */ name: string; /** * TIN (БИН/ИИН) */ tin: string; /** * Optional head information (branch, email, website, logo, phones) */ head?: LetterHeadDraft; } /** * DX-friendly interface for attachment */ interface LetterAttachmentDraft { /** * Filename with extension */ filename: string; /** * MIME type (e.g., "application/pdf") */ mimeType: string; /** * File size in bytes */ size: number; /** * Base64-encoded file content */ base64: string; /** * Optional description of the attachment */ description?: string; } /** * API-compliant interface for letter NK payload * * This is the exact structure expected by Didox API for doctype 013. * Field transformations: * - letter → Letter {Number, Date} * - sender/recipient → Sender/Recipient {Name, Tin, Head} * - head optional fields → empty strings or null (Website) * - html → Html * - attachments → Attachments with ContentBase64 */ interface ApiLetterNKPayload { Letter: { Number: string; Date: string; }; Sender: { Name: string; Tin: string; Head: { BranchCode: string; BranchName: string; Email: string; Website: string | null; LogoBase64: string; Phones: string[]; }; }; Recipient: { Name: string; Tin: string; Head: { BranchCode: string; BranchName: string; Email: string; Website: string | null; LogoBase64: string; Phones: string[]; }; }; Html: string; Attachments: Array<{ Filename: string; MimeType: string; Size: number; ContentBase64: string; Description: string; }>; } /** * Builder for creating Letter NK documents (doctype 013) * * The LetterNKBuilder provides a DX-friendly fluent API for building * letters to tax committee documents. It supports comprehensive sender/recipient * information, HTML content, and file attachments. * * Features: * - Fluent API for intuitive document building * - Comprehensive sender and recipient information with optional head fields * - HTML content support without sanitization * - File attachment management with base64 encoding * - DX-friendly draft format with API transformation * - Raw escape hatch for custom fields * - TypeScript type safety with exactOptionalPropertyTypes * * @extends BaseDocumentBuilder * * @example * ```typescript * // Basic letter * const letter = builders.letterNK() * .letter({ * number: 'ИСХ-145/2024', * date: '2024-12-15' * }) * .sender({ * name: 'ТОО "ТехноСнаб Казахстан"', * tin: '123456789012' * }) * .recipient({ * name: 'Департамент Налогового Комитета МФ РК по г. Алматы', * tin: '999888777666' * }) * .html('

Уважаемые господа, прошу разъяснить вопрос...

') * .build(); * * // Detailed sender with head information * const detailedLetter = builders.letterNK() * .letter({ number: 'ИСХ-146/2024', date: '2024-12-16' }) * .sender({ * name: 'ТОО "Производство+"', * tin: '111222333444', * head: { * branchCode: 'ALM01', * branchName: 'Алматинский филиал', * email: 'info@production.kz', * website: 'https://production.kz', * logoBase64: 'iVBORw0KGgoAAAANSUhEUgAAAAUA...', * phones: ['+7 727 123 45 67', '+7 701 234 56 78'] * } * }) * .recipient({ * name: 'НК РК', * tin: '999888777666' * }) * .html('

Detailed content

') * .addAttachment({ * filename: 'balance.pdf', * mimeType: 'application/pdf', * size: 102400, * base64: 'JVBERi0xLjQK...', * description: 'Бухгалтерский баланс за 2024 год' * }) * .build(); * ``` */ declare class LetterNKBuilder extends BaseDocumentBuilder { private draft; /** * Set letter information (number and date) * * @param letterInfo - Letter metadata * @returns The builder instance for method chaining * * @example * ```typescript * builder.letter({ * number: 'ИСХ-145/2024', * date: '2024-12-15' * }) * ``` */ letter(letterInfo: { number: string; date: string; }): this; /** * Set sender information * * @param senderInfo - Complete sender details * @returns The builder instance for method chaining * * @example * ```typescript * builder.sender({ * name: 'ТОО "ТехноСнаб Казахстан"', * tin: '123456789012', * head: { * branchCode: 'ALM01', * branchName: 'Головной офис', * email: 'office@technosnab.kz', * website: 'https://technosnab.kz', * logoBase64: 'iVBORw0KGgoAAAANSUhEUgAAAAUA...', * phones: ['+7 727 350 12 34', '+7 701 234 56 78'] * } * }) * ``` */ sender(senderInfo: LetterSenderDraft): this; /** * Set recipient information * * @param recipientInfo - Complete recipient details * @returns The builder instance for method chaining * * @example * ```typescript * builder.recipient({ * name: 'Департамент Налогового Комитета МФ РК по г. Алматы', * tin: '999888777666', * head: { * email: 'almaty@kgd.gov.kz', * website: 'https://kgd.gov.kz', * phones: ['+7 7172 58 09 09'] * } * }) * ``` */ recipient(recipientInfo: LetterRecipientDraft): this; /** * Set HTML content of the letter * * NO sanitization or validation is performed on the HTML content. * The content is passed as-is to the API. * * @param htmlContent - HTML content of the letter * @returns The builder instance for method chaining * * @example * ```typescript * builder.html(` *
*

Запрос разъяснения по применению НДС

*

Уважаемые господа,

*

Просим дать письменное разъяснение...

*
* `) * ``` */ html(htmlContent: string): this; /** * Add a single attachment to the letter * * @param attachment - Attachment details * @returns The builder instance for method chaining * * @example * ```typescript * builder.addAttachment({ * filename: 'balance.pdf', * mimeType: 'application/pdf', * size: 102400, * base64: 'JVBERi0xLjQK...', * description: 'Бухгалтерский баланс за 2024 год' * }) * ``` */ addAttachment(attachment: LetterAttachmentDraft): this; /** * Add multiple attachments to the letter * * @param attachments - Array of attachment details * @returns The builder instance for method chaining * * @example * ```typescript * builder.addAttachments([ * { * filename: 'contract.pdf', * mimeType: 'application/pdf', * size: 245760, * base64: 'JVBERi0xLjQK...', * description: 'Контракт № 2024-089' * }, * { * filename: 'specification.pdf', * mimeType: 'application/pdf', * size: 102400, * base64: 'JVBERi0xLjQK...', * description: 'Спецификация к контракту' * } * ]) * ``` */ addAttachments(attachments: LetterAttachmentDraft[]): this; /** * Raw data merge (escape hatch) * * Allows merging arbitrary JSON data directly into the API payload. * Useful for edge cases, advanced scenarios, or undocumented API fields. * The data is deep-merged with the generated payload. * * @param data - Raw data to merge into the payload * @returns The builder instance for method chaining * * @example * ```typescript * builder.raw({ * CustomField: 'Custom Value', * Letter: { * Priority: 'urgent', * Category: 'tax-inquiry' * } * }) * ``` */ raw(data: Partial>): this; /** * Build the final API-compliant payload * * Transforms the DX-friendly draft into the API format expected by Didox. * Performs validation and applies field transformations: * * - letter → Letter {Number, Date} * - sender/recipient → Sender/Recipient {Name, Tin, Head} * - head optional fields → empty strings (except Website → null) * - html → Html * - attachments → Attachments with ContentBase64, Description (empty string default) * * @returns Complete API payload ready for Didox submission * @throws {DidoxValidationError} When required fields are missing * * @example * ```typescript * const payload = builder * .letter({ number: 'ИСХ-001', date: '2024-12-15' }) * .sender({ name: 'Company', tin: '123456789012' }) * .recipient({ name: 'НК РК', tin: '999888777666' }) * .html('

Content

') * .build(); * * await client.documents.createDraft('013', payload); * ``` */ build(): ApiLetterNKPayload & Record; /** * Deep merge helper for combining API payload with raw data * * @private */ private deepMerge; } /** * Factory function for creating a new LetterNKBuilder instance * * @returns A new LetterNKBuilder instance ready for method chaining * * @example * ```typescript * const letter = letterNK() * .letter({ number: 'ИСХ-001', date: '2024-12-15' }) * .sender({ name: 'Company', tin: '123456789012' }) * .recipient({ name: 'НК РК', tin: '999888777666' }) * .html('

Content

') * .build(); * ``` */ declare function letterNK(): LetterNKBuilder; /** * @fileoverview FoundersProtocolBuilder for doctype 075 — Протокол собрания учредителей * * Provides a DX-friendly fluent API for building founders' meeting protocol documents. * Supports complex multi-participant scenarios with agenda items and comprehensive * company information management. * * @example Basic usage * ```typescript * const protocol = builders.foundersProtocol() * .document('Протокол №1', '001', 'Ташкент', '2025-02-07') * .company({ * tin: '123456789', * name: '"DIDOX TECH" MCHJ', * fizTin: '12345678901234', * fio: 'Иванов Иван Иванович', * address: 'г. Ташкент, ул. Амира Темура, 15' * }) * .addParticipant({ * tin: '987654321', * name: 'Петров Петр Петрович', * share: 51, * chairman: true * }) * .addParticipant({ * tin: '111222333', * name: 'Сидоров Сидор Сидорович', * share: 49, * secretary: true * }) * .addPart('О создании общества', 'Принято единогласно создать ООО') * .addPart('Об избрании руководства', 'Избран директор и секретарь') * .build(); * ``` * * @example With company details * ```typescript * const detailedProtocol = builders.foundersProtocol() * .document('Протокол собрания учредителей', 'PROT-2025-001', 'Ташкент', '2025-02-07') * .company({ * tin: '310529901', * name: '"VENKON GROUP" MCHJ', * fizTin: '12345678901234', * fio: 'Директор Иванов И.И.', * bankId: 'NBU01', * oked: 62010, * account: '20208000400000000001', * address: 'г. Ташкент, ул. Университетская, 4', * workPhone: '+998711234567', * mobile: '+998901234567' * }) * .addParticipants([ * { * tin: '123456789', * name: 'Учредитель 1', * companyTin: '987654321', * companyName: 'Компания-учредитель', * share: '60%', * citizenship: 'UZ', * chairman: true * }, * { * tin: '987654321', * name: 'Учредитель 2', * share: '40%', * secretary: true * } * ]) * .addParts([ * { title: 'Вопрос 1', body: 'Принятие устава' }, * { title: 'Вопрос 2', body: 'Выбор руководства' }, * { title: 'Вопрос 3', body: 'Определение уставного капитала' } * ]) * .raw({ * meetingType: 'FOUNDATION', * duration: '2_HOURS' * }) * .build(); * ``` * * @since 3.2.7 */ /** * DX-friendly interface for founders protocol document draft */ interface FoundersProtocolDraft { /** * Document metadata */ document: { /** Document name/title */ name: string; /** Document number */ no: string; /** Meeting place */ place: string; /** Document date (YYYY-MM-DD format) */ date: string; }; /** * Company information for the protocol */ company: { /** Company TIN */ tin: string; /** Company name */ name: string; /** Physical person TIN (for individual) */ fizTin: string; /** Full name of the representative */ fio: string; /** Bank ID (optional) */ bankId?: string; /** OKED classification code (optional) */ oked?: number; /** Bank account number (optional) */ account?: string; /** Company address */ address: string; /** Work phone (optional) */ workPhone?: string; /** Mobile phone (optional) */ mobile?: string; }; /** * Protocol participants/founders */ participants: ProtocolParticipantDraft[]; /** * Protocol agenda items/parts */ parts: ProtocolPartDraft[]; } /** * DX-friendly interface for protocol participant */ interface ProtocolParticipantDraft { /** Participant TIN */ tin: string; /** Participant name */ name: string; /** Company TIN if participant represents a company (optional) */ companyTin?: string; /** Company name if participant represents a company (optional) */ companyName?: string; /** Share percentage or amount */ share: number | string; /** Citizenship (optional) */ citizenship?: string; /** Whether this participant is chairman (optional) */ chairman?: boolean; /** Whether this participant is secretary (optional) */ secretary?: boolean; } /** * DX-friendly interface for protocol agenda part */ interface ProtocolPartDraft { /** Part title */ title: string; /** Part body/content */ body: string; } /** * API-compliant interface for founders protocol payload */ interface ApiFoundersProtocolPayload { documentdoc: { documentname: string; documentno: string; documentplace: string; documentdate: string; }; company: { tin: string; name: string; fiztin: string; fio: string; bankid: string; oked: number; account: string; address: string; workphone: string; mobile: string; }; participants: Array<{ tin: string; name: string; companyTaxId: string; companyname: string; share: string; citizenship: string; ischairman: boolean; issecretary: boolean; }>; parts: Array<{ ordno: number; title: string; body: string; }>; } /** * Builder for creating Founders Protocol documents (doctype 075) * * The FoundersProtocolBuilder provides a DX-friendly fluent API for building * founders' meeting protocol documents. It supports complex scenarios with * multiple participants, detailed company information, and structured agenda items. * * Features: * - Fluent API for intuitive document building * - Multi-participant support with roles (chairman, secretary) * - Comprehensive company information handling * - Structured agenda items with automatic ordering * - DX-friendly draft format with API transformation * - Raw escape hatch for custom fields * - TypeScript type safety with exactOptionalPropertyTypes * * @extends BaseDocumentBuilder * * @example * ```typescript * const protocol = builders.foundersProtocol() * .document('Протокол №1', '001', 'Ташкент', '2025-02-07') * .company({ * tin: '123456789', * name: '"DIDOX TECH" MCHJ', * fizTin: '12345678901234', * fio: 'Иванов Иван Иванович', * address: 'г. Ташкент, ул. Амира Темура, 15' * }) * .addParticipant({ * tin: '987654321', * name: 'Петров Петр Петрович', * share: 51, * chairman: true * }) * .addPart('Вопрос 1', 'Принято решение') * .build(); * ``` */ declare class FoundersProtocolBuilder extends BaseDocumentBuilder { private draft; /** * Set document metadata for the founders protocol * * @param name - Document name/title * @param no - Document number * @param place - Meeting place * @param date - Document date in YYYY-MM-DD format * @returns The builder instance for method chaining * * @example * ```typescript * builder.document('Протокол собрания учредителей', 'PROT-001', 'Ташкент', '2025-02-07') * ``` */ document(name: string, no: string, place: string, date: string): this; /** * Set company information for the protocol * * @param companyInfo - Company details * @returns The builder instance for method chaining * * @example * ```typescript * builder.company({ * tin: '310529901', * name: '"DIDOX TECH" MCHJ', * fizTin: '12345678901234', * fio: 'Директор Иванов И.И.', * address: 'г. Ташкент, ул. Амира Темура, 15', * bankId: 'NBU01', * oked: 62010 * }) * ``` */ company(companyInfo: FoundersProtocolDraft['company']): this; /** * Add a single participant to the protocol * * @param participant - Participant information * @returns The builder instance for method chaining * * @example * ```typescript * builder.addParticipant({ * tin: '123456789', * name: 'Иванов Иван Иванович', * share: 51, * chairman: true, * citizenship: 'UZ' * }) * ``` */ addParticipant(participant: ProtocolParticipantDraft): this; /** * Add multiple participants to the protocol at once * * @param participants - Array of participants to add * @returns The builder instance for method chaining * * @example * ```typescript * builder.addParticipants([ * { * tin: '123456789', * name: 'Учредитель 1', * share: '60%', * chairman: true * }, * { * tin: '987654321', * name: 'Учредитель 2', * share: '40%', * secretary: true * } * ]) * ``` */ addParticipants(participants: ProtocolParticipantDraft[]): this; /** * Add a single agenda item/part to the protocol * * @param title - Part title * @param body - Part content/body * @returns The builder instance for method chaining * * @example * ```typescript * builder.addPart('О создании общества', 'Принято единогласно создать ООО с уставным капиталом...') * ``` */ addPart(title: string, body: string): this; /** * Add multiple agenda items/parts to the protocol at once * * @param parts - Array of parts to add * @returns The builder instance for method chaining * * @example * ```typescript * builder.addParts([ * { title: 'Вопрос 1', body: 'Принятие устава' }, * { title: 'Вопрос 2', body: 'Выбор руководства' }, * { title: 'Вопрос 3', body: 'Определение капитала' } * ]) * ``` */ addParts(parts: ProtocolPartDraft[]): this; /** * Override with raw API payload data (escape hatch) * * Allows direct modification of the final API payload for advanced scenarios * or custom fields not covered by the standard API. The data is deep-merged * with the generated payload, allowing fine-grained control. * * @param data - Raw data to merge into the payload * @returns The builder instance for method chaining * * @example * ```typescript * builder.raw({ * meetingType: 'FOUNDATION', * duration: '2_HOURS', * customField: 'custom value', * company: { * oked: 62020 // Override specific company field * } * }) * ``` */ raw(data: Partial>): this; /** * Build the final API-compliant payload * * Transforms the DX-friendly draft into the API format expected by Didox. * Performs validation and applies field transformations: * * - chairman → ischairman * - secretary → issecretary * - share → string conversion * - ordno → auto-increment from 1 * - Optional fields → empty strings if missing * - oked → number type * - Removes undefined values * * @returns Complete API payload ready for Didox submission * @throws {DidoxValidationError} When required fields are missing * * @example * ```typescript * const payload = builder * .document('Протокол №1', '001', 'Ташкент', '2025-02-07') * .company({ ... }) * .addParticipant({ ... }) * .addPart('Вопрос 1', 'Содержание') * .build(); * * // Returns API-compliant structure ready for createDraft() * ``` */ build(): ApiFoundersProtocolPayload & Record; } /** * Factory function for creating a new FoundersProtocolBuilder instance * * @returns A new FoundersProtocolBuilder instance ready for method chaining * * @example * ```typescript * const protocol = foundersProtocol() * .document('Протокол №1', '001', 'Ташкент', '2025-02-07') * .company({ ... }) * .addParticipant({ ... }) * .addPart('Вопрос', 'Содержание') * .build(); * ``` */ declare function foundersProtocol(): FoundersProtocolBuilder; /** * API payload for Arbitrary Document (doctype 000) * * This interface represents the exact JSON structure required by the Didox API * for arbitrary documents. The builder's build() method transforms the DX-friendly * ArbitraryDocumentDraft into this format. */ interface ApiArbitraryDocumentPayload { /** Document data structure */ data: { /** Document information */ Document: { /** Document number */ DocumentNo: string; /** Document date in YYYY-MM-DD format */ DocumentDate: string; /** Document name/title */ DocumentName?: string; }; /** Document subtype */ Subtype: number; /** Optional contract information */ ContractDoc?: { /** Contract number */ ContractNo: string; /** Contract date in YYYY-MM-DD format */ ContractDate: string; }; /** Seller TIN */ SellerTin: string; /** Seller information */ Seller: { /** Company name */ Name: string; /** Branch code (empty string if not provided) */ BranchCode: string; /** Branch name (empty string if not provided) */ BranchName: string; /** Company address */ Address: string; }; /** Buyer TIN */ BuyerTin: string; /** Buyer information */ Buyer: { /** Company name */ Name: string; /** Branch code (empty string if not provided) */ BranchCode: string; /** Branch name (empty string if not provided) */ BranchName: string; /** Company address */ Address: string; }; }; /** PDF document in base64 data URL format */ document: string; } /** * Empowerment Builder (Stage 3.2.9) * * Builder for creating empowerment documents (doctype 006 - Доверенность). * Provides DX-friendly fluent API with transformation to API-compliant payload. * * Key features: * - Three-party structure: Seller, Buyer, Agent * - NO prices, VAT, or sums (pure product list with quantities) * - Auto-increment OrdNo for products * - Optional contract reference * - Agent with passport information * * @module empowerment */ /** * DX-friendly interface for agent passport information */ interface AgentPassportDraft { /** * Passport number (optional) */ number?: string; /** * Passport issued by (optional) */ issuedBy?: string; /** * Passport issue date in YYYY-MM-DD format (optional) */ issueDate?: string; } /** * DX-friendly interface for agent information */ interface AgentDraft { /** * Full name (ФИО) */ fio: string; /** * PINFL (14-digit personal identification number) */ pinfl: string; /** * Job title (optional) */ jobTitle?: string; /** * Passport information (optional) */ passport?: AgentPassportDraft; } /** * DX-friendly interface for seller/buyer company information */ interface CompanyDraft { /** * TIN (ИНН) */ tin: string; /** * Company name */ name: string; /** * Bank account number */ account: string; /** * Bank ID (MFO) */ bankId: string; /** * Company address */ address: string; /** * Director name (optional) */ director?: string; /** * Accountant name (optional) */ accountant?: string; /** * Branch code (optional) */ branchCode?: string; /** * Branch name (optional) */ branchName?: string; } /** * DX-friendly interface for product in empowerment */ interface EmpowermentProductDraft { /** * Product name */ name: string; /** * Catalog code (ИКПУ) */ catalogCode: string; /** * Catalog name (optional, from ИКПУ classifier) */ catalogName?: string; /** * Measure unit ID (e.g., "1" for pieces) */ measureId: string; /** * Quantity */ count: number; } /** * API-compliant interface for empowerment payload * * This is the exact structure expected by Didox API for doctype 006. */ interface ApiEmpowermentPayload { EmpowermentDoc: { EmpowermentNo: string; EmpowermentDateOfIssue: string; EmpowermentDateOfExpire: string; }; ContractDoc: { ContractNo: string; ContractDate: string; }; Agent: { JobTitle: string | null; Fio: string; Passport: { Number: string | null; IssuedBy: string | null; DateOfIssue: string | null; }; AgentTin: string; }; SellerTin: string; Seller: { Name: string; Address: string; BankAccount: string; BankId: string; Director: string; Accountant: string; BranchCode: string; BranchName: string; }; BuyerTin: string; Buyer: { Name: string; Address: string; BankAccount: string; BankId: string; Director: string; Accountant: string; BranchCode: string; BranchName: string; }; ProductList: { Tin: string; HasExcise: boolean; HasVat: boolean; Products: Array<{ OrdNo: number; CatalogCode: string; CatalogName: string; Name: string; MeasureId: string; Count: string; }>; }; } /** * Builder for creating Empowerment documents (doctype 006) * * The EmpowermentBuilder provides a DX-friendly fluent API for building * empowerment (power of attorney) documents. It supports three-party structure * (seller, buyer, agent) with product lists, but without any pricing or VAT information. * * Features: * - Fluent API for intuitive document building * - Three-party structure: Seller, Buyer, Agent * - Product list with auto-incrementing OrdNo * - No prices, VAT, or sum calculations * - Optional contract reference * - Agent passport information support * - DX-friendly draft format with API transformation * - Raw escape hatch for custom fields * - TypeScript type safety with exactOptionalPropertyTypes * * @extends BaseDocumentBuilder * * @example * ```typescript * // Basic empowerment * const empowerment = builders.empowerment() * .empowerment('EMP-001', '2025-02-07', '2025-02-14') * .agent({ * fio: 'MAMATQULOV SANJAR XAMZALI O\'G\'LI', * pinfl: '50106026830029' * }) * .seller({ * tin: '302936161', * name: '"VENKON GROUP" MCHJ', * account: '20208000400308125001', * bankId: '00974', * address: 'г. Ташкент, ул. Навои, 1' * }) * .buyer({ * tin: '310529901', * name: '"DIDOX TECH" MCHJ', * account: '20208000905656222001', * bankId: '00401', * address: 'г. Ташкент, ул. Амира Темура, 15' * }) * .addProduct({ * name: 'Ноутбук', * catalogCode: '08471001001000000', * measureId: '1', * count: 10 * }) * .build(); * * // With contract and passport details * const detailedEmpowerment = builders.empowerment() * .empowerment('EMP-002', '2025-02-10', '2025-03-10') * .contract('CNT-1', '2025-01-01') * .agent({ * fio: 'ИВАНОВ ИВАН ИВАНОВИЧ', * pinfl: '12345678901234', * jobTitle: 'Менеджер по продажам', * passport: { * number: 'AC1234567', * issuedBy: 'ОВД Мирзо-Улугбекского района', * issueDate: '2020-05-15' * } * }) * .seller({ * tin: '123456789', * name: 'ООО "Поставщик"', * account: '20208000400000000001', * bankId: '00401', * address: 'Адрес поставщика', * director: 'Директор Иванов И.И.', * accountant: 'Бухгалтер Петрова П.П.', * branchCode: 'BRANCH01', * branchName: 'Центральный филиал' * }) * .buyer({ * tin: '987654321', * name: 'ООО "Покупатель"', * account: '20208000400000000002', * bankId: '00974', * address: 'Адрес покупателя' * }) * .addProducts([ * { * name: 'Компьютер настольный', * catalogCode: '08471001002000000', * catalogName: 'Компьютеры персональные', * measureId: '1', * count: 5 * }, * { * name: 'Монитор 24"', * catalogCode: '08471002001000000', * measureId: '1', * count: 5 * } * ]) * .build(); * ``` */ declare class EmpowermentBuilder extends BaseDocumentBuilder { private draft; /** * Set empowerment document information (number and dates) * * @param no - Empowerment number * @param issueDate - Issue date in YYYY-MM-DD format * @param expireDate - Expiration date in YYYY-MM-DD format * @returns The builder instance for method chaining * * @example * ```typescript * builder.empowerment('EMP-2025-001', '2025-02-07', '2025-02-14') * ``` */ empowerment(no: string, issueDate: string, expireDate: string): this; /** * Set contract reference (optional) * * @param no - Contract number * @param date - Contract date in YYYY-MM-DD format * @returns The builder instance for method chaining * * @example * ```typescript * builder.contract('CNT-2025-089', '2025-01-15') * ``` */ contract(no: string, date: string): this; /** * Set agent information (person receiving empowerment) * * @param agentInfo - Complete agent details * @returns The builder instance for method chaining * * @example * ```typescript * // Basic agent * builder.agent({ * fio: 'MAMATQULOV SANJAR XAMZALI O\'G\'LI', * pinfl: '50106026830029' * }) * * // Agent with full details * builder.agent({ * fio: 'ИВАНОВ ИВАН ИВАНОВИЧ', * pinfl: '12345678901234', * jobTitle: 'Менеджер по продажам', * passport: { * number: 'AC1234567', * issuedBy: 'ОВД Мирзо-Улугбекского района', * issueDate: '2020-05-15' * } * }) * ``` */ agent(agentInfo: AgentDraft): this; /** * Set seller company information * * @param sellerInfo - Complete seller details * @returns The builder instance for method chaining * * @example * ```typescript * builder.seller({ * tin: '302936161', * name: '"VENKON GROUP" MCHJ', * account: '20208000400308125001', * bankId: '00974', * address: 'г. Ташкент, ул. Навои, 1', * director: 'Директор Иванов И.И.', * accountant: 'Гл. бухгалтер Петрова П.П.', * branchCode: 'TSH01', * branchName: 'Ташкентский филиал' * }) * ``` */ seller(sellerInfo: CompanyDraft): this; /** * Set buyer company information * * @param buyerInfo - Complete buyer details * @returns The builder instance for method chaining * * @example * ```typescript * builder.buyer({ * tin: '310529901', * name: '"DIDOX TECH" MCHJ', * account: '20208000905656222001', * bankId: '00401', * address: 'г. Ташкент, ул. Амира Темура, 15' * }) * ``` */ buyer(buyerInfo: CompanyDraft): this; /** * Add a single product to the empowerment * * Products are assigned auto-incrementing OrdNo starting from 1. * Count is converted to string in the final API payload. * * @param product - Product details * @returns The builder instance for method chaining * * @example * ```typescript * builder.addProduct({ * name: 'Ноутбук Dell Latitude', * catalogCode: '08471001001000000', * catalogName: 'Компьютеры портативные', * measureId: '1', * count: 10 * }) * ``` */ addProduct(product: EmpowermentProductDraft): this; /** * Add multiple products to the empowerment * * Products are assigned auto-incrementing OrdNo in the order they are added. * * @param products - Array of product details * @returns The builder instance for method chaining * * @example * ```typescript * builder.addProducts([ * { * name: 'Компьютер настольный', * catalogCode: '08471001002000000', * catalogName: 'Компьютеры персональные', * measureId: '1', * count: 5 * }, * { * name: 'Монитор 24"', * catalogCode: '08471002001000000', * measureId: '1', * count: 5 * } * ]) * ``` */ addProducts(products: EmpowermentProductDraft[]): this; /** * Raw data merge (escape hatch) * * Allows merging arbitrary JSON data directly into the API payload. * Useful for edge cases, advanced scenarios, or undocumented API fields. * The data is deep-merged with the generated payload. * * @param data - Raw data to merge into the payload * @returns The builder instance for method chaining * * @example * ```typescript * builder.raw({ * CustomField: 'Custom Value', * EmpowermentDoc: { * AdditionalInfo: 'Some additional information' * } * }) * ``` */ raw(data: Partial>): this; /** * Build the final API-compliant payload * * Transforms the DX-friendly draft into the API format expected by Didox. * Performs validation and applies field transformations: * * - empowerment → EmpowermentDoc {EmpowermentNo, EmpowermentDateOfIssue, EmpowermentDateOfExpire} * - contract → ContractDoc {ContractNo, ContractDate} (empty strings if not provided) * - agent → Agent with JobTitle (null default), Passport fields (null defaults) * - seller/buyer → Seller/Buyer with BranchCode/BranchName defaults ("") * - products → ProductList with auto-increment OrdNo, count as string * - HasExcise: false, HasVat: false (always) * * @returns Complete API payload ready for Didox submission * @throws {DidoxValidationError} When required fields are missing or products list is empty * * @example * ```typescript * const payload = builder * .empowerment('EMP-001', '2025-02-07', '2025-02-14') * .agent({ fio: 'Agent Name', pinfl: '12345678901234' }) * .seller({ tin: '123456789', name: 'Seller', account: '...', bankId: '...', address: '...' }) * .buyer({ tin: '987654321', name: 'Buyer', account: '...', bankId: '...', address: '...' }) * .addProduct({ name: 'Product', catalogCode: '...', measureId: '1', count: 10 }) * .build(); * * await client.documents.createDraft('006', payload); * ``` */ build(): ApiEmpowermentPayload & Record; /** * Deep merge helper for combining API payload with raw data * * @private */ private deepMerge; } /** * Factory function for creating a new EmpowermentBuilder instance * * @returns A new EmpowermentBuilder instance ready for method chaining * * @example * ```typescript * const empowerment = empowerment() * .empowerment('EMP-001', '2025-02-07', '2025-02-14') * .agent({ fio: 'Agent Name', pinfl: '12345678901234' }) * .seller({ tin: '123456789', name: 'Seller', ... }) * .buyer({ tin: '987654321', name: 'Buyer', ... }) * .addProduct({ name: 'Product', catalogCode: '...', measureId: '1', count: 10 }) * .build(); * ``` */ declare function empowerment(): EmpowermentBuilder; /** * DX-friendly Act Draft interface * * Developer-friendly structure for building act documents. * This gets transformed to Didox API JSON format in build(). */ interface ActDraft { /** Act document information */ act: { no: string; date: string; text?: string; }; /** Optional contract reference */ contract?: { no: string; date: string; }; /** Seller (performer) organization details */ seller: { tin: string; name: string; branchCode?: string; branchName?: string; }; /** Buyer (customer) organization details */ buyer: { tin: string; name: string; branchCode?: string; branchName?: string; }; /** List of products/services/works */ products: ActProductDraft[]; /** Optional act flags */ flags?: { hasVat?: boolean; hasExcise?: boolean; }; } /** * DX-friendly Product Draft interface * * Simple structure for adding products/services to acts. */ interface ActProductDraft { /** Product/service name */ name: string; /** Product catalog code */ catalogCode: string; /** Product catalog name */ catalogName: string; /** Package code */ packageCode: string; /** Package name */ packageName: string; /** Count/quantity */ count: number; /** Unit price */ price: number; /** VAT rate (optional) */ vatRate?: number; /** Without VAT flag (optional) */ withoutVat?: boolean; /** Benefit name (optional) */ lgotaName?: string; /** Benefit type (optional) */ lgotaType?: 1 | 2; } /** * API TTN Payload interface * * Exact structure expected by Didox API for TTN documents (docType: '041'). */ interface ApiTtnPayload { WaybillLocalType: number; DeliveryType: number; WaybillDoc: { WaybillNo: string; WaybillDate: string; }; ContractDoc?: { ContractNo: string; ContractDate: string; }; Consignor: { ConsignorTin: string; ConsignorName: string; ConsignorBranchCode: string; ConsignorBranchName: string; }; Consignee: { ConsigneeTin: string; ConsigneeName: string; ConsigneeBranchCode: string; ConsigneeBranchName: string; }; Carrier: { CarrierTin: string; CarrierName: string; CarrierBranchCode: string; CarrierBranchName: string; }; FreightForwarder?: { FreightForwarderTin: string; FreightForwarderName: string; FreightForwarderBranchCode: string; FreightForwarderBranchName: string; }; Client?: { ClientTin: string; ClientName: string; ClientBranchCode: string; ClientBranchName: string; }; Payer?: { PayerTin: string; PayerName: string; PayerBranchCode: string; PayerBranchName: string; }; TransportType: number; Roadway: { Truck: { RegNo: string; Model: string; }; Trailer?: { RegNo: string; Model: string; }; Driver: { Pinfl: string; FullName: string; }; ProductGroups: { OrdNo: number; LoadingPoint: { Address: string; Tin: string; Name: string; }; LoadingTrustee?: { Pinfl: string; FullName: string; }; UnloadingPoint: { Address: string; Tin: string; Name: string; }; UnloadingTrustee?: { Pinfl: string; FullName: string; }; Empowerment?: { EmpowermentNo: string; EmpowermentDate: string; EmpowermentSeries?: string; }; ProductList: { OrdNo: number; CatalogCode: string; CatalogName: string; Name: string; PackageCode: string; PackageName: string; Count: string; Amount: string; DeliverySum: string; }[]; }[]; }; ResponsiblePerson: { Pinfl: string; FullName: string; }; TotalDistance: string; DeliveryCost: string; TotalDeliveryCost: string; HasCommittent?: boolean; SingleSidedType?: number; isValid: boolean; } /** * DX-friendly Invoice Draft interface * * Developer-friendly structure for building invoices. * This gets transformed to Didox API JSON format in build(). */ interface InvoiceDraft { /** Invoice document information */ factura: { no: string; date: string; }; /** Optional contract reference */ contract?: { no: string; date: string; }; /** Seller organization details */ seller: { tin: string; name: string; vatRegCode: string; account: string; bankId: string; address: string; }; /** Buyer organization details */ buyer: { tin: string; name: string; vatRegCode: string; account: string; bankId: string; address: string; }; /** List of products/services */ products: InvoiceProductDraft[]; /** Optional invoice flags */ flags?: { hasVat?: boolean; hasExcise?: boolean; hasLgota?: boolean; hasCommittent?: boolean; }; } /** * DX-friendly Product Draft interface * * Simple structure for adding products to invoices. */ interface InvoiceProductDraft { /** Product name */ name: string; /** Product catalog code */ catalogCode: string; /** Optional catalog name */ catalogName?: string; /** Package code */ packageCode: string; /** Package name */ packageName: string; /** Quantity */ quantity: number; /** Unit price */ price: number; /** VAT rate (optional) */ vatRate?: number; /** Origin code */ origin: number; } /** * Document Builders Collection * * Centralized access to all document builders. Each builder provides a fluent API * for constructing documents with proper typing and IDE support. * * @example * ```typescript * // Create an invoice document * const invoicePayload = builders.invoice() * .raw({ FacturaType: 0 }) * .build(); * * await client.documents.createDraft('002', invoicePayload); * * // Create a transport waybill * const ttnPayload = builders.ttn() * .raw({ transportInfo: { vehicleNumber: '01A123BC' } }) * .build(); * * await client.documents.createDraft('041', ttnPayload); * ``` */ declare const builders: { /** * Invoice document builder (docType: '002') * For creating standard invoices */ readonly invoice: DocumentBuilderFactory; /** * Pharmacy invoice document builder * For creating pharmacy-specific invoices */ readonly invoicePharm: DocumentBuilderFactory; /** * Hybrid invoice document builder * For creating hybrid invoices */ readonly hybridInvoice: DocumentBuilderFactory; /** * Transport waybill (TTN) document builder (docType: '041') * For creating transport waybills */ readonly ttn: DocumentBuilderFactory; /** * Act document builder (docType: '075') * For creating act of work completed documents */ readonly act: DocumentBuilderFactory; /** * Contract document builder * For creating contract documents */ readonly contract: DocumentBuilderFactory; /** * Empowerment document builder (doctype: '006') * For creating empowerment (power of attorney) documents. * Three-party structure: Seller, Buyer, Agent. No prices or VAT. */ readonly empowerment: typeof empowerment; /** * Arbitrary document builder (doctype: '000') * For creating arbitrary PDF documents for internal EDO use. * These documents don't sync with roaming or other operators. */ readonly arbitrary: DocumentBuilderFactory; /** * Verification act document builder * For creating verification act documents */ readonly verificationAct: DocumentBuilderFactory; /** * Acceptance transfer document builder * For creating acceptance transfer documents */ readonly acceptanceTransfer: DocumentBuilderFactory; /** * Founders protocol document builder (doctype: '075') * For creating founders' meeting protocol documents */ readonly foundersProtocol: typeof foundersProtocol; /** * Letter NK document builder (doctype: '013') * For creating letters to tax committee (Письмо НК) */ readonly letterNK: typeof letterNK; /** * Multi-party arbitrary document builder (doctype: '010') * For creating multi-party arbitrary PDF documents with 1 owner + N clients. * These documents are for internal EDO use and don't sync with roaming. */ readonly multiParty: DocumentBuilderFactory; }; /** * Document types enum for Didox platform */ declare enum DocumentType { /** Electronic invoice (ЭСФ) */ FACTURA = "002", /** Pharmaceutical invoice (ЭСФ для фармацевтики) */ FACTURA_PHARM = "008", /** Hybrid invoice (Гибридная ЭСФ) */ HYBRID_FACTURA = "023", /** Waybill (ТТН) */ WAYBILL = "041", /** Act (Акт) */ ACT = "005", /** Power of attorney (Доверенность) */ EMPOWERMENT = "006", /** Contract NK (Договор НК) */ CONTRACT_NK = "007", /** Free form document (Произвольный документ) */ FREE_FORM = "000", /** Verification act (Акт сверки) */ VERIFICATION_ACT = "052", /** Acceptance transfer act (Акт приема-передачи) */ ACCEPTANCE_TRANSFER = "054", /** Multi-party free form (Многосторонний произвольный) */ MULTI_FREE_FORM = "010", /** Founders protocol (Протокол учредителей) */ FOUNDERS_PROTOCOL = "075", /** Tax letter (Налоговое письмо) */ TAX_LETTER = "013" } /** * Document status enum */ declare enum DocumentStatus { /** Draft state */ DRAFT = 0, /** Sent for signing */ SENT = 1, /** Signed by all parties */ SIGNED = 2, /** Rejected by counterparty */ REJECTED = 3, /** Cancelled by sender */ CANCELLED = 4, /** Error state */ ERROR = 5, /** Partially signed */ PARTIALLY_SIGNED = 6, /** Waiting for signature */ WAITING_SIGNATURE = 7, /** Processing */ PROCESSING = 8, /** Expired */ EXPIRED = 9 } /** * Document owner type enum */ declare enum OwnerType { /** Incoming document */ INCOMING = 0, /** Outgoing document */ OUTGOING = 1 } /** * Parameters for listing documents */ interface ListDocumentsParams { /** * Document owner type (0 = incoming, 1 = outgoing) */ owner: 0 | 1; /** * Page number (starts from 1) * @minimum 1 */ page: number; /** * Number of items per page * @minimum 1 * @maximum 100 */ limit: number; /** * Filter by document status * Can be a single status or array of statuses */ status?: number | number[]; /** * Filter by document type code */ doctype?: string; /** * Filter by partner (counterparty) */ partner?: string; /** * Filter by creation date from (YYYY-MM-DD format) */ dateFromCreated?: string; /** * Filter by creation date to (YYYY-MM-DD format) */ dateToCreated?: string; /** * Filter by update date from (YYYY-MM-DD format) */ dateFromUpdated?: string; /** * Filter by update date to (YYYY-MM-DD format) */ dateToUpdated?: string; /** * Filter by signature date from (YYYY-MM-DD format) */ signDateFrom?: string; /** * Filter by signature date to (YYYY-MM-DD format) */ signDateTo?: string; /** * Filter by document date from (YYYY-MM-DD format) */ docDateFromCreated?: string; /** * Filter by document date to (YYYY-MM-DD format) */ docDateToCreated?: string; /** * Filter by contract name */ contractName?: string; /** * Filter by contract date (YYYY-MM-DD format) */ contractDate?: string; /** * Filter documents with committent (0 = no, 1 = yes) */ hasCommittent?: 0 | 1; /** * Filter documents with benefits (0 = no, 1 = yes) */ hasLgota?: 0 | 1; /** * Filter documents with marks (0 = no, 1 = yes) */ hasMarks?: 0 | 1; /** * Filter one-sided documents (0 = no, 1 = yes) */ oneside?: 0 | 1; /** * Output format for response * @default 'raw' */ output?: 'raw' | 'normalized'; } /** * Document metadata interface */ interface DocumentMetadata { /** * Document unique identifier */ id: string; /** * Document type code */ type: DocumentType; /** * Document status */ status: DocumentStatus; /** * Owner type (incoming/outgoing) */ owner: OwnerType; /** * Document number */ number?: string; /** * Document date */ date?: string; /** * Creation timestamp */ createdAt: string; /** * Last update timestamp */ updatedAt: string; /** * Partner information */ partner?: { tin: string; name: string; }; } /** * Document statistics response */ interface DocumentStatistics { /** * Total documents count */ total: number; /** * Count by status */ byStatus: Record; /** * Count by document type */ byType: Record; /** * Count by owner type */ byOwner: Record; } /** * Document privileges response */ interface DocumentPrivileges { /** * Can view document */ canView: boolean; /** * Can edit document */ canEdit: boolean; /** * Can sign document */ canSign: boolean; /** * Can cancel document */ canCancel: boolean; /** * Can delete document */ canDelete: boolean; /** * Can download document */ canDownload: boolean; } /** * Document creation payload */ interface DocumentCreatePayload { /** * Document type */ type: DocumentType; /** * Document specific data */ data: unknown; } /** * Document API response wrapper */ interface DocumentResponse { /** * Operation success flag */ success: boolean; /** * Response data */ data: T; /** * Error message (if any) */ error?: string; /** * Additional metadata */ meta?: { page?: number; limit?: number; total?: number; totalPages?: number; }; } /** * Raw documents list response from API */ interface DocumentsListResponse { /** * Array of documents */ data: DocumentMetadata[]; /** * Pagination metadata */ meta?: { page?: number; limit?: number; total?: number; totalPages?: number; }; } /** * Normalized documents list response */ interface NormalizedDocumentsListResponse { /** * Array of normalized documents */ data: DocumentMetadata[]; /** * Standardized pagination metadata */ meta: PaginationMeta; } /** * Documents statistics response from API */ interface DocumentsStatisticsResponse { /** * Total documents count */ total: number; /** * Count by status */ byStatus: Record; /** * Count by document type */ byType: Record; /** * Count by owner type */ byOwner: Record; } /** * Raw document response from Didox API * Used for getById method - returns document as-is without normalization */ type RawDocumentResponse = any; /** * Raw document privileges response from Didox API * Used for getPrivileges method - returns privileges array as-is without normalization */ type RawDocumentPrivilegesResponse = any; /** * Pagination metadata */ interface PaginationMeta { /** * Current page number */ currentPage: number; /** * Total number of pages */ totalPages: number; /** * Total number of items */ totalItems: number; /** * Number of items per page */ itemsPerPage: number; /** * Whether there is a next page */ hasNext: boolean; /** * Whether there is a previous page */ hasPrevious: boolean; } /** * Date range filter for document queries */ interface DateRangeFilter { /** * Start date (ISO format: YYYY-MM-DD) */ from?: string; /** * End date (ISO format: YYYY-MM-DD) */ to?: string; } /** * Document filtering parameters subset */ interface DocumentFilterParams { /** * Filter by creation date from */ dateFromCreated?: string; /** * Filter by creation date to */ dateToCreated?: string; /** * Filter by modification date from */ dateFromModified?: string; /** * Filter by modification date to */ dateToModified?: string; /** * Filter by document status */ status?: number | number[]; /** * Filter by document type */ type?: number | number[]; /** * Filter by partner identifier */ partner?: string; /** * Search query string */ search?: string; /** * Owner type filter */ owner?: OwnerType; } /** * Documents API client for Didox platform * * Provides methods for managing electronic documents including invoices, * waybills, acts, and other document types supported by the Didox EDO platform. */ declare class DocumentsClient { private readonly httpClient; /** * Document builders for fluent document creation * * Provides chainable, type-safe builders for all supported document types. * Each builder offers IDE-friendly methods for constructing valid document payloads. * * @example * ```typescript * // Create invoice using builder * const payload = client.documents.builders.invoice() * .raw({ FacturaType: 0 }) * .build(); * * await client.documents.createDraft('002', payload); * * // Create TTN using builder * const ttnPayload = client.documents.builders.ttn() * .raw({ transportInfo: { vehicleNumber: '01A123BC' } }) * .build(); * * await client.documents.createDraft('041', ttnPayload); * ``` */ readonly builders: { readonly invoice: DocumentBuilderFactory; readonly invoicePharm: DocumentBuilderFactory; readonly hybridInvoice: DocumentBuilderFactory; readonly ttn: DocumentBuilderFactory; readonly act: DocumentBuilderFactory; readonly contract: DocumentBuilderFactory; readonly empowerment: typeof empowerment; readonly arbitrary: DocumentBuilderFactory; readonly verificationAct: DocumentBuilderFactory; readonly acceptanceTransfer: DocumentBuilderFactory; readonly foundersProtocol: typeof foundersProtocol; readonly letterNK: typeof letterNK; readonly multiParty: DocumentBuilderFactory; }; constructor(httpClient: HttpClient); /** * Get paginated list of documents * * Retrieves a filtered and paginated list of documents based on specified criteria. * Supports filtering by status, type, dates, partner, and other parameters. * * @param params - Filtering and pagination parameters * @returns Promise resolving to paginated document list * * @throws {DidoxValidationError} When parameters are invalid * @throws {DidoxAuthError} When authentication fails (401 status) * @throws {DidoxApiError} When API returns other error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const documents = await client.documents.list({ * owner: 1, // outgoing documents * page: 1, * limit: 20, * status: [1, 2], // sent or signed * dateFromCreated: '2024-01-01', * dateToCreated: '2024-01-31' * }); * * console.log('Found documents:', documents.data.length); * console.log('Total pages:', documents.meta.totalPages); * } catch (error) { * if (error instanceof DidoxValidationError) { * console.error('Invalid parameters:', error.message); * } * } * ``` */ list(params: ListDocumentsParams): Promise; /** * Get document statistics * * Retrieves statistical information about documents matching the specified criteria. * Returns counts by status, type, and other aggregations. * * @param params - Filtering parameters (same as list method) * @returns Promise resolving to document statistics * * @throws {DidoxValidationError} When parameters are invalid * @throws {DidoxAuthError} When authentication fails (401 status) * @throws {DidoxApiError} When API returns other error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const stats = await client.documents.statistics({ * owner: 1, * page: 1, * limit: 1, // Minimal page for stats * dateFromCreated: '2024-01-01' * }); * * console.log('Total documents:', stats.total); * console.log('By status:', stats.byStatus); * console.log('By type:', stats.byType); * } catch (error) { * console.error('Failed to get statistics:', error.message); * } * ``` */ statistics(params: ListDocumentsParams): Promise; /** * Get document by ID * * Retrieves detailed information about a specific document by its unique identifier. * Returns raw Didox API response without any normalization or transformation. * * @param id - Document unique identifier * @returns Promise resolving to raw document response from Didox API * * @throws {DidoxValidationError} When document ID is invalid * @throws {DidoxAuthError} When authentication fails (401 status) * @throws {DidoxApiError} When API returns other error responses (e.g., 404 if document not found) * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const document = await client.documents.getById('11F092E3428D10C68F7B1E0008000075'); * * // Raw Didox API response structure * console.log('Document data:', document); * // Note: Structure depends on document type and Didox API version * } catch (error) { * if (error instanceof DidoxApiError && error.statusCode === 404) { * console.error('Document not found'); * } * } * ``` */ getById(id: string): Promise; /** * Get document privileges * * Retrieves user privileges for a specific document, indicating what actions * the current user can perform. Returns raw Didox API response without normalization. * * @param id - Document unique identifier * @returns Promise resolving to raw document privileges response from Didox API * * @throws {DidoxValidationError} When document ID is invalid * @throws {DidoxAuthError} When authentication fails (401 status) * @throws {DidoxApiError} When API returns other error responses * @throws {DidoxNetworkError} When network request fails * * @example * ```typescript * try { * const privileges = await client.documents.getPrivileges('11F092E3428D10C68F7B1E0008000075'); * * // Raw Didox API response - structure may vary * console.log('Privileges data:', privileges); * * // Example of potential structure (actual may differ): * // { * // canView: true, * // canEdit: false, * // canSign: true, * // canCancel: false, * // canDelete: false, * // canDownload: true * // } * } catch (error) { * console.error('Failed to get privileges:', error.message); * } * ``` */ getPrivileges(id: string): Promise; /** * Create document draft * * Creates a draft document in Didox system using the specified document type and payload. * This is a universal method that accepts any document structure without validation. * * @param docType - Didox document type code (e.g. '002', '041', '075') * @param payload - Raw document JSON body according to Didox API specification * @param options - Additional options for request handling * @param options.output - Response mode: 'wrapped' (default) handles errors, 'raw' returns as-is * @returns Promise resolving to raw Didox API response * * @throws {DidoxValidationError} When docType or payload is invalid * @throws {DidoxApiError} When API returns error responses (unless output = 'raw') * @throws {DidoxAuthError} When authentication fails (unless output = 'raw') * @throws {DidoxNetworkError} When network request fails (unless output = 'raw') * * @example * ```typescript * // Create invoice draft * const invoice = await client.documents.createDraft('002', { * // Invoice payload structure according to Didox API * sellerInfo: { tin: '123456789', name: 'Company LLC' }, * buyerInfo: { tin: '987654321', name: 'Client Corp' }, * items: [{ name: 'Product', price: 1000, quantity: 1 }] * }); * * // Create transport waybill with raw output * const ttn = await client.documents.createDraft('041', ttnPayload, { * output: 'raw' * }); * * // Create act of work completed * const act = await client.documents.createDraft('075', actPayload); * ``` */ createDraft(docType: string, payload: unknown, options?: { output?: 'wrapped' | 'raw'; }): Promise; /** * Build URL with query parameters for API requests * * Transforms the ListDocumentsParams into a URL with query parameters. * Handles arrays by converting them to comma-separated strings. * Only includes parameters that have defined values. * * @private * @param endpoint - Base endpoint URL * @param params - Document filtering parameters * @returns Complete URL with query parameters */ private buildUrlWithParams; } /** * Main Didox SDK client * * @example * ```typescript * const didox = new DidoxClient({ * partnerToken: 'your-partner-token', * environment: 'development' * }); * * // Login as legal entity * const result = await didox.auth.loginLegalEntity({ * taxId: '123456789', * password: 'your-password' * }); * ``` */ declare class DidoxClient { private readonly config; private readonly httpClient; /** * Authentication API */ readonly auth: AuthApi; /** * Account / Profile API */ readonly account: AccountApi; /** * Company Profile API */ readonly profile: ProfileApi; /** * Utilities API */ readonly utilities: UtilitiesApi; /** * Documents API */ readonly documents: DocumentsClient; constructor(config: DidoxConfig); /** * Get the current configuration */ getConfig(): Readonly; /** * Set access token for authenticated requests * This is called automatically after successful login */ setAccessToken(token: string): void; /** * Clear access token */ clearAccessToken(): void; /** * Validate the configuration */ private validateConfig; } /** * Base class for all Didox SDK errors */ declare abstract class DidoxError extends Error { readonly name: string; readonly timestamp: Date; constructor(message: string, name: string); } /** * Validation error thrown when input parameters are invalid */ declare class DidoxValidationError extends DidoxError { readonly field: string | undefined; constructor(message: string, field?: string); } /** * Authentication error thrown when auth operations fail */ declare class DidoxAuthError extends DidoxError { readonly statusCode: number | undefined; constructor(message: string, statusCode?: number); } /** * API error thrown when Didox API returns an error response */ declare class DidoxApiError extends DidoxError { readonly statusCode: number; readonly response?: unknown; constructor(message: string, statusCode: number, response?: unknown); } /** * Network error thrown when HTTP requests fail (timeout, connection issues, etc.) */ declare class DidoxNetworkError extends DidoxError { readonly cause: Error | undefined; constructor(message: string, cause?: Error); } export { AccountApi, type AccountProfile, type AddProductClassRequest, type AddProductClassResponse, AuthApi, BaseDocumentBuilder, type CompanyBranch, type CompanyLoginRequest, type CompanyLoginResponse, type CompanyProfile, type DateRangeFilter, DidoxApiError, DidoxAuthError, DidoxClient, type DidoxConfig, DidoxError, type DidoxLocale, DidoxNetworkError, DidoxRoleCode, DidoxValidationError, type DocumentBuilderFactory, type DocumentCreatePayload, type DocumentFilterParams, type DocumentMetadata, type DocumentPrivileges, type DocumentResponse, type DocumentStatistics, DocumentStatus, DocumentType, DocumentsClient, type DocumentsListResponse, type DocumentsStatisticsResponse, GNKRoleCode, type GetBranchesByTinRequest, type LegalEntityInfo, type LegalEntityLoginRequest, type LegalEntityLoginResponse, type ListDocumentsParams, type NormalizedDocumentsListResponse, OwnerType, type PaginationMeta, type ProductClass, type ProductClassCodesResponse, type ProductClassOrigin, type ProductClassPackage, type ProductClassSearchParams, type ProductClassSearchResponse, ProductClassesApi, type ProductClassesCodeCheckResponse, ProfileApi, type ProfileOperators, type ProfileUpdateRequest, type ProfileUpdateResponse, type RawDocumentPrivilegesResponse, type RawDocumentResponse, type RelatedCompany, type RemoveProductClassResponse, type SupportedLanguage, type TaxpayerTypeResponse, type UpdateCompanyUsersPermissionsRequest, type UpdateCompanyUsersPermissionsResponse, type UpdateProfileRequest, type UpdateProfileResponse, type UserPermissions, UsersApi, UtilitiesApi, VatApi, VatRegStatus, type VatRegStatusResponse, type Warehouse, WarehousesApi, type WarehousesResponse, builders };