UNPKG

ofd.ru

Version:

API клиент ОФД OFD.ru на TypeScript

467 lines (448 loc) 18.1 kB
const FERMA_TEST_OPTIONS = { /** Базовый тестовый URL */ baseUrl: "https://ferma-test.ofd.ru/api", /** ИНН тестовой организации */ inn: "3245001416", /** Данные для тестирования ФФД версии 1.1 */ ffd11: { /** Логин */ login: "fermatest1", /** Пароль */ password: "Hjsf3321klsadfAA" }, /** Данные для тестирования ФФД весрии 1.2 */ ffd12: { /** Логин */ login: "fermatest2", /** Пароль */ password: "Go2999483Mb" } }; var ReceiptType = /* @__PURE__ */ ((ReceiptType2) => { ReceiptType2["Income"] = "Income"; ReceiptType2["IncomeReturn"] = "IncomeReturn"; ReceiptType2["IncomePrepayment"] = "IncomePrepayment"; ReceiptType2["IncomeReturnPrepayment"] = "IncomeReturnPrepayment"; ReceiptType2["IncomeCorrection"] = "IncomeCorrection"; ReceiptType2["BuyCorrection"] = "BuyCorrection"; ReceiptType2["IncomeReturnCorrection"] = "IncomeReturnCorrection"; ReceiptType2["ExpenseReturnCorrection"] = "ExpenseReturnCorrection"; ReceiptType2["Expense"] = "Expense"; ReceiptType2["ExpenseReturn"] = "ExpenseReturn"; return ReceiptType2; })(ReceiptType || {}); var TaxationSystem = /* @__PURE__ */ ((TaxationSystem2) => { TaxationSystem2["Common"] = "Common"; TaxationSystem2["SimpleIn"] = "SimpleIn"; TaxationSystem2["SimpleInOut"] = "SimpleInOut"; TaxationSystem2["Unified"] = "Unified"; TaxationSystem2["UnifiedAgricultural"] = "UnifiedAgricultural"; TaxationSystem2["Patent"] = "Patent"; return TaxationSystem2; })(TaxationSystem || {}); var ReceiptPaymentType = /* @__PURE__ */ ((ReceiptPaymentType2) => { ReceiptPaymentType2[ReceiptPaymentType2["Product"] = 1] = "Product"; ReceiptPaymentType2[ReceiptPaymentType2["ExciseProduct"] = 2] = "ExciseProduct"; ReceiptPaymentType2[ReceiptPaymentType2["Work"] = 3] = "Work"; ReceiptPaymentType2[ReceiptPaymentType2["Service"] = 4] = "Service"; ReceiptPaymentType2[ReceiptPaymentType2["GamblingBet"] = 5] = "GamblingBet"; ReceiptPaymentType2[ReceiptPaymentType2["GamblingWin"] = 6] = "GamblingWin"; ReceiptPaymentType2[ReceiptPaymentType2["LotteryTicket"] = 7] = "LotteryTicket"; ReceiptPaymentType2[ReceiptPaymentType2["LotteryWin"] = 8] = "LotteryWin"; ReceiptPaymentType2[ReceiptPaymentType2["IntellectualProperty"] = 9] = "IntellectualProperty"; ReceiptPaymentType2[ReceiptPaymentType2["AdvancePayment"] = 10] = "AdvancePayment"; ReceiptPaymentType2[ReceiptPaymentType2["AgencyFee"] = 11] = "AgencyFee"; ReceiptPaymentType2[ReceiptPaymentType2["CompositeItem"] = 12] = "CompositeItem"; ReceiptPaymentType2[ReceiptPaymentType2["OtherItem"] = 13] = "OtherItem"; ReceiptPaymentType2[ReceiptPaymentType2["PropertyTransfer"] = 14] = "PropertyTransfer"; ReceiptPaymentType2[ReceiptPaymentType2["NonOperationalIncome"] = 15] = "NonOperationalIncome"; ReceiptPaymentType2[ReceiptPaymentType2["InsuranceContributions"] = 16] = "InsuranceContributions"; ReceiptPaymentType2[ReceiptPaymentType2["TradeFee"] = 17] = "TradeFee"; ReceiptPaymentType2[ReceiptPaymentType2["ResortFee"] = 18] = "ResortFee"; ReceiptPaymentType2[ReceiptPaymentType2["Pledge"] = 19] = "Pledge"; ReceiptPaymentType2[ReceiptPaymentType2["ExpenseReduction"] = 20] = "ExpenseReduction"; ReceiptPaymentType2[ReceiptPaymentType2["PensionContributionsIP"] = 21] = "PensionContributionsIP"; ReceiptPaymentType2[ReceiptPaymentType2["PensionContributions"] = 22] = "PensionContributions"; ReceiptPaymentType2[ReceiptPaymentType2["MedicalContributionsIP"] = 23] = "MedicalContributionsIP"; ReceiptPaymentType2[ReceiptPaymentType2["MedicalContributions"] = 24] = "MedicalContributions"; ReceiptPaymentType2[ReceiptPaymentType2["SocialContributions"] = 25] = "SocialContributions"; ReceiptPaymentType2[ReceiptPaymentType2["CasinoPayment"] = 26] = "CasinoPayment"; ReceiptPaymentType2[ReceiptPaymentType2["CashIssuance"] = 27] = "CashIssuance"; ReceiptPaymentType2[ReceiptPaymentType2["ExciseProductNoMark"] = 30] = "ExciseProductNoMark"; ReceiptPaymentType2[ReceiptPaymentType2["ExciseProductMark"] = 31] = "ExciseProductMark"; ReceiptPaymentType2[ReceiptPaymentType2["ProductNoMark"] = 32] = "ProductNoMark"; ReceiptPaymentType2[ReceiptPaymentType2["ProductMark"] = 33] = "ProductMark"; return ReceiptPaymentType2; })(ReceiptPaymentType || {}); var AgentType = /* @__PURE__ */ ((AgentType2) => { AgentType2["BankPaymentAgent"] = "BANK_PAYMENT_AGENT"; AgentType2["BankPaymentSubagent"] = "BANK_PAYMENT_SUBAGENT"; AgentType2["PaymentAgent"] = "PAYMENT_AGENT"; AgentType2["PaymentSubagent"] = "PAYMENT_SUBAGENT"; AgentType2["Confidant"] = "CONFIDANT"; AgentType2["Commissioner"] = "COMMISSIONER"; AgentType2["Agent"] = "AGENT"; return AgentType2; })(AgentType || {}); var CorrectionType = /* @__PURE__ */ ((CorrectionType2) => { CorrectionType2["Self"] = "SELF"; CorrectionType2["INSTRUCTION"] = "INSTRUCTION"; return CorrectionType2; })(CorrectionType || {}); var IdDocumentType = /* @__PURE__ */ ((IdDocumentType2) => { IdDocumentType2["RfId"] = "RF_ID"; IdDocumentType2["RfIdEtc"] = "RF_ID_ETC"; IdDocumentType2["TempRfId"] = "TEMP_RF_ID"; IdDocumentType2["BirthRfId"] = "BIRTH_RF_ID"; IdDocumentType2["OtherRfId"] = "OTHER_RF_ID"; IdDocumentType2["ForeignId"] = "FOREIGN_ID"; IdDocumentType2["ForeignIdOther"] = "FOREIGN_ID_OTHER"; IdDocumentType2["IdForeignStateless"] = "ID_FOREIGN_STATELESS"; IdDocumentType2["ResidencePermit"] = "RESIDENCE_PERMIT"; IdDocumentType2["TempResidencePermit"] = "TEMP_RESIDENCE_PERMIT"; IdDocumentType2["StatelessReviewId"] = "STATELESS_REVIEW_ID"; IdDocumentType2["RefugeeId"] = "REFUGEE_ID"; IdDocumentType2["OtherId"] = "OTHER_ID"; IdDocumentType2["StatelessReviewRfId"] = "STATELESS_REVIEW_RF_ID"; return IdDocumentType2; })(IdDocumentType || {}); var FoivId = /* @__PURE__ */ ((FoivId2) => { FoivId2["Mvd"] = "001"; FoivId2["Emercom"] = "002"; FoivId2["Mid"] = "003"; FoivId2["Rossotrudnichestvo"] = "004"; FoivId2["MoD"] = "005"; FoivId2["Fsvts"] = "006"; FoivId2["Fstek"] = "007"; FoivId2["Minjust"] = "008"; FoivId2["Fsinn"] = "009"; FoivId2["Fssp"] = "010"; FoivId2["Gfs"] = "011"; FoivId2["Svr"] = "012"; FoivId2["Fsb"] = "013"; FoivId2["Rosgvardiya"] = "014"; FoivId2["Fso"] = "015"; FoivId2["Rosfinmonitoring"] = "016"; FoivId2["Rosarkhiv"] = "017"; FoivId2["Gusp"] = "018"; FoivId2["Udp"] = "019"; FoivId2["Minzdrav"] = "020"; FoivId2["Roszdravnadzor"] = "021"; FoivId2["Mincult"] = "022"; FoivId2["Minobrnauki"] = "023"; FoivId2["Minprirody"] = "024"; FoivId2["Roshydromet"] = "025"; FoivId2["Rosprirodnadzor"] = "026"; FoivId2["Rosvodresursy"] = "027"; FoivId2["Rosleskhoz"] = "028"; FoivId2["Rosnedra"] = "029"; FoivId2["Minpromtorg"] = "030"; FoivId2["Rosstandart"] = "031"; FoivId2["Minpros"] = "032"; FoivId2["Minvostokrazvitiya"] = "033"; FoivId2["Minselhoz"] = "034"; FoivId2["Rosselkhoznadzor"] = "035"; FoivId2["Rosrybolovstvo"] = "036"; FoivId2["Minsport"] = "037"; FoivId2["Minstroy"] = "038"; FoivId2["Mintrans"] = "039"; FoivId2["Rostransnadzor"] = "040"; FoivId2["Rosaviatsiya"] = "041"; FoivId2["Rosavtodor"] = "042"; FoivId2["Roszheldor"] = "043"; FoivId2["Rosmorrechflot"] = "044"; FoivId2["Mintrud"] = "045"; FoivId2["Rostrud"] = "046"; FoivId2["Minfin"] = "047"; FoivId2["Fns"] = "048"; FoivId2["Probe"] = "049"; FoivId2["Rosalkogol"] = "050"; FoivId2["Fts"] = "051"; FoivId2["Treasury"] = "052"; FoivId2["Rosimushchestvo"] = "053"; FoivId2["Mintsyfra"] = "054"; FoivId2["Roskomnadzor"] = "055"; FoivId2["Rospechat"] = "056"; FoivId2["Rossvyaz"] = "057"; FoivId2["Minekonomrazvitiya"] = "058"; FoivId2["Rosakkreditatsiya"] = "059"; FoivId2["Rosstat"] = "060"; FoivId2["Rospatent"] = "061"; FoivId2["Rostourism"] = "062"; FoivId2["Minenergo"] = "063"; FoivId2["Fas"] = "064"; FoivId2["Rosreestr"] = "065"; FoivId2["Rospotrebnadzor"] = "066"; FoivId2["Rosobrnadzor"] = "067"; FoivId2["Rostekhnadzor"] = "068"; FoivId2["Rosrezerv"] = "069"; FoivId2["Fmba"] = "070"; FoivId2["Rosmolodezh"] = "071"; FoivId2["Fadn"] = "072"; return FoivId2; })(FoivId || {}); var PaymentType = /* @__PURE__ */ ((PaymentType2) => { PaymentType2[PaymentType2["Cash"] = 0] = "Cash"; PaymentType2[PaymentType2["Cashless"] = 1] = "Cashless"; PaymentType2[PaymentType2["Prepayment"] = 2] = "Prepayment"; PaymentType2[PaymentType2["Credit"] = 3] = "Credit"; PaymentType2[PaymentType2["Other"] = 4] = "Other"; return PaymentType2; })(PaymentType || {}); var Vat = /* @__PURE__ */ ((Vat2) => { Vat2["VatNo"] = "VatNo"; Vat2["Vat5"] = "Vat5"; Vat2["CalculatedVat5105"] = "CalculatedVat5105"; Vat2["Vat7"] = "Vat7"; Vat2["CalculatedVat7107"] = "CalculatedVat7107"; Vat2["Vat10"] = "Vat10"; Vat2["Vat20"] = "Vat20"; Vat2["Vat0"] = "Vat0"; Vat2["CalculatedVat10110"] = "CalculatedVat10110"; Vat2["CalculatedVat20120"] = "CalculatedVat20120"; return Vat2; })(Vat || {}); var PaymentMethod = /* @__PURE__ */ ((PaymentMethod2) => { PaymentMethod2[PaymentMethod2["FullPrepayment"] = 1] = "FullPrepayment"; PaymentMethod2[PaymentMethod2["Prepayment"] = 2] = "Prepayment"; PaymentMethod2[PaymentMethod2["Advance"] = 3] = "Advance"; PaymentMethod2[PaymentMethod2["FullPayment"] = 4] = "FullPayment"; PaymentMethod2[PaymentMethod2["PartialPayment"] = 5] = "PartialPayment"; PaymentMethod2[PaymentMethod2["CreditTransfer"] = 6] = "CreditTransfer"; PaymentMethod2[PaymentMethod2["CreditPayment"] = 7] = "CreditPayment"; return PaymentMethod2; })(PaymentMethod || {}); var MarkingCodeType = /* @__PURE__ */ ((MarkingCodeType2) => { MarkingCodeType2["UnknownProductCode"] = "UNKNOWN_PRODUCT_CODE"; MarkingCodeType2["Ean8"] = "EAN8"; MarkingCodeType2["Ean13"] = "EAN13"; MarkingCodeType2["Itf14"] = "ITF14"; MarkingCodeType2["Gs1"] = "GS1"; MarkingCodeType2["Gs1m"] = "GS1M"; MarkingCodeType2["ShortMc"] = "SHORT_MC"; MarkingCodeType2["Fur"] = "FUR"; MarkingCodeType2["Egais20"] = "EGAIS20"; MarkingCodeType2["Egais30"] = "EGAIS30"; MarkingCodeType2["Ktf1"] = "KTF1"; MarkingCodeType2["Ktf2"] = "KTF2"; MarkingCodeType2["Ktf3"] = "KTF3"; MarkingCodeType2["Ktf4"] = "KTF4"; MarkingCodeType2["Ktf5"] = "KTF5"; MarkingCodeType2["Ktf6"] = "KTF6"; return MarkingCodeType2; })(MarkingCodeType || {}); var MarkingCodePlannedStatus = /* @__PURE__ */ ((MarkingCodePlannedStatus2) => { MarkingCodePlannedStatus2["PieceProductIncome"] = "PIECE_PRODUCT_INCOME"; MarkingCodePlannedStatus2["MeasuredProductIncome"] = "MEASURED_PRODUCT_INCOME"; MarkingCodePlannedStatus2["PieceProductReturn"] = "PIECE_PRODUCT_RETURN"; MarkingCodePlannedStatus2["MeasuredProductReturn"] = "MEASURED_PRODUCT_RETURN"; MarkingCodePlannedStatus2["ProductStatusNotChanged"] = "PRODUCT_STATUS_NOT_CHANGED"; return MarkingCodePlannedStatus2; })(MarkingCodePlannedStatus || {}); var Measure = /* @__PURE__ */ ((Measure2) => { Measure2["Piece"] = "PIECE"; Measure2["Gram"] = "GRAM"; Measure2["Kilogram"] = "KILOGRAM"; Measure2["Ton"] = "TON"; Measure2["Centimeter"] = "CENTIMETER"; Measure2["Decimeter"] = "DECIMETER"; Measure2["Meter"] = "METER"; Measure2["SquareCentimeter"] = "SQUARE_CENTIMETER"; Measure2["SquareDecimeter"] = "SQUARE_DECIMETER"; Measure2["SquareMeter"] = "SQUARE_METER"; Measure2["Milliliter"] = "MILLILITER"; Measure2["Liter"] = "LITER"; Measure2["CubicMeter"] = "CUBIC_METER"; Measure2["KilowattHour"] = "KILOWATT_HOUR"; Measure2["Gigacalorie"] = "GIGACALORIE"; Measure2["Day"] = "DAY"; Measure2["Hour"] = "HOUR"; Measure2["Minute"] = "MINUTE"; Measure2["Second"] = "SECOND"; Measure2["Kilobyte"] = "KILOBYTE"; Measure2["Megabyte"] = "MEGABYTE"; Measure2["Gigabyte"] = "GIGABYTE"; Measure2["Terabyte"] = "TERABYTE"; Measure2["Other"] = "OTHER"; return Measure2; })(Measure || {}); class AuthTokenManager { fetcher; login; password; authToken; /** Timestamp истечения токена, UTC */ authTokenExpirationTimestamp; constructor(fetcher, login, password) { this.fetcher = fetcher; this.login = login; this.password = password; } async updateAuthToken() { const { Data: { AuthToken, ExpirationDateUtc } } = await this.fetcher.fetch("/Authorization/CreateAuthToken", { method: "POST", body: JSON.stringify({ Login: this.login, Password: this.password }) }); this.authToken = AuthToken; this.authTokenExpirationTimestamp = Date.parse(ExpirationDateUtc); } async getAuthToken() { if (!this.authToken || this.authTokenExpirationTimestamp && this.authTokenExpirationTimestamp < Date.now()) { await this.updateAuthToken(); } return this.authToken; } } class FermaApiError extends Error { /** Запрос к API */ request; /** Ответ API */ response; /** * Код ошибки * * @see https://ofd.ru/razrabotchikam/ferma#%D0%BE%D0%BF%D0%B8%D1%81%D0%B0%D0%BD%D0%B8%D0%B5_%D0%BE%D1%88%D0%B8%D0%B1%D0%BE%D0%BA */ code; constructor(data, request, response) { super(`${data.Error.Message}. Код ошибки: ${data.Error.Code}`); this.name = "FermaApiError"; this.response = response; this.code = data.Error.Code; this.request = request; } } class FermaError extends Error { /** Запрос к API */ request; /** Ответ API */ response; constructor(message, request, response) { super(message); this.name = "FermaError"; this.response = response; this.request = request; } } class FermaFetcher { baseUrl; constructor(baseUrl = "https://ferma.ofd.ru/api") { this.baseUrl = baseUrl; } async fetch(path, options) { const request = new Request(`${this.baseUrl}${path}`, { ...options, headers: { "Content-Type": "application/json", ...options?.headers } }); try { const response = await fetch(request); const data = await response.json(); if (data.Status === "Failed") throw new FermaApiError(data, request, response); return data; } catch (error) { if (error instanceof FermaApiError) throw error; if (error instanceof SyntaxError) throw new FermaError("Неверный JSON ответ", request); if (error instanceof Error) throw new FermaError(error.message, request); throw new FermaError("Неизвестная ошибка", request); } } } class FermaAuthedFetcher { fetcher; authTokenManager; constructor(fetcher, login, password) { this.fetcher = fetcher; this.authTokenManager = new AuthTokenManager(fetcher, login, password); } async fetch(path, options, includeAuthToken = true) { if (includeAuthToken) { const authToken = await this.authTokenManager.getAuthToken(); const url = new URL(`${this.fetcher.baseUrl}${path}`); url.searchParams.append("AuthToken", authToken); const urlString = url.toString(); return this.fetcher.fetch( urlString.replace(this.fetcher.baseUrl, ""), options ); } return this.fetcher.fetch(path, { ...options }); } } class Ferma { authedFetcher; /** * Конструктор класса * * Значения параметров можно получить в личном кабинете клиента в разделе Ferma®, после покупки услуг сервиса Ferma® или узнать у вашего менеджера. * */ constructor({ login, password, baseUrl }) { this.authedFetcher = new FermaAuthedFetcher( new FermaFetcher(baseUrl), login, password ); } /** * Запрос на формирование фискальных документов. * * @param data Данные для формирования документа * @returns ID документа * * @see https://ofd.ru/razrabotchikam/ferma#%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81_%D0%BD%D0%B0_%D1%84%D0%BE%D1%80%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D1%84%D0%B8%D1%81%D0%BA%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D1%85_%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D0%BE%D0%B2 */ async createReceipt(data) { const { Data: { ReceiptId } } = await this.authedFetcher.fetch( "/kkt/cloud/receipt", { method: "POST", body: JSON.stringify({ Request: data }) } ); return ReceiptId; } /** * Проверка статуса кассового чека. * * Важно! Информация о статусе кассового чека хранится в оперативной памяти сервиса Ferma® всего сутки. После истечения суток при повторном запросе статуса кассового чека в ответ будет выведена ошибка «Чек не найден». После истечения суток информацию о статусе кассового чека можно получить в запросе реестра кассовых чеков. * * @param data `InvoiceId` или `ReceiptId` чека * @returns Статус чека * * @see https://ofd.ru/razrabotchikam/ferma#%D0%BF%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%BA%D0%B0_%D1%81%D1%82%D0%B0%D1%82%D1%83%D1%81%D0%B0_%D0%BA%D0%B0%D1%81%D1%81%D0%BE%D0%B2%D0%BE%D0%B3%D0%BE_%D1%87%D0%B5%D0%BA%D0%B0 */ async getReceipt(data) { const { Data } = await this.authedFetcher.fetch( "/kkt/cloud/status", { method: "POST", body: JSON.stringify({ Request: data }) } ); return Data; } } export { AgentType, CorrectionType, FERMA_TEST_OPTIONS, Ferma, FoivId, IdDocumentType, MarkingCodePlannedStatus, MarkingCodeType, Measure, PaymentMethod, PaymentType, ReceiptPaymentType, ReceiptType, TaxationSystem, Vat }; //# sourceMappingURL=index.js.map