aves-sdk 1.2.3 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,2 @@
1
- var pe=Object.defineProperty;var nt=(e,t,n)=>t in e?pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var a=(e,t)=>pe(e,"name",{value:t,configurable:!0});var p=(e,t,n)=>nt(e,typeof t!="symbol"?t+"":t,n);import{Module as Kt,Global as Wt}from"@nestjs/common";import{ConfigModule as tt}from"@nestjs/config";import{Inject as Ze,Injectable as _t}from"@nestjs/common";var A=Symbol("AVES_SDK_CONFIG"),F=Symbol("XML_HTTP_CLIENT");var g={SEARCH_MASTER_RECORD:"SearchMasterRecordRQ",MANAGE_MASTER_RECORD:"ManageMasterRecordRQ",BOOK_FILE:"BookFileRQ",MODI_FILE_HEADER:"ModiFileHeaderRQ",MOD_FILE_SERVICES:"ModFileServicesRQ",SET_STATUS:"SetStatusRQ",SET_STATUS_SERVICE:"SetStatusServiceRQ",CANCEL_FILE:"CancelFileRQ",FILE_PAYMENT_LIST:"FilePaymentListRQ",PRINT_BOOKING_DOCUMENT:"PrintBookingDocumentRQ"};var S={SEARCH_MASTER_RECORDS:"/interop/masterRecords/v2/rest/Search",INSERT_OR_UPDATE_MASTER_RECORD:"/interop/masterRecords/v2/rest/InsertOrUpdate",CREATE_BOOKING_FILE:"/interop/booking/v2/rest/CreateBookingFile",MOD_BOOKING_FILE_HEADER:"/interop/booking/v2/rest/ModBookingFileHeader",MOD_BOOKING_FILE_SERVICES:"/interop/booking/v2/rest/ModBookingFileServices",SET_BOOKING_FILE_STATUS:"/interop/booking/v2/rest/SetBookingFileStatus",SET_BOOKING_FILE_SERVICE_STATUS:"/interop/booking/v2/rest/SetBookingFileServiceStatus",CANCEL_BOOKING_FILE:"/interop/booking/v2/rest/CancelBookingFile",INSERT_FILE_PAYMENT_LIST:"/interop/booking/v2/rest/InsertFilePaymentList",PRINT_BOOKING_DOCUMENT:"/interop/document/v2/rest/PrintBookingDocument"};import{z as o}from"zod";var f={ADULT:"adult",CHILD:"child",INFANT:"infant",SENIOR:"senior"},y={MALE:"male",FEMALE:"female"},O={FLIGHT:"flight",HOTEL:"hotel",CAR:"car",TRANSFER:"transfer",INSURANCE:"insurance"},P={CONFIRMED:"confirmed",PENDING:"pending",CANCELLED:"cancelled"},v={CREDIT_CARD:"credit_card",DEBIT_CARD:"debit_card",BANK_TRANSFER:"bank_transfer",CASH:"cash"},V={PENDING:"pending",CONFIRMED:"confirmed",FAILED:"failed"},C={CUSTOMER:"customer",SUPPLIER:"supplier",VOUCHER:"voucher",SUPPLIER_VOUCHER:"supplier_voucher"},T={ENABLED:"enabled",WARNING:"warning",BLACKLISTED:"blacklisted",DISABLED:"disabled"},l={QUOTATION:"quotation",WORK_IN_PROGRESS:"work_in_progress",CONFIRMED:"confirmed",OPTIONED:"optioned",NULLIFIED:"nullified",CANCELED:"canceled"},I={VISA_REQUEST:"visa_request",TRAVEL_INFORMATION:"travel_information",VOUCHER:"voucher",BOOKING_CONTRACT:"booking_contract",BOOKING_CONFIRMATION:"booking_confirmation",SUPPLIER_SERVICE_LIST:"supplier_service_list",INVOICE:"invoice",PROFORMA_INVOICE:"proforma_invoice",ADEGUAMENTO:"adeguamento",RESERVATION_FORM:"reservation_form",OPEN_XML:"open_xml",SALES_INVOICE:"sales_invoice",TICKETING_TMASTER:"ticketing_tmaster",SUMMARY_FORM:"summary_form"},w={PDF:"pdf",HTML:"html",XML:"xml"},j={EMAIL:"email",SMS:"sms",DOWNLOAD:"download"},B={CUSTOMER_REQUEST:"customer_request",NO_SHOW:"no_show",OPERATIONAL:"operational",OTHER:"other"},X={ORIGINAL_PAYMENT:"original_payment",CREDIT:"credit",CASH:"cash"},k={SERVICE:"service",TAX:"tax",FEE:"fee",DISCOUNT:"discount"},G={SENT:"sent",PENDING:"pending",FAILED:"failed"},rt=o.enum(["home","work","billing","delivery"]),$=o.enum(["home","work","mobile","fax"]),st=o.enum(["home","work"]),it=o.enum([f.ADULT,f.CHILD,f.INFANT,f.SENIOR]),at=o.enum(["mr","mrs","ms","dr","prof"]),Re=o.enum([y.MALE,y.FEMALE]),ct=o.enum([O.FLIGHT,O.HOTEL,O.CAR,O.TRANSFER,O.INSURANCE]),mt=o.enum([P.CONFIRMED,P.PENDING,P.CANCELLED]),ut=o.enum([v.CREDIT_CARD,v.DEBIT_CARD,v.BANK_TRANSFER,v.CASH]),pt=o.enum([V.PENDING,V.CONFIRMED,V.FAILED]),lt=o.enum([C.CUSTOMER,C.SUPPLIER,C.VOUCHER,C.SUPPLIER_VOUCHER]),to=o.enum(["equals","contains","starts_with","ends_with"]),oo=o.enum(["individual","group","corporate"]),no=o.enum(["low","normal","high","urgent"]),ro=o.enum(["meal","seat","wheelchair","other"]),dt=o.enum([B.CUSTOMER_REQUEST,B.NO_SHOW,B.OPERATIONAL,B.OTHER]),Et=o.enum([X.ORIGINAL_PAYMENT,X.CREDIT,X.CASH]),Rt=o.enum([I.VISA_REQUEST,I.TRAVEL_INFORMATION,I.VOUCHER,I.BOOKING_CONTRACT,I.BOOKING_CONFIRMATION,I.SUPPLIER_SERVICE_LIST,I.INVOICE,I.PROFORMA_INVOICE,I.ADEGUAMENTO,I.RESERVATION_FORM,I.OPEN_XML,I.SALES_INVOICE,I.TICKETING_TMASTER,I.SUMMARY_FORM]),gt=o.enum([w.PDF,w.HTML,w.XML]),St=o.enum([j.EMAIL,j.SMS,j.DOWNLOAD]),Z=o.enum([l.QUOTATION,l.WORK_IN_PROGRESS,l.CONFIRMED,l.OPTIONED,l.NULLIFIED,l.CANCELED]),It=o.enum([k.SERVICE,k.TAX,k.FEE,k.DISCOUNT]),so=o.enum([G.SENT,G.PENDING,G.FAILED]),Ct=o.enum([T.ENABLED,T.WARNING,T.BLACKLISTED,T.DISABLED]),Tt=o.enum(["email","sms","phone"]),D=o.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in YYYY-MM-DD format"),z=o.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?$/,"DateTime must be in ISO 8601 format"),ge=o.object({type:rt.optional(),street:o.string().max(100,"Street must be 100 characters or less").optional(),city:o.string().max(50,"City must be 50 characters or less").optional(),state:o.string().max(50,"State must be 50 characters or less").optional(),postalCode:o.string().max(20,"Postal code must be 20 characters or less").optional(),country:o.string().max(50,"Country must be 50 characters or less").optional()}),Se=o.object({phone:o.object({type:$.optional(),number:o.string().min(1,"Phone number is required").max(30,"Phone number must be 30 characters or less")}).optional(),email:o.object({type:st.optional(),address:o.string().email("Valid email address is required").max(100,"Email must be 100 characters or less")}).optional(),mobile:o.object({type:$.optional(),number:o.string().min(1,"Mobile number is required").max(30,"Mobile number must be 30 characters or less")}).optional(),fax:o.object({type:$.optional(),number:o.string().min(1,"Fax number is required").max(30,"Fax number must be 30 characters or less")}).optional(),webUrl:o.string().url("Valid URL is required").max(200,"Web URL must be 200 characters or less").optional()}),b=o.object({id:o.string().max(6,"Customer ID must be 6 characters or less"),type:lt,status:Ct,personalInfo:o.object({title:o.string().max(10,"Title must be 10 characters or less").optional(),firstName:o.string().min(1,"First name is required").max(50,"First name must be 50 characters or less"),lastName:o.string().min(1,"Last name is required").max(50,"Last name must be 50 characters or less"),dateOfBirth:D.optional(),gender:Re.optional(),nationality:o.string().max(3,"Nationality code must be 3 characters or less").optional(),birthCity:o.string().max(50,"Birth city must be 50 characters or less").optional(),birthCounty:o.string().max(10,"Birth county code must be 10 characters or less").optional()}).optional(),contact:Se.optional(),address:ge.optional(),businessInfo:o.object({companyName:o.string().max(100,"Company name must be 100 characters or less").optional(),taxId:o.string().max(30,"Tax ID must be 30 characters or less").optional(),vatCode:o.string().max(30,"VAT code must be 30 characters or less").optional(),fiscalCode:o.string().max(30,"Fiscal code must be 30 characters or less").optional(),licenseNumber:o.string().max(50,"License number must be 50 characters or less").optional(),priceListCode:o.string().max(30,"Price list code must be 30 characters or less").optional()}).optional(),preferences:o.object({language:o.string().length(2,"Language code must be exactly 2 characters").optional(),currency:o.string().length(3,"Currency code must be exactly 3 characters").optional(),communicationMethod:Tt.optional()}).optional(),meta:o.object({createdDate:o.string().optional(),modifiedDate:o.string().optional(),loginType:o.enum(["WEB_BOOKING","BUSINESS_TRAVEL","GROUP_TRAVEL","SUPPLIER","ADMINISTRATOR"]).optional(),thirdPartRecordCode:o.string().max(50,"Third part record code must be 50 characters or less").optional(),searchField:o.string().max(100,"Search field must be 100 characters or less").optional(),extraInfo:o.string().max(500,"Extra info must be 500 characters or less").optional()}).optional(),codes:o.object({zoneCode:o.string().max(10,"Zone code must be 10 characters or less").optional(),areaCode:o.string().max(10,"Area code must be 10 characters or less").optional(),branchOfficeCode:o.string().max(10,"Branch office code must be 10 characters or less").optional(),categoryCode:o.string().max(10,"Category code must be 10 characters or less").optional(),activityCode:o.string().max(10,"Activity code must be 10 characters or less").optional(),promoterCode:o.string().max(10,"Promoter code must be 10 characters or less").optional(),networkCode:o.string().max(10,"Network code must be 10 characters or less").optional()}).optional()}),J=o.object({id:o.string().regex(/^\d{3}$/,"Passenger ID must be 3 digits (001, 002, etc.)"),type:it,title:at.optional(),firstName:o.string().min(1,"First name is required").max(50,"First name must be 50 characters or less"),lastName:o.string().min(1,"Last name is required").max(50,"Last name must be 50 characters or less"),dateOfBirth:D.optional(),gender:Re.optional(),nationality:o.string().max(3,"Nationality code must be 3 characters or less").optional(),passport:o.object({number:o.string().min(1,"Passport number is required").max(20,"Passport number must be 20 characters or less"),expiryDate:D,issuingCountry:o.string().min(1,"Issuing country is required").max(3,"Country code must be 3 characters or less")}).optional(),address:ge.optional(),contact:Se.optional()}),ee=o.object({id:o.string().min(1,"Service ID is required"),type:ct,status:mt,code:o.string().max(50,"Service code must be 50 characters or less").optional(),name:o.string().max(200,"Service name must be 200 characters or less").optional(),description:o.string().max(500,"Description must be 500 characters or less").optional(),startDate:D.optional(),endDate:D.optional(),price:o.object({currency:o.string().length(3,"Currency code must be exactly 3 characters"),amount:o.number().nonnegative("Amount must be non-negative")}).optional()}),le=o.object({id:o.string().min(1,"Payment ID is required"),type:ut,status:pt,amount:o.object({currency:o.string().length(3,"Currency code must be exactly 3 characters"),amount:o.number().positive("Amount must be positive")}),details:o.object({cardNumber:o.string().max(20,"Card number must be 20 characters or less").optional(),expiryDate:o.string().regex(/^\d{2}\/\d{2}$/,"Expiry date must be in MM/YY format").optional(),cardHolderName:o.string().max(100,"Cardholder name must be 100 characters or less").optional()}).optional()}),h=o.object({pages:o.number().int().positive("Pages must be positive").max(100,"Pages cannot exceed 100"),page:o.number().int().min(1,"Page must be at least 1")}).optional(),Ie=o.discriminatedUnion("type",[o.object({type:o.literal("code"),code:o.string().min(1,"Code is required").max(6,"Code must be 6 characters or less"),pagination:h}),o.object({type:o.literal("name"),name:o.string().min(1,"Name is required"),city:o.string().max(50,"City must be 50 characters or less").optional(),pagination:h}),o.object({type:o.literal("vat_code"),vatCode:o.string().min(1,"VAT code is required"),phoneNumber:o.string().max(30,"Phone number must be 30 characters or less").optional(),pagination:h}),o.object({type:o.literal("zone"),zipCode:o.string().min(1,"Zip code is required"),city:o.string().max(50,"City must be 50 characters or less").optional(),countyCode:o.string().max(10,"County code must be 10 characters or less").optional(),pagination:h}),o.object({type:o.literal("category"),categoryCode:o.string().min(1,"Category code is required"),pagination:h}),o.object({type:o.literal("email"),email:o.email("Valid email is required"),pagination:h}),o.object({type:o.literal("last_mod_date"),from:o.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in YYYY-MM-DD format"),to:o.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in YYYY-MM-DD format"),pagination:h}),o.object({type:o.literal("search_field"),searchField:o.string().min(1,"Search field is required"),pagination:h}),o.object({type:o.literal("external_ref_code"),externalRefCode:o.string().min(1,"External ref code is required"),pagination:h})]),de=o.object({createDate:o.string().optional(),bookingFileRefCode:o.string().max(50).optional(),travelAgentCode:o.string().max(30).optional(),clerkName:o.string().max(60).optional(),description:o.string().max(200,"Description must be 200 characters or less").optional(),startDate:o.string().min(1,"Start date is required"),endDate:o.string().min(1,"End date is required"),currency:o.string().max(3,"Currency code must be 3 characters or less").optional(),markupCode:o.string().max(20).optional(),bookingFileStatus:o.object({value:Z,expiredDate:D.optional()}).optional(),passengers:o.array(J).min(1,"At least one passenger is required").max(99,"Maximum 99 passengers allowed"),services:o.array(ee).min(1,"At least one service is required").max(50,"Maximum 50 services allowed"),statisticCodes:o.object({code1:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code2:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code3:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code4:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code5:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code6:o.string().max(4,"Statistic code must be 4 characters or less").optional()}).optional(),destination:o.object({code:o.string().optional(),iataCode:o.string().optional(),nationCode:o.string().optional()}).optional(),earlyBookingDate:D.optional(),cupCode:o.string().max(30).optional(),cigCode:o.string().max(30).optional(),customerPromoterCode:o.string().max(20).optional(),billingReferenceCode:o.string().max(20).optional(),paymentReferenceCode:o.string().max(20).optional(),deadlines:o.array(o.object({code:o.string().min(1,"Deadline code is required"),description:o.string().optional(),expireDate:o.string().optional()})).optional(),printDocument:o.boolean().optional(),sendDocumentViaEmail:o.boolean().optional(),bookingFinancialInfo:o.object({customerPaymentType:o.enum(["CASH","BANK","RID","RIBA","SPECIFIC_CODE","NOT_SET"]).optional(),customerSpecPaymentTypeCode:o.string().max(20).optional()}).optional(),groupingPaxPolicy:o.enum(["GROUPED_PAX","NOT_GROUPED_PAX","ONE_PAX_ONLY"]).optional(),groupBookingFile:o.boolean().optional(),typeDownloadFile:o.enum(["AVES2AVES","AVES2AVESVIA","AVES2AVESITA"]).optional(),setBookingFileCodeFromStartDate:o.boolean().optional()}),Ce=o.union([de.extend({customerId:o.string().max(6,"Customer ID must be 6 characters or less").min(1,"Customer ID is required"),customerDetails:o.never().optional()}),de.extend({customerId:o.never().optional(),customerDetails:b})]),Te=o.object({bookingId:o.string().min(1,"Booking ID is required").max(20,"Booking ID must be 20 characters or less"),customerId:o.string().max(6,"Customer ID must be 6 characters or less").optional(),reason:dt,description:o.string().max(500,"Description must be 500 characters or less").optional(),refundRequest:o.object({amount:o.number().positive("Refund amount must be positive"),currency:o.string().length(3,"Currency code must be exactly 3 characters"),method:Et}).optional()}),fe=o.object({bookingId:o.string().min(1,"Booking ID is required").max(20,"Booking ID must be 20 characters or less"),customerId:o.string().max(6,"Customer ID must be 6 characters or less").optional(),documentType:Rt,format:gt.optional(),language:o.string().length(2,"Language code must be exactly 2 characters").optional(),deliveryMethod:o.object({type:St,address:o.string().max(100,"Delivery address must be 100 characters or less").optional()}).optional()}),ye=o.union([o.object({bookingId:o.string().min(1,"Booking ID is required").max(20,"Booking ID must be 20 characters or less"),bookingRefCode:o.never().optional(),payments:o.array(le).min(1,"At least one payment is required").max(20,"Maximum 20 payments allowed"),enableMultiple:o.boolean().optional(),operationType:o.enum(["absolute","final","final_no_controls"]).optional()}),o.object({bookingId:o.never().optional(),bookingRefCode:o.string().min(1,"Booking reference code is required").max(20,"Booking reference code must be 20 characters or less"),payments:o.array(le).min(1,"At least one payment is required").max(20,"Maximum 20 payments allowed"),enableMultiple:o.boolean().optional(),operationType:o.enum(["absolute","final","final_no_controls"]).optional()})]),io=o.object({bookingId:o.string().min(1,"Booking ID is required").max(20,"Booking ID must be 20 characters or less"),customerId:o.string().max(6,"Customer ID must be 6 characters or less"),startDate:D,passengers:o.array(J).optional(),notes:o.string().max(999,"Notes must be 999 characters or less").optional(),statisticCodes:o.object({code1:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code2:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code3:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code4:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code5:o.string().max(4,"Statistic code must be 4 characters or less").optional(),code6:o.string().max(4,"Statistic code must be 4 characters or less").optional()}).optional()}),ao=o.object({bookingId:o.string().min(1,"Booking ID is required").max(20,"Booking ID must be 20 characters or less"),customerId:o.string().max(6,"Customer ID must be 6 characters or less"),services:o.array(ee).min(1,"At least one service is required").max(50,"Maximum 50 services allowed")}),co=o.object({bookingId:o.string().min(1,"Booking ID is required").max(20,"Booking ID must be 20 characters or less"),customerId:o.string().max(6,"Customer ID must be 6 characters or less"),status:Z,expireDate:D.optional()}),mo=o.object({id:o.string().min(1,"Booking ID is required"),status:Z,createdAt:z,updatedAt:z,description:o.string().optional(),nation:o.string().optional(),destination:o.string().optional(),firstConfirmationDate:z.optional(),paxNumber:o.number().int().nonnegative().optional(),reference:o.string().optional(),clerkName:o.string().optional(),customer:b,passengers:o.array(J),services:o.array(ee),pricing:o.object({totalAmount:o.object({currency:o.string().length(3,"Currency code must be exactly 3 characters"),amount:o.number().nonnegative("Amount must be non-negative")}),breakdowns:o.array(o.object({type:It,description:o.string().min(1,"Description is required"),amount:o.number()})).optional(),totals:o.object({beforeDiscount:o.number().optional(),afterDiscount:o.number().optional(),discount:o.number().optional(),withoutVat:o.number().optional(),dueAmount:o.number().optional(),paidAmount:o.number().optional(),balance:o.number().optional()}).optional()})}),uo=o.object({customers:o.array(b),pagination:o.object({page:o.number().int().min(1,"Page must be at least 1"),pages:o.number().int().min(1,"Pages must be at least 1"),totalItems:o.number().int().min(0,"Total items must be non-negative"),hasMore:o.boolean()})}),Ee=o.object({fileName:o.string().min(1,"File name is required"),content:o.string().optional(),contentSize:o.number().int().min(0,"Content size must be non-negative")}),po=o.object({emailRecipient:o.email("Valid email address is required").optional(),documents:o.array(Ee).min(0,"Documents array is required"),additionalDocuments:o.array(o.object({emailRecipient:o.string().email("Valid email address is required"),documents:o.array(Ee)})).optional()}),lo=o.object({success:o.boolean(),message:o.string().optional(),data:o.any().optional()});var oe=class oe{constructor(t){p(this,"RqHeader");p(this,"Body");Object.assign(this,t)}};a(oe,"RequestPayload");var te=oe,ne=class ne{constructor(t){p(this,"Request");this.Request=new te(t)}};a(ne,"WrapRequestDto");var q=ne;var _=a(e=>{let t;if(typeof e=="string"){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))throw new Error(`Invalid date format. Expected YYYY-MM-DD, got: ${e}`);try{t=new Date(e+"T00:00:00.000Z")}catch{throw new Error(`Invalid date string: ${e}`)}}else t=e;if(isNaN(t.getTime()))throw new Error(`Invalid date value: ${e}`);let n=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0");return`${n}-${r}-${i}`},"createDateString"),H=a(e=>{let t;if(typeof e=="string"){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?$/.test(e))throw new Error(`Invalid datetime format. Expected ISO 8601, got: ${e}`);try{t=new Date(e)}catch{throw new Error(`Invalid datetime string: ${e}`)}}else t=e;if(isNaN(t.getTime()))throw new Error(`Invalid datetime value: ${e}`);return t.toISOString()},"createDateTimeString");function he(e){return{[C.CUSTOMER]:"CUSTOMER",[C.SUPPLIER]:"SUPPLIER",[C.VOUCHER]:"VOUCHER",[C.SUPPLIER_VOUCHER]:"SUPPLIER_VOUCHER"}[e]||"CUSTOMER"}a(he,"mapCustomerTypeToXml");function De(e){return{CUSTOMER:C.CUSTOMER,SUPPLIER:C.SUPPLIER,VOUCHER:C.VOUCHER,SUPPLIER_VOUCHER:C.SUPPLIER_VOUCHER}[e]||C.CUSTOMER}a(De,"mapCustomerTypeFromXml");function Ne(e){return{[T.ENABLED]:"ENABLED",[T.WARNING]:"WARNING",[T.BLACKLISTED]:"BLACKLISTED",[T.DISABLED]:"DISABLED"}[e]||"ENABLED"}a(Ne,"mapCustomerStatusToXml");function Ae(e){return{ENABLED:T.ENABLED,WARNING:T.WARNING,BLACKLISTED:T.BLACKLISTED,DISABLED:T.DISABLED}[e]||T.ENABLED}a(Ae,"mapCustomerStatusFromXml");function re(e){return{[l.QUOTATION]:"QUOTATION",[l.WORK_IN_PROGRESS]:"WORK_IN_PROGRESS",[l.CONFIRMED]:"CONFIRMED",[l.OPTIONED]:"OPTIONED",[l.NULLIFIED]:"NULLIFIED",[l.CANCELED]:"CANCELED"}[e]??"QUOTATION"}a(re,"mapBookingStatusToXml");function Oe(e){return{QUOTATION:l.QUOTATION,WORK_IN_PROGRESS:l.WORK_IN_PROGRESS,CONFIRMED:l.CONFIRMED,OPTIONED:l.OPTIONED,NULLIFIED:l.NULLIFIED,CANCELED:l.CANCELED}[e]??l.QUOTATION}a(Oe,"mapBookingStatusFromXml");function be(e){return{visa_request:"VISA_REQUEST",travel_information:"TRAVEL_INFORMATION",voucher:"VOUCHER",booking_contract:"BOOKING_CONTRACT",booking_confirmation:"BOOKING_CONFIRMATION",supplier_service_list:"SUPPLIER_SERVICE_LIST",invoice:"INVOICE",proforma_invoice:"PROFORMA_INVOICE",adeguamento:"ADEGUAMENTO",reservation_form:"RESERVATION_FORM",open_xml:"OPEN_XML",sales_invoice:"SALES_INVOICE",ticketing_tmaster:"TICKETING_TMASTER",summary_form:"SUMMARY_FORM"}[e]||"VOUCHER"}a(be,"mapDocumentTypeToXml");function _e(e){return{male:"M",female:"F"}[e]||"M"}a(_e,"mapGenderToXml");var ft=new Set(["QUOTATION","WORK_IN_PROGRESS","CONFIRMED","OPTIONED","CANCELED"]),yt={CONFIRM:"CONFIRMED",OPTION:"OPTIONED",REQUEST:"WORK_IN_PROGRESS",NULLIFIED:"CANCELED"};function ht(e){let t=e.toUpperCase(),n=yt[t];return n||(ft.has(t)?t:"QUOTATION")}a(ht,"normalizeBookingStatus");function Dt(e){let t=typeof e=="string"?e:re(e);return ht(t)}a(Dt,"mapBookingFileStatusForRQ");function Le(e){let t=(e.Name||"").split(" "),n=t.pop()||"",r=t.join(" ")||e.Name,i={AD:f.ADULT,CH:f.CHILD,IN:f.INFANT,OV:f.SENIOR};return{id:e["@RPH"],type:i[e.CategoryCode]||f.ADULT,title:void 0,firstName:r,lastName:n,dateOfBirth:e.BirthDate?_(e.BirthDate):void 0,gender:e.Sex==="M"?y.MALE:e.Sex==="F"?y.FEMALE:void 0,nationality:e.NationCode||e.CitizenshipCode,passport:e.IDDocInfo?{number:e.IDDocInfo["@IDCode"]||"",expiryDate:_(e.IDDocInfo["@IDExpireDate"]||""),issuingCountry:""}:void 0,address:void 0,contact:e.eMail||e.PhoneNumber?{email:e.eMail?{address:e.eMail}:void 0,phone:e.PhoneNumber?{number:e.PhoneNumber}:void 0}:void 0}}a(Le,"mapPassengerFromXml");function Fe(e){return{id:e["@ServiceCode"],type:O.HOTEL,status:P.PENDING,code:e["@ServiceCode"],name:e.FirstDescription,description:e.SecondDescription,startDate:e.StartDate?_(e.StartDate):void 0,endDate:e.EndDate?_(e.EndDate):void 0,price:e.ServiceTotalAmountDetail?.ServiceTotalPrice?{currency:"EUR",amount:parseFloat(e.ServiceTotalAmountDetail.ServiceTotalPrice)}:void 0}}a(Fe,"mapServiceFromXml");var Nt=a((e,t)=>{switch(e.type){case"code":t.RecordCode=e.code;break;case"name":t.Name=e.name,e.city&&(t.City=e.city);break;case"vat_code":t.VatCode=e.vatCode,e.phoneNumber&&(t.PhoneNumber=e.phoneNumber);break;case"zone":t.ZipCode=e.zipCode,e.city&&(t.City=e.city),e.countyCode&&(t.CountyCode=e.countyCode);break;case"category":t.CategoryCode=e.categoryCode;break;case"email":t.Email=e.email;break;case"last_mod_date":t.LastModificationDate={"@MinDate":e.from,"@MaxDate":e.to};break;case"search_field":t.SearchFieldValue=e.searchField;break;case"external_ref_code":t.SearchFieldValue=e.externalRefCode;break}return t},"buildSearchMasterRecordRQ");function Pe(e){let t={SearchType:e.type.toUpperCase()};return Nt(e,t)}a(Pe,"mapSearchCustomerToXml");function K(e){let t=e.personalInfo?`${e.personalInfo.firstName} ${e.personalInfo.lastName}`.trim():e.id;return{"@RecordCode":e.id,RecordType:he(e.type),Name:t,LanguageCode:e.preferences?.language||"01",Moniker:e.personalInfo?.title,Gender:e.personalInfo?.gender?_e(e.personalInfo?.gender):void 0,BirthDate:e.personalInfo?.dateOfBirth,CitizenshipCode:e.personalInfo?.nationality,Email:e.contact?.email?.address,FirstPhoneNumber:e.contact?.phone?.number,MobilePhone:e.contact?.phone?.number,Address:e.address?.street,CityName:e.address?.city,StateCode:e.address?.country,ZipCode:e.address?.postalCode,FiscalCode:e.businessInfo?.taxId,VatCode:e.businessInfo?.taxId,RecordStatus:Ne(e.status),FinancialDetail:e.preferences?.currency?{"@CurrencyCode":e.preferences.currency}:void 0}}a(K,"mapCustomerToXml");function xe(e){let t=e.customerDetails?K(e.customerDetails):{"@RecordCode":e.customerId||"",RecordType:"CUSTOMER",Name:"Customer",LanguageCode:"01"};return{CreateDate:e.createDate,BookingFileRefCode:e.bookingFileRefCode,TravelAgentCode:e.travelAgentCode,ClerkName:e.clerkName,CustomerDetail:t,CurrencyCode:e.currency,MarkupCode:e.markupCode,BookingFileStatus:e.bookingFileStatus?{"@Value":Dt(e.bookingFileStatus.value),...e.bookingFileStatus.expiredDate&&{"@ExpiredDate":e.bookingFileStatus.expiredDate}}:{"@Value":"QUOTATION"},StatisticCodes:e.statisticCodes?{"@sCode1":e.statisticCodes.code1,"@sCode2":e.statisticCodes.code2,"@sCode3":e.statisticCodes.code3,"@sCode4":e.statisticCodes.code4,"@sCode5":e.statisticCodes.code5,"@sCode6":e.statisticCodes.code6}:void 0,Destination:e.destination?{"@Code":e.destination.code,"@IataCode":e.destination.iataCode,"@NationCode":e.destination.nationCode}:void 0,BookingFileDescription:e.description,StartDate:e.startDate,EndDate:e.endDate,EarlyBookingDate:e.earlyBookingDate,CupCode:e.cupCode,CigCode:e.cigCode,CustomerPromoterCode:e.customerPromoterCode,BillingReferenceCode:e.billingReferenceCode,PaymentReferenceCode:e.paymentReferenceCode,BookingFileDocument:e.printDocument!==void 0||e.sendDocumentViaEmail!==void 0?{"@PrintDoc":e.printDocument||!1,"@SendDocViaEmail":e.sendDocumentViaEmail||!1}:void 0,DeadlineList:e.deadlines?{DeadlineDetail:e.deadlines.map(n=>({"@DeadlineCode":n.code,"@Description":n.description,"@ExpireDate":n.expireDate}))}:void 0,BookingFinancialInfo:e.bookingFinancialInfo?{"@Customer_PaymentType":e.bookingFinancialInfo.customerPaymentType||"NOT_SET","@Customer_SpecPaymentTypeCode":e.bookingFinancialInfo.customerSpecPaymentTypeCode}:void 0,GroupingPaxPolicy:e.groupingPaxPolicy,GroupBookingFile:e.groupBookingFile,TypeDownloadFile:e.typeDownloadFile,SetBookingFileCodeFromStartDate:e.setBookingFileCodeFromStartDate,PassengerList:{PassengerDetail:e.passengers.map((n,r)=>Me(n,r+1))},SelectedServiceList:{SelectedServiceDetail:e.services.map((n,r)=>ve(n,r+1))}}}a(xe,"mapCreateBookingToXml");function Me(e,t){return{"@RPH":String(t).padStart(3,"0"),Name:`${e.firstName} ${e.lastName}`,CategoryCode:e.type===f.ADULT?"AD":e.type===f.CHILD?"CH":e.type===f.INFANT?"IN":"OV",Sex:e.gender===y.MALE?"M":"F",BirthDate:e.dateOfBirth,eMail:e.contact?.email?.address,PhoneNumber:e.contact?.phone?.number}}a(Me,"mapPassengerToAvesXml");function ve(e,t){return{"@sCode":e.id,AvesServiceType:"TOP",StartDate:e.startDate||new Date().toISOString(),EndDate:e.endDate||new Date().toISOString(),Qty:1,Pax:1,AvesSession:t}}a(ve,"mapServiceToAvesXml");function Be(e){return{BookingFileCode:e.bookingId,CustomerRecordCode:e.customerId||""}}a(Be,"mapCancelBookingToXml");function ke(e){return{RefMasterRecordCode:e.customerId||"",LanguageCode:e.language||"01",BookingFileCode:e.bookingId,InfoDocumentsToPrint:{InfoDocumentToPrint:[{DocumentType:be(e.documentType)}]},GetDocumentContent:e.deliveryMethod?.type==="download",SendDocumentViaEmail:e.deliveryMethod?.type==="email"}}a(ke,"mapPrintDocumentToXml");function Ue(e){let t="AbsoluteAmountsInsertion";return e.operationType==="final"?t="FinalAmountToAchieve":e.operationType==="final_no_controls"&&(t="FinalAmountToAchieveWithoutControls"),{BookingFileCode:e.bookingId,BookingFileRefCode:e.bookingRefCode,EnableMultiplePayments:e.enableMultiple??e.payments.length>1,OperationType:t,FilePaymentList:{FilePaymentDetail:e.payments.map(n=>({"@PaymentDate":new Date().toISOString(),"@Amount":String(n.amount?.amount||0),"@PaymentType":At(n.type)}))}}}a(Ue,"mapAddPaymentToXml");function At(e){return{cash:"C",bank:"B",bank2:"D",bank3:"T",atm:"P",creditCard:"R",credit_card:"R",rebate:"A"}[e]||"C"}a(At,"mapPaymentTypeToAvesXml");function Ve(e){let t=K(e);return t["@InsertCriteria"]="S",{MasterRecordDetail:t}}a(Ve,"mapCreateCustomerToXml");function we(e){let t=K(e);return t["@InsertCriteria"]="T",{MasterRecordDetail:t}}a(we,"mapUpdateCustomerToXml");function je(e){let t=K(e);return t["@InsertCriteria"]="M",{MasterRecordDetail:t}}a(je,"mapUpsertCustomerToXml");function Xe(e,t,n,r){return{BookingFileCode:t,BookingFileStartDate:n,CustomerRecordCode:e,NewCustomerRecordCode:r?.newCustomerRecordCode,BookingNote:r?.notes,PassengerList:r?.passengers?{PassengerDetail:r.passengers.map((i,c)=>Me(i,c+1))}:void 0}}a(Xe,"mapUpdateBookingHeaderToXml");function Ge(e,t,n){return{CustomerRecordCode:e,BookingFileCode:t,SelectedServiceList:{SelectedServiceDetail:n.map((r,i)=>ve(r,i+1))}}}a(Ge,"mapUpdateBookingServicesToXml");function qe(e,t,n,r){return{CustomerRecordCode:e,BookingFileCode:t,FileStatus:{"@Value":re(n),...r?.expiredDate&&{"@ExpiredDate":r.expiredDate},...r?.optionedFileExpireDatePolicy&&{"@OptionedFileExpireDatePolicy":r.optionedFileExpireDatePolicy}},...r?.backOfficeRequest!==void 0&&{BackOfficeRequest:r.backOfficeRequest},...r?.printDoc!==void 0||r?.sendDocViaEmail!==void 0?{BookingFileDocument:{"@PrintDoc":r.printDoc||!1,"@SendDocViaEmail":r.sendDocViaEmail||!1}}:{},...r?.applyPenalty!==void 0&&{Penalty:{"@Apply":r.applyPenalty,...r.penaltyCode&&{"@SpecificCode":r.penaltyCode}}},...r?.simulateCancelAndGetPenalty!==void 0&&{SimulateCancelAndGetPenaltyAmount:r.simulateCancelAndGetPenalty}}}a(qe,"mapSetBookingStatusToXml");function He(e,t,n,r){return{CustomerRecordCode:e,BookingFileCode:t,BookingServiceRef:n,BookingFileServiceStatus:"NULLIFIED",...r&&{BookingFileServiceStatusDate:r}}}a(He,"mapSetBookingServiceStatusToXml");function se(e){let t=(e.Name??"").split(" "),n=t.pop()??"",r=t.join(" ")??e.Name;return{id:e["@RecordCode"],type:De(e.RecordType),status:Ae(e.RecordStatus??""),personalInfo:{title:e.Moniker,firstName:r,lastName:n,dateOfBirth:e.BirthDate?_(e.BirthDate):void 0,gender:e.Gender==="M"?y.MALE:e.Gender==="F"?y.FEMALE:void 0,nationality:e.CitizenshipCode,birthCity:e.BirthCity,birthCounty:e.BirthCounty},contact:{email:e.Email?{address:e.Email}:void 0,phone:e.FirstPhoneNumber?{number:e.FirstPhoneNumber}:void 0,mobile:e.MobilePhone?{number:e.MobilePhone}:void 0,fax:e.FaxNumber?{number:e.FaxNumber}:void 0,webUrl:e.WebUrl},address:e.Address?{street:e.Address,city:e.CityName,state:e.CountyCode,postalCode:e.ZipCode,country:e.StateCode}:void 0,businessInfo:e.VatCode||e.FiscalCode?{companyName:void 0,taxId:e.VatCode||e.FiscalCode,licenseNumber:void 0,vatCode:e.VatCode,fiscalCode:e.FiscalCode,priceListCode:e.PriceListCode}:void 0,preferences:{language:e.LanguageCode,currency:e.FinancialDetail?.["@CurrencyCode"],communicationMethod:void 0},meta:{createdDate:e.CreatedDate,modifiedDate:e.ModifiedDate,loginType:e.LoginType,thirdPartRecordCode:e.ThirdPartRecordCode,searchField:e.SearchField,extraInfo:e.ExtraInfo},codes:{zoneCode:e.ZoneCode,areaCode:e.AreaCode,branchOfficeCode:e.BranchOfficeCode,categoryCode:e.CategoryCode,activityCode:e.ActivityCode,promoterCode:e.PromoterCode,networkCode:e.NetworkCode}}}a(se,"mapCustomerFromXml");function W(e){return e?e.MasterRecordDetail?{success:!0,message:"Operation successful",data:se(e.MasterRecordDetail)}:{success:!1,message:"No master record in response",data:void 0}:{success:!1,message:"Invalid XML response",data:void 0}}a(W,"mapCustomerResponseFromXml");function Ot(e){return{id:e.BookingFileCode,status:Oe(e.BookingFileStatus["@Value"]),createdAt:H(e.CreationDate),updatedAt:H(e.CreationDate),description:e.Description,nation:e.Nation,destination:e.Destination,firstConfirmationDate:e.FirstConfirmationDate?H(e.FirstConfirmationDate):void 0,paxNumber:e.PaxNumber,reference:e.Reference,clerkName:e.ClerkName,customer:se({"@RecordCode":e.CustomerRecordCode,RecordType:"CUSTOMER",Name:e.CustomerName,LanguageCode:"01",Email:e.CustomerEmail}),passengers:e.PassengerList.PassengerDetail.map(Le),services:e.BookedServiceList?.BookedServiceDetail.map(Fe)||[],pricing:{totalAmount:{currency:e.TotalAmountDetail?.CurrencyCode||"EUR",amount:parseFloat(e.TotalAmountDetail?.TotalAmountAfterDiscount||"0")},breakdowns:void 0,totals:e.TotalAmountDetail?{beforeDiscount:parseFloat(e.TotalAmountDetail.TotalAmountBeforeDiscount||"0"),afterDiscount:parseFloat(e.TotalAmountDetail.TotalAmountAfterDiscount||"0"),discount:parseFloat(e.TotalAmountDetail.TotalDiscount||"0"),withoutVat:parseFloat(e.TotalAmountDetail.TotalAmountWithoutVat||"0"),dueAmount:parseFloat(e.TotalAmountDetail.DueAmount||"0"),paidAmount:parseFloat(e.TotalAmountDetail.PaiedAmount||"0"),balance:parseFloat(e.TotalAmountDetail.Balance||"0")}:void 0}}}a(Ot,"mapBookingFromXml");function U(e){if(!e)return{success:!1,message:"Invalid XML response",data:void 0};let t=e.OperationResult["@Status"]==="SUCCESS";if(!t||!e.BookingFile)return{success:t,message:e?.OperationResult["@Message"],data:void 0};let n=Ot(e.BookingFile);return{success:t,message:e.OperationResult["@Message"],data:n}}a(U,"mapBookingResponseFromXml");function Ke(e,t){let i=t?.pages||50,c=t?.page||1;if(!e||!e.MasterRecordList)return{customers:[],pagination:{page:c,pages:1,totalItems:0,hasMore:!1}};let u=e.MasterRecordList.MasterRecordDetail.map(se),E=u.length,ue=E===i,ot=ue?c+1:c;return{customers:u,pagination:{page:c,pages:ot,totalItems:E,hasMore:ue}}}a(Ke,"mapSearchResponseFromXml");function We(e){if(!e)return{success:!1,message:"Invalid XML response",data:void 0};let t=e.BaseDocumentAndAttachments?.SingleBaseDocumentOrAttachment.map(i=>({fileName:i.DocFileName,content:i.Base64DocContent,contentSize:i.Base64DocContent?.length||0}))||[],n=e.AdditionalDocuments?.AdditionalDocument.map(i=>({emailRecipient:i.EmailRecipient,documents:i.BaseDocumentAndAttachments?.SingleBaseDocumentOrAttachment.map(c=>({fileName:c.DocFileName,content:c.Base64DocContent,contentSize:c.Base64DocContent?.length||0}))||[]}));return{success:!0,message:"Documents generated successfully",data:{emailRecipient:e.EmailRecipient,documents:t,additionalDocuments:n}}}a(We,"mapDocumentResponseFromXml");function Ye(e){if(!e)return{success:!1,message:"Invalid XML response",data:void 0};let t=e.OperationResult["@Status"]==="SUCCESS";return t?{success:t,message:e.OperationResult["@Message"],data:{refundInfo:e.OperationResult.RefundInfo?{refundAmount:e.OperationResult.RefundInfo["@RefundAmount"],currency:e.OperationResult.RefundInfo["@Currency"],refundMethod:e.OperationResult.RefundInfo["@RefundMethod"],processingTime:e.OperationResult.RefundInfo["@ProcessingTime"]}:void 0}}:{success:t,message:e?.OperationResult["@Message"],data:void 0}}a(Ye,"mapCancelResponseFromXml");function Qe(e){return e?{success:!0,message:"Payment registered successfully",data:{booking:void 0,paymentSummary:{totalPaid:{currency:"EUR",amount:0},outstandingAmount:{currency:"EUR",amount:0},paymentHistory:[]}}}:{success:!1,message:"Invalid XML response",data:void 0}}a(Qe,"mapPaymentResponseFromXml");function bt(e,t,n,r){var i=arguments.length,c=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")c=Reflect.decorate(e,t,n,r);else for(var E=e.length-1;E>=0;E--)(u=e[E])&&(c=(i<3?u(c):i>3?u(t,n,c):u(t,n))||c);return i>3&&c&&Object.defineProperty(t,n,c),c}a(bt,"_ts_decorate");function $e(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}a($e,"_ts_metadata");function ze(e,t){return function(n,r){t(n,r,e)}}a(ze,"_ts_param");var ie=class ie{constructor(t,n){p(this,"config");p(this,"http");this.config=t,this.http=n}buildHeader(){let{hostId:t,xtoken:n,languageCode:r}=this.config;return{"@HostID":t,"@Xtoken":n,"@Interface":"WEB","@UserName":"WEB","@LanguageCode":r}}wrapRequest(t){return new q({RqHeader:this.buildHeader(),Body:t})}async searchCustomers(t){let n=Ie.parse(t),r=Pe(n),i=await this.http.postXml(S.SEARCH_MASTER_RECORDS,g.SEARCH_MASTER_RECORD,this.wrapRequest(r));return Ke(i.Response.Body,n.pagination)}async createCustomer(t){let n=b.parse(t),r=Ve(n),i=await this.http.postXml(S.INSERT_OR_UPDATE_MASTER_RECORD,g.MANAGE_MASTER_RECORD,this.wrapRequest(r));return W(i.Response.Body)}async updateCustomer(t){let n=b.parse(t),r=we(n),i=await this.http.postXml(S.INSERT_OR_UPDATE_MASTER_RECORD,g.MANAGE_MASTER_RECORD,this.wrapRequest(r));return W(i.Response.Body)}async upsertCustomer(t){let n=b.parse(t),r=je(n),i=await this.http.postXml(S.INSERT_OR_UPDATE_MASTER_RECORD,g.MANAGE_MASTER_RECORD,this.wrapRequest(r));return W(i.Response.Body)}async createBooking(t){let n=Ce.parse(t),r=xe(n),i=await this.http.postXml(S.CREATE_BOOKING_FILE,g.BOOK_FILE,this.wrapRequest(r));return U(i.Response.Body)}async updateBookingHeader(t,n,r,i){let c=Xe(t,n,r,i),u=await this.http.postXml(S.MOD_BOOKING_FILE_HEADER,g.MODI_FILE_HEADER,this.wrapRequest(c));return{success:u.Response.RsStatus["@Status"]==="OK",message:u.Response.RsStatus.ErrorDescription}}async updateBookingServices(t,n,r){let i=Ge(t,n,r),c=await this.http.postXml(S.MOD_BOOKING_FILE_SERVICES,g.MOD_FILE_SERVICES,this.wrapRequest(i));return U(c.Response.Body)}async setBookingStatus(t,n,r,i){let c=qe(t,n,r,i),u=await this.http.postXml(S.SET_BOOKING_FILE_STATUS,g.SET_STATUS,this.wrapRequest(c));return U(u.Response.Body)}async setBookingServiceStatus(t,n,r,i){let c=He(t,n,r,i),u=await this.http.postXml(S.SET_BOOKING_FILE_SERVICE_STATUS,g.SET_STATUS_SERVICE,this.wrapRequest(c));return U(u.Response.Body)}async cancelBooking(t){let n=Te.parse(t),r=Be(n),i=await this.http.postXml(S.CANCEL_BOOKING_FILE,g.CANCEL_FILE,this.wrapRequest(r));return Ye(i.Response.Body)}async addPayment(t){let n=ye.parse(t),r=Ue(n),i=await this.http.postXml(S.INSERT_FILE_PAYMENT_LIST,g.FILE_PAYMENT_LIST,this.wrapRequest(r));return Qe(i.Response.Body)}async printDocument(t){let n=fe.parse(t),r=ke(n),i=await this.http.postXml(S.PRINT_BOOKING_DOCUMENT,g.PRINT_BOOKING_DOCUMENT,this.wrapRequest(r));return We(i.Response.Body)}async searchMasterRecord(t){return this.http.postXml(S.SEARCH_MASTER_RECORDS,g.SEARCH_MASTER_RECORD,this.wrapRequest(t))}async insertOrUpdateMasterRecord(t){return this.http.postXml(S.INSERT_OR_UPDATE_MASTER_RECORD,g.MANAGE_MASTER_RECORD,this.wrapRequest(t))}async createBookingFile(t){return this.http.postXml(S.CREATE_BOOKING_FILE,g.BOOK_FILE,this.wrapRequest(t))}async cancelBookingFile(t){return this.http.postXml(S.CANCEL_BOOKING_FILE,g.CANCEL_FILE,this.wrapRequest(t))}async printBookingDocument(t){return this.http.postXml(S.PRINT_BOOKING_DOCUMENT,g.PRINT_BOOKING_DOCUMENT,this.wrapRequest(t))}};a(ie,"AvesService");var N=ie;N=bt([_t(),ze(0,Ze(A)),ze(1,Ze(F)),$e("design:type",Function),$e("design:paramtypes",[typeof AvesSdkConfig>"u"?Object:AvesSdkConfig,typeof IXmlHttpClient>"u"?Object:IXmlHttpClient])],N);import Pt from"axios";import{XMLBuilder as xt,XMLParser as Mt}from"fast-xml-parser";import{Inject as vt,Injectable as Bt,Scope as kt}from"@nestjs/common";function Lt(e,t,n,r){var i=arguments.length,c=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")c=Reflect.decorate(e,t,n,r);else for(var E=e.length-1;E>=0;E--)(u=e[E])&&(c=(i<3?u(c):i>3?u(t,n,c):u(t,n))||c);return i>3&&c&&Object.defineProperty(t,n,c),c}a(Lt,"_ts_decorate");function Je(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}a(Je,"_ts_metadata");function Ft(e,t){return function(n,r){t(n,r,e)}}a(Ft,"_ts_param");var ae=class ae{constructor(t){p(this,"config");p(this,"httpClient");p(this,"xmlBuilder");p(this,"xmlParser");this.config=t,this.httpClient=Pt.create({baseURL:t.baseUrl,timeout:typeof t.timeout=="number"?t.timeout:3e4,headers:{"Content-Type":"application/xml",Accept:"application/xml, text/xml, */*;q=0.1"},transitional:{clarifyTimeoutError:!0},validateStatus:a(n=>n>=200&&n<300,"validateStatus")}),this.xmlBuilder=new xt({attributeNamePrefix:"@",ignoreAttributes:!1,suppressEmptyNode:!0,format:process.env.NODE_ENV?.toLowerCase()==="development"}),this.xmlParser=new Mt({attributeNamePrefix:"@",ignoreAttributes:!1,parseAttributeValue:!1,trimValues:!0,isArray:a(n=>["Field","Item","Service","Passenger","Payment","MasterRecord","Request","Notes","ServiceID"].includes(n),"isArray")})}async postXml(t,n,r,i){let c=this.xmlBuilder.build({[n]:r}),u=await this.httpClient.post(t,c,i);return this.xmlParser.parse(u.data)}};a(ae,"XmlHttpClient");var x=ae;x=Lt([Bt({scope:kt.DEFAULT}),Ft(0,vt(A)),Je("design:type",Function),Je("design:paramtypes",[typeof AvesSdkConfig>"u"?Object:AvesSdkConfig])],x);import{registerAs as Ut}from"@nestjs/config";var Vt="aves",ce=Ut(Vt,()=>({baseUrl:process.env.AVES_BASE_URL??"",hostId:process.env.AVES_HOST_ID??"",xtoken:process.env.AVES_XTOKEN??"",languageCode:process.env.AVES_LANGUAGE_CODE,timeout:process.env.AVES_TIMEOUT?Number(process.env.AVES_TIMEOUT):void 0}));import{z as s}from"zod";var wt=s.enum(["01","02"]),et=s.object({baseUrl:s.url(),hostId:s.string().length(6),xtoken:s.string(),languageCode:wt.optional(),timeout:s.number().optional()}),jt=s.object({"@Type":s.enum(["HOME","WORK","BILLING","DELIVERY"]).optional(),Street:s.string().max(100).optional(),City:s.string().max(50).optional(),State:s.string().max(50).optional(),PostalCode:s.string().max(20).optional(),Country:s.string().max(50).optional()}),Xt=s.object({Phone:s.object({"@Type":s.enum(["HOME","WORK","MOBILE","FAX"]).optional(),"@Number":s.string()}).optional(),Email:s.object({"@Type":s.enum(["HOME","WORK"]).optional(),"@Address":s.string()}).optional()}),Gt=s.object({"@PassengerID":s.string().min(1),"@Type":s.enum(["ADT","CHD","INF"]),"@Title":s.enum(["MR","MRS","MS","DR","PROF"]).optional(),FirstName:s.string().min(1).max(50),LastName:s.string().min(1).max(50),DateOfBirth:s.date().optional(),Gender:s.enum(["M","F"]).optional(),Nationality:s.string().max(3).optional(),Address:jt.optional(),ContactInfo:Xt.optional()}),qt=s.object({"@ServiceID":s.string().min(1),"@Type":s.enum(["FLIGHT","HOTEL","CAR","TRANSFER","INSURANCE"]),"@Status":s.enum(["CONFIRMED","PENDING","CANCELLED"]),ServiceDetails:s.object({Code:s.string().optional(),Name:s.string().optional(),Description:s.string().optional(),StartDate:s.string().optional(),EndDate:s.string().optional(),Price:s.object({"@Currency":s.string(),"@Amount":s.number()}).optional()})}),Jo=s.object({"@PaymentID":s.string().min(1),"@Type":s.enum(["CREDIT_CARD","DEBIT_CARD","BANK_TRANSFER","CASH"]),"@Status":s.enum(["PENDING","CONFIRMED","FAILED"]),Amount:s.object({"@Currency":s.string(),"@Amount":s.number()}),PaymentDetails:s.object({CardNumber:s.string().optional(),ExpiryDate:s.string().optional(),CardHolderName:s.string().optional()}).optional()}),en=s.object({SearchCriteria:s.object({MasterRecordType:s.enum(["CUSTOMER","AGENT","SUPPLIER"]),SearchFields:s.object({Field:s.array(s.object({"@Name":s.string(),"@Value":s.string(),"@Operator":s.enum(["EQUALS","CONTAINS","STARTS_WITH","ENDS_WITH"]).optional()}))}),Pagination:s.object({"@PageSize":s.number(),"@PageNumber":s.number()}).optional()})}),tn=s.object({BookingDetails:s.object({"@BookingType":s.enum(["INDIVIDUAL","GROUP","CORPORATE"]),"@Priority":s.enum(["LOW","NORMAL","HIGH","URGENT"]),CustomerInfo:s.object({"@CustomerID":s.string().optional(),CustomerDetails:s.any().optional()}),PassengerList:s.object({Passenger:s.array(Gt)}),SelectedServiceList:s.object({Service:s.array(qt)}),SpecialRequests:s.object({Request:s.array(s.object({"@Type":s.enum(["MEAL","SEAT","WHEELCHAIR","OTHER"]),"@Description":s.string()}))}).optional()})}),on=s.object({"@BookingFileID":s.string().min(1),CancellationDetails:s.object({"@Reason":s.enum(["CUSTOMER_REQUEST","NO_SHOW","OPERATIONAL","OTHER"]),"@Description":s.string().optional(),RefundRequest:s.object({"@Amount":s.number(),"@Currency":s.string(),"@Method":s.enum(["ORIGINAL_PAYMENT","CREDIT","CASH"])}).optional()})}),nn=s.object({"@BookingFileID":s.string().min(1),DocumentRequest:s.object({"@DocumentType":s.enum(["CONFIRMATION","INVOICE","VOUCHER","TICKET","ALL"]),"@Format":s.enum(["PDF","HTML","XML"]),"@Language":s.string().optional(),DeliveryMethod:s.object({"@Type":s.enum(["EMAIL","SMS","DOWNLOAD"]),"@Address":s.string().optional()}).optional()})});function Ht(e,t,n,r){var i=arguments.length,c=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")c=Reflect.decorate(e,t,n,r);else for(var E=e.length-1;E>=0;E--)(u=e[E])&&(c=(i<3?u(c):i>3?u(t,n,c):u(t,n))||c);return i>3&&c&&Object.defineProperty(t,n,c),c}a(Ht,"_ts_decorate");var L=class L{static forRoot(t){let n=this.validateConfig(t);return{module:L,imports:[tt.forFeature(ce)],providers:[{provide:A,useValue:n},this.createXmlHttpClientProvider(),N],exports:[N,F]}}static forRootAsync(t){let n=this.createAsyncProviders(t);return{module:L,imports:[...t.imports??[],tt.forFeature(ce)],providers:[...n,this.createXmlHttpClientProvider(),N],exports:[N,F]}}static createXmlHttpClientProvider(){return{provide:F,useClass:x}}static createAsyncProviders(t){if(t.useFactory)return[{provide:A,useFactory:a(async(...i)=>{try{let c=await t.useFactory(...i);return this.validateConfig(c)}catch(c){throw new Error(`Failed to create Aves configuration: ${c.message}`)}},"useFactory"),inject:t.inject??[]}];let n=t.useClass||t.useExisting;if(!n)throw new Error("Invalid AvesModule async options: provide useFactory, useClass, or useExisting");let r=[{provide:A,useFactory:a(async i=>{try{let c=await i.createAvesOptions();return this.validateConfig(c)}catch(c){throw new Error(`Failed to create Aves configuration: ${c.message}`)}},"useFactory"),inject:[n]}];return t.useClass&&r.push({provide:t.useClass,useClass:t.useClass}),r}static validateConfig(t){let n=et.safeParse(t);if(!n.success)throw new Error(`Invalid AVES SDK configuration: ${n.error.issues.map(r=>r.message).join(", ")}`);return n.data}};a(L,"AvesModule"),p(L,"MODULE_NAME","AvesModule"),p(L,"VERSION","1.0.0");var Y=L;Y=Ht([Wt(),Kt({})],Y);import{Injectable as Qt}from"@nestjs/common";var R=(function(e){return e.ERROR="ERROR",e.WARNING="WARNING",e.INFO="INFO",e})({}),m=(function(e){return e.INVALID_TOKEN="AVES_001",e.TOKEN_EXPIRED="AVES_002",e.INSUFFICIENT_PERMISSIONS="AVES_003",e.INVALID_REQUEST_FORMAT="AVES_100",e.MISSING_REQUIRED_FIELD="AVES_101",e.INVALID_FIELD_VALUE="AVES_102",e.INVALID_DATE_FORMAT="AVES_103",e.BOOKING_NOT_FOUND="AVES_200",e.BOOKING_ALREADY_CANCELLED="AVES_201",e.INVALID_BOOKING_STATUS="AVES_202",e.PAYMENT_FAILED="AVES_203",e.INSUFFICIENT_INVENTORY="AVES_204",e.INTERNAL_SERVER_ERROR="AVES_500",e.SERVICE_UNAVAILABLE="AVES_501",e.TIMEOUT="AVES_502",e.RATE_LIMIT_EXCEEDED="AVES_503",e})({});var M=class M extends Error{constructor(n,r,i={}){super(r);p(this,"code");p(this,"severity");p(this,"timestamp");p(this,"requestId");p(this,"context");this.name="AvesException",this.code=n,this.severity=i.severity||R.ERROR,this.timestamp=new Date().toISOString(),this.context=i.context,this.requestId=i.requestId||this.generateRequestId(),Object.setPrototypeOf(this,M.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,M)}static fromAvesError(n){return new M(n.code,n.message,{severity:n.severity,context:n.context,requestId:n.requestId})}isRetryable(){return[m.TIMEOUT,m.SERVICE_UNAVAILABLE,m.INTERNAL_SERVER_ERROR,m.RATE_LIMIT_EXCEEDED].includes(this.code)}getUserFriendlyMessage(){return{[m.INVALID_TOKEN]:"Your session has expired. Please log in again.",[m.TOKEN_EXPIRED]:"Your session has expired. Please log in again.",[m.INSUFFICIENT_PERMISSIONS]:"You do not have permission to perform this action.",[m.BOOKING_NOT_FOUND]:"The requested booking could not be found.",[m.BOOKING_ALREADY_CANCELLED]:"This booking has already been cancelled.",[m.PAYMENT_FAILED]:"Payment processing failed. Please try again.",[m.INSUFFICIENT_INVENTORY]:"The requested service is no longer available.",[m.SERVICE_UNAVAILABLE]:"The service is temporarily unavailable. Please try again later.",[m.TIMEOUT]:"The request timed out. Please try again.",[m.RATE_LIMIT_EXCEEDED]:"Too many requests. Please wait a moment and try again."}[this.code]||this.message}toJSON(){return{name:this.name,code:this.code,message:this.message,severity:this.severity,timestamp:this.timestamp,requestId:this.requestId,context:this.context,stack:this.stack,isRetryable:this.isRetryable(),userFriendlyMessage:this.getUserFriendlyMessage()}}toAvesError(){return{code:this.code,message:this.message,severity:this.severity,timestamp:this.timestamp,requestId:this.requestId,context:this.context}}getHttpStatusCode(){switch(this.code){case m.INVALID_TOKEN:case m.TOKEN_EXPIRED:return 401;case m.INSUFFICIENT_PERMISSIONS:return 403;case m.BOOKING_NOT_FOUND:return 404;case m.INVALID_REQUEST_FORMAT:case m.MISSING_REQUIRED_FIELD:case m.INVALID_FIELD_VALUE:return 400;case m.RATE_LIMIT_EXCEEDED:return 429;case m.SERVICE_UNAVAILABLE:return 503;case m.TIMEOUT:return 408;default:return 500}}getCategory(){return this.code.startsWith("AVES_1")?"Authentication":this.code.startsWith("AVES_2")?"Business Logic":this.code.startsWith("AVES_5")?"System":"Unknown"}generateRequestId(){return`aves_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}};a(M,"AvesException");var d=M;function Yt(e,t,n,r){var i=arguments.length,c=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")c=Reflect.decorate(e,t,n,r);else for(var E=e.length-1;E>=0;E--)(u=e[E])&&(c=(i<3?u(c):i>3?u(t,n,c):u(t,n))||c);return i>3&&c&&Object.defineProperty(t,n,c),c}a(Yt,"_ts_decorate");var me=class me{parseError(t){return t instanceof d?t:this.isHttpError(t)?this.parseHttpError(t):this.isAvesXmlResponse(t)?this.parseAvesXmlError(t):t instanceof Error?new d(m.INTERNAL_SERVER_ERROR,t.message,{severity:R.ERROR,context:this.buildContext({type:"javascript_error",errorName:t.name,stack:t.stack||"No stack trace available"})}):new d(m.INTERNAL_SERVER_ERROR,"Unknown error occurred",{severity:R.ERROR,context:this.buildContext({type:"unknown_error",errorName:typeof t,errorValue:String(t)})})}parseHttpError(t){if(t.response){let n=t.response.status,r=t.response.statusText;switch(n){case 400:return new d(m.INVALID_REQUEST_FORMAT,`Bad Request: ${r}`,{severity:R.ERROR,context:this.buildContext({type:"http_error",errorName:n,statusText:r,url:t.config?.url,method:t.config?.method,timeout:t.config?.timeout})});case 401:return new d(m.INVALID_TOKEN,"Authentication failed",{severity:R.ERROR,context:this.buildContext({type:"http_error",status:n,url:t.config?.url,method:t.config?.method,timeout:t.config?.timeout})});case 403:return new d(m.INSUFFICIENT_PERMISSIONS,"Access forbidden",{severity:R.ERROR,context:this.buildContext({type:"http_error",status:n,url:t.config?.url,method:t.config?.method,timeout:t.config?.timeout})});case 404:return new d(m.BOOKING_NOT_FOUND,"Resource not found",{severity:R.ERROR,context:this.buildContext({type:"http_error",status:n,url:t.config?.url,method:t.config?.method,timeout:t.config?.timeout})});case 429:return new d(m.RATE_LIMIT_EXCEEDED,"Rate limit exceeded",{severity:R.ERROR,context:this.buildContext({type:"http_error",status:n,retryAfter:t.response.headers?.["retry-after"]})});case 500:return new d(m.INTERNAL_SERVER_ERROR,"Internal server error",{severity:R.ERROR,context:this.buildContext({type:"http_error",status:n,url:t.config?.url,method:t.config?.method,timeout:t.config?.timeout})});case 503:return new d(m.SERVICE_UNAVAILABLE,"Service unavailable",{severity:R.ERROR,context:this.buildContext({type:"http_error",status:n,url:t.config?.url,method:t.config?.method,timeout:t.config?.timeout})});default:return new d(m.INTERNAL_SERVER_ERROR,`HTTP ${n}: ${r}`,{severity:R.ERROR,context:this.buildContext({type:"http_error",status:n,statusText:r,url:t.config?.url,method:t.config?.method,timeout:t.config?.timeout})})}}else return t.request?new d(m.TIMEOUT,"Request timeout - no response from AVES API",{severity:R.ERROR,context:this.buildContext({type:"http_error",timeout:!0,url:t.config?.url,method:t.config?.method,configuredTimeout:t.config?.timeout})}):new d(m.INTERNAL_SERVER_ERROR,`Request setup error: ${t.message}`,{severity:R.ERROR,context:this.buildContext({type:"http_error",setupError:!0})})}parseAvesXmlError(t){if(!t?.Response?.RsStatus)return new d(m.INVALID_REQUEST_FORMAT,"Invalid response format from AVES API",{severity:R.ERROR,context:this.buildContext({type:"aves_xml_error",missingRsStatus:!0})});let n=t.Response.RsStatus;if(n["@Status"]==="ERROR")return new d(n.ErrorCode||m.INTERNAL_SERVER_ERROR,n.ErrorDescription||"Unknown error from AVES API",{severity:R.ERROR,context:this.buildContext({type:"aves_xml_error",originalResponse:n})});if(n.Warnings?.Warning){let r=Array.isArray(n.Warnings.Warning)?n.Warnings.Warning:[n.Warnings.Warning];return new d(m.INVALID_FIELD_VALUE,r.join("; "),{severity:R.WARNING,context:this.buildContext({type:"aves_xml_warning",warnings:r})})}return new d(m.INTERNAL_SERVER_ERROR,"Unexpected response from AVES API",{severity:R.ERROR,context:this.buildContext({type:"aves_xml_error",unexpectedResponse:!0,status:n["@Status"]})})}isRetryable(t){return[m.TIMEOUT,m.SERVICE_UNAVAILABLE,m.INTERNAL_SERVER_ERROR,m.RATE_LIMIT_EXCEEDED].includes(t.code)}getUserFriendlyMessage(t){return{[m.INVALID_TOKEN]:"Your session has expired. Please log in again.",[m.TOKEN_EXPIRED]:"Your session has expired. Please log in again.",[m.INSUFFICIENT_PERMISSIONS]:"You do not have permission to perform this action.",[m.BOOKING_NOT_FOUND]:"The requested booking could not be found.",[m.BOOKING_ALREADY_CANCELLED]:"This booking has already been cancelled.",[m.PAYMENT_FAILED]:"Payment processing failed. Please try again.",[m.INSUFFICIENT_INVENTORY]:"The requested service is no longer available.",[m.SERVICE_UNAVAILABLE]:"The service is temporarily unavailable. Please try again later.",[m.TIMEOUT]:"The request timed out. Please try again.",[m.RATE_LIMIT_EXCEEDED]:"Too many requests. Please wait a moment and try again."}[t.code]||t.message}buildContext(t){let n={};return typeof t=="object"&&t!==null?Object.keys(t).forEach(r=>{let i=t[r];if(this.isSensitiveKey(r)){n[r]="********";return}this.isSerializableValue(i)?n[r]=i:typeof i=="function"?n[r]="[Function]":i instanceof Error?n[r]={name:i.name,message:i.message,stack:i.stack?.split(`
2
- `).slice(0,3).join(`
3
- `)}:n[r]=String(i)}):typeof t=="string"?n.message=t:typeof t=="number"||typeof t=="boolean"?n.value=t:n.input=String(t),n.timestamp=new Date().toISOString(),n.contextType=typeof t,n}isSensitiveKey(t){let n=["password","token","secret","key","auth","credential","xtoken","authorization","cookie","session","private"],r=t.toLowerCase();return n.some(i=>r.includes(i))}isSerializableValue(t){return t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?!0:Array.isArray(t)?t.length<=10:typeof t=="object"&&t.constructor===Object?Object.keys(t).length<=20:!1}isHttpError(t){return t&&(t.response||t.request||t.config)}isAvesXmlResponse(t){return t&&t.Response&&t.Response.RsStatus}};a(me,"AvesErrorHandler");var Q=me;Q=Yt([Qt()],Q);export{Q as AvesErrorHandler,d as AvesException,Y as AvesModule,N as AvesService,l as BookingStatusType,B as CancelReasonType,T as CustomerStatusType,C as CustomerType,j as DeliveryMethodType,G as DeliveryStatusType,w as DocumentFormatType,I as DocumentType,y as GenderType,f as PassengerType,V as PaymentStatusType,v as PaymentType,k as PricingItemType,X as RefundMethodType,P as ServiceStatusType,O as ServiceType};
1
+ import{request as ue}from"undici";import{parse as F,safeParse as he}from"valibot";import{XMLParser as X,XMLBuilder as G}from"fast-xml-parser";var Q={ignoreAttributes:!1,attributeNamePrefix:"@",parseAttributeValue:!0,parseTrueNumberOnly:!1,trimValues:!0,ignoreNameSpace:!0,removeNSPrefix:!0,parseTagValue:!0},Z={ignoreAttributes:!1,attributeNamePrefix:"@",suppressEmptyNode:!1},J=new X(Q),Y=new G(Z);function B(r){return Y.build(r)}function U(r){return J.parse(r)}import*as e from"valibot";import*as n from"valibot";var f=n.object({"@HostID":n.pipe(n.string(),n.minLength(6),n.maxLength(6)),"@Xtoken":n.string(),"@Interface":n.literal("WEB"),"@UserName":n.literal("WEB"),"@LanguageCode":n.optional(n.pipe(n.string(),n.minLength(2),n.maxLength(2)))}),ee=n.optional(n.pipe(n.string(),n.transform(r=>r.split(",")))),C=n.object({"@Status":n.union([n.literal("OK"),n.literal("ERROR"),n.literal("WARNING"),n.literal("TIMEOUT")]),ErrorCode:n.optional(n.string()),ErrorDescription:n.optional(n.string()),Warnings:ee});import*as t from"valibot";import*as g from"valibot";function te(r){return r.charAt(0).toUpperCase()+r.slice(1)}function H(r){return r.charAt(0).toLowerCase()+r.slice(1)}var ae=new Set(["recordCode","insertCriteria","currencyCode","creditLimit","c_PaymentType","c_SpecPaymentTypeCode","s_PaymentType","s_SpecPaymentTypeCode","key","value","minDate","maxDate","hostID","xtoken","interface","userName","status"]);function y(r){if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(s=>y(s));if(r instanceof Date||r instanceof RegExp||r instanceof Map||r instanceof Set||r instanceof Error)return r;let i={};for(let[s,o]of Object.entries(r)){let c=ae.has(s),l=te(s),d=c?`@${l}`:l;o&&typeof o=="object"&&!Array.isArray(o)?o instanceof Date||o instanceof RegExp||o instanceof Map||o instanceof Set||o instanceof Error?i[d]=o:i[d]=y(o):Array.isArray(o)?i[d]=o.map(v=>typeof v=="object"&&v&&!Array.isArray(v)?y(v):v):i[d]=o}return i}function T(r){if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(s=>T(s));if(r instanceof Date||r instanceof RegExp||r instanceof Map||r instanceof Set||r instanceof Error)return r;let i={};for(let[s,o]of Object.entries(r))if(s.startsWith("@")){let c=s.slice(1),l=H(c);i[l]=o}else{let c=H(s);o&&typeof o=="object"&&!Array.isArray(o)?o instanceof Date||o instanceof RegExp||o instanceof Map||o instanceof Set||o instanceof Error?i[c]=o:i[c]=T(o):Array.isArray(o)?i[c]=o.map(l=>typeof l=="object"&&l&&!Array.isArray(l)?T(l):l):i[c]=o}return i}function R(r){return g.pipe(r,g.transform(i=>y(i)))}function S(r){return g.pipe(r,g.transform(i=>T(i)))}var q=t.object({currencyCode:t.string(),creditLimit:t.optional(t.string()),c_PaymentType:t.optional(t.union([t.literal("CASH"),t.literal("BANK"),t.literal("RID"),t.literal("RIBA"),t.literal("SPECIFIC_CODE")])),c_SpecPaymentTypeCode:t.optional(t.string()),s_PaymentType:t.optional(t.union([t.literal("CASH"),t.literal("BANK"),t.literal("RID"),t.literal("RIBA"),t.literal("SPECIFIC_CODE")])),s_SpecPaymentTypeCode:t.optional(t.string())}),E=R(q),z=t.object({key:t.string(),value:t.string()}),A=R(z),k=t.object({recordCode:t.optional(t.pipe(t.string(),t.minLength(6),t.maxLength(6))),insertCriteria:t.optional(t.union([t.literal("S"),t.literal("N"),t.literal("T"),t.literal("M")])),createdDate:t.optional(t.string()),recordType:t.optional(t.union([t.literal("CUSTOMER"),t.literal("SUPPLIER")],"CUSTOMER")),recordStatus:t.optional(t.union([t.literal("ENABLED"),t.literal("DISABLED"),t.literal("WARNING"),t.literal("BLACKLISTED")],"ENABLED")),moniker:t.optional(t.string()),name:t.optional(t.string()),extraInfo:t.optional(t.string()),languageCode:t.pipe(t.string(),t.minLength(2),t.maxLength(2)),address:t.optional(t.string()),zipCode:t.optional(t.string()),cityName:t.optional(t.string()),countyCode:t.optional(t.string()),stateCode:t.optional(t.string()),categoryCode:t.optional(t.string()),firstPhoneNumber:t.optional(t.string()),mobilePhoneNumber:t.optional(t.string()),email:t.optional(t.string()),gender:t.optional(t.string()),birthDate:t.optional(t.string()),fiscalCode:t.optional(t.string()),vatCode:t.optional(t.string()),financialDetail:t.optional(q),dynamicFields:t.optional(t.array(z))}),x=R(k),re=S(x);var oe=e.object({minDate:e.string(),maxDate:e.string()}),p=e.optional(e.pipe(e.string(),e.minLength(2),e.maxLength(2))),ne=e.object({searchType:e.literal("CODE"),recordCode:e.pipe(e.string(),e.minLength(6),e.maxLength(6)),languageCode:p}),ie=e.object({searchType:e.literal("NAME"),name:e.string(),city:e.optional(e.string()),languageCode:p}),se=e.object({searchType:e.literal("VATCODE"),vatCode:e.string(),phoneNumber:e.optional(e.string()),languageCode:p}),ce=e.object({searchType:e.literal("ZONE"),zipCode:e.string(),countyCode:e.string(),city:e.optional(e.string()),languageCode:p}),le=e.object({searchType:e.literal("CATEGORY"),categoryCode:e.string(),languageCode:p}),ve=e.object({searchType:e.literal("EMAIL"),email:e.string(),languageCode:p}),pe=e.object({searchType:e.literal("LASTMODDATE"),lastModificationDate:oe,languageCode:p}),me=e.object({searchType:e.literal("SEARCH_FIELD"),searchFieldValue:e.string(),languageCode:p}),de=e.object({searchType:e.literal("EXTERNAL_REF_CODE"),searchFieldValue:e.string(),languageCode:p}),j=e.union([ne,ie,se,ce,le,ve,pe,me,de]),V=R(j),P=e.object({RqHeader:f,SearchMasterRecord:V}),K=e.object({"@RecordCode":e.optional(e.pipe(e.union([e.string(),e.number()]),e.transform(r=>String(r)),e.minLength(6),e.maxLength(6))),"@InsertCriteria":e.optional(e.union([e.literal("S"),e.literal("N"),e.literal("T"),e.literal("M")])),CreatedDate:e.optional(e.string()),RecordType:e.optional(e.union([e.literal("CUSTOMER"),e.literal("SUPPLIER")])),RecordStatus:e.optional(e.union([e.literal("ENABLED"),e.literal("DISABLED"),e.literal("WARNING"),e.literal("BLACKLISTED")],"ENABLED")),Moniker:e.optional(e.string()),Name:e.optional(e.string()),LanguageCode:e.optional(e.pipe(e.string(),e.minLength(2),e.maxLength(2))),Address:e.optional(e.string()),ZipCode:e.optional(e.string()),CityName:e.optional(e.string()),CountyCode:e.optional(e.string()),StateCode:e.optional(e.string()),CategoryCode:e.optional(e.string()),FirstPhoneNumber:e.optional(e.string()),MobilePhoneNumber:e.optional(e.string()),Email:e.optional(e.string()),Gender:e.optional(e.string()),BirthDate:e.optional(e.string()),FiscalCode:e.optional(e.string()),NewsletterDisabled:e.optional(e.union([e.literal("true"),e.literal("false"),e.boolean()])),FinancialDetail:e.optional(E),DynamicFields:e.optional(e.array(A))}),ge=e.object({MasterRecordDetail:e.optional(e.pipe(e.union([e.array(K),K]),e.transform(r=>{if(r)return Array.isArray(r)?r:[r]})))}),N=S(e.object({RsStatus:C,MasterRecordList:e.optional(ge)}));import*as a from"valibot";var Re=a.object({CustomerRecordCode:a.pipe(a.union([a.string(),a.number()]),a.transform(r=>String(r)),a.minLength(6),a.maxLength(6))}),Se=a.object({"@RecordCode":a.optional(a.pipe(a.string(),a.minLength(6),a.maxLength(6))),"@InsertCriteria":a.optional(a.union([a.literal("S"),a.literal("N"),a.literal("T"),a.literal("M")])),CreatedDate:a.optional(a.string()),RecordType:a.optional(a.union([a.literal("CUSTOMER"),a.literal("SUPPLIER")])),RecordStatus:a.optional(a.union([a.literal("ENABLED"),a.literal("DISABLED"),a.literal("WARNING"),a.literal("BLACKLISTED")],"ENABLED")),Moniker:a.optional(a.string()),Name:a.optional(a.string()),LanguageCode:a.optional(a.pipe(a.string(),a.minLength(2),a.maxLength(2))),Address:a.optional(a.string()),ZipCode:a.optional(a.string()),CityName:a.optional(a.string()),CountyCode:a.optional(a.string()),StateCode:a.optional(a.string()),CategoryCode:a.optional(a.string()),FirstPhoneNumber:a.optional(a.string()),MobilePhoneNumber:a.optional(a.string()),Email:a.optional(a.string()),Gender:a.optional(a.string()),BirthDate:a.optional(a.string()),FiscalCode:a.optional(a.string()),NewsletterDisabled:a.optional(a.union([a.literal("true"),a.literal("false"),a.boolean()])),FinancialDetail:a.optional(E),DynamicFields:a.optional(a.array(A))}),I=a.object({RqHeader:f,MasterRecordDetail:a.intersect([Se,a.object({"@InsertCriteria":a.union([a.literal("S"),a.literal("N"),a.literal("T"),a.literal("M")])})])}),b=S(a.object({RsStatus:C,CustomerRecordRS:a.optional(Re)}));function W(r,i){return{[r]:i}}var L={SEARCH_REQUEST:"SearchMasterRecordRQ",SEARCH_RESPONSE:"SearchMasterRecordRS",UPSERT_REQUEST:"ManageMasterRecordRQ",UPSERT_RESPONSE:"ManageMasterRecordRS"},m=class extends Error{constructor(s,o,c,l){super(s);this.status=o;this.errorCode=c;this.errorDescription=l;this.name="AvesError"}},O=class{constructor(i,s,o,c){this.baseURL=i;this.hostID=s;this.xtoken=o;this.languageCode=c;this.baseURL=i.replace(/\/$/,"")}createRqHeader(){return{"@HostID":this.hostID,"@Xtoken":this.xtoken,"@Interface":"WEB","@UserName":"WEB",...this.languageCode&&{"@LanguageCode":this.languageCode}}}createUrl(i){return`${this.baseURL}${i}`}get endpoints(){return{search:"/interop/masterRecords/v2/rest/Search",upsert:"/interop/masterRecords/v2/rest/InsertOrUpdate"}}async request(i,s,o,c){let l=this.createUrl(i),d=B(s),v=await ue(l,{method:"POST",headers:{"Content-Type":"application/xml"},body:d}),$=await v.body.text();if(v.statusCode!==200)throw new m($,v.statusCode.toString());let _=U($)[o];if(!_)throw new m(`Invalid response structure: missing root element '${o}'`,void 0,"VALIDATION_ERROR");let M=he(c,_);if(!M.success)throw new m(`Invalid response format: ${M.issues.map(h=>h.message).join(", ")}`,"400","VALIDATION_ERROR");let D=M.output.rsStatus,u=D?.status;if(u==="ERROR"||u==="TIMEOUT"){let h=D?.errorCode,w=D?.errorDescription;throw new m(w||`API Error: ${u}`,u,h,w)}if(u==="WARNING"){let h=D?.warnings?.join(", ");console.warn("AVES API Warning:",h)}return M.output}async search(i){let s=F(P,{RqHeader:this.createRqHeader(),SearchMasterRecord:i}),o=W(L.SEARCH_REQUEST,s);return await this.request(this.endpoints.search,o,L.SEARCH_RESPONSE,N)}async upsertRecord(i){let o={"@InsertCriteria":"T",...F(x,i)},c=F(I,{RqHeader:this.createRqHeader(),MasterRecordDetail:o}),l=W(L.UPSERT_REQUEST,c);return this.request(this.endpoints.upsert,l,L.UPSERT_RESPONSE,b)}};export{O as AvesClient,m as AvesError,E as FinancialDetailSchema,I as ManageMasterRecordRequestSchema,b as ManageMasterRecordResponseSchema,x as MasterRecordDetailApiSchema,re as MasterRecordDetailResponseSchema,k as MasterRecordDetailSchema,f as RqHeaderSchema,C as RsStatusSchema,V as SearchMasterRecordApiSchema,P as SearchMasterRecordRequestSchema,N as SearchMasterRecordResponseSchema,j as SearchMasterRecordSchema};
4
2
  //# sourceMappingURL=index.js.map