UNPKG

turboself-api

Version:

A wrapper around Turboself internal API.

1 lines 13.1 kB
"use strict";var e=class{constructor(e){this.baseURL=e}async sendRequest(e){const{method:t,path:s,body:n,headers:a}=e,r=`${this.baseURL}/${s}`,i=await fetch(r,{method:t,body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...a,"User-Agent":"@raphckrman/turboself-api"}});if(!i.ok){const e=await i.json();throw new Error(`${i.status}: ${JSON.stringify(e)}`)}return await i.json()}async get(e,t){return this.sendRequest({method:"GET",path:e,headers:t})}async post(e,t,s){return this.sendRequest({method:"POST",path:e,body:t,headers:s?.headers})}async put(e,t,s){return this.sendRequest({method:"PUT",path:e,body:t,headers:s?.headers})}async delete(e,t,s){const n=new URLSearchParams(t).toString(),a=n?`${e}?${n}`:e;return this.sendRequest({method:"DELETE",path:a,headers:s?.headers})}},t=e=>`v1/historiques/hotes/${e}`,s=class{constructor(e,t,s,n,a,r){this.id=e,this.hostId=t,this.label=s,this.amount=n,this.estimatedAmount=a,this.estimatedDate=r}},n=class{constructor(e,t,s,n,a,r,i,o,l){this.id=e,this.hostId=t,this.amount=s,this.status=n,this.token=a,this.url=r,this.cancelURL=i,this.returnURL=o,this.date=l}},a=class{constructor(e,t,s,n){this.id=e,this.date=t,this.label=s,this.amount=n}},r=class{constructor(e,t,s,n,a,r,i){this.id=e,this.week=t,this.hostId=s,this.from=n,this.to=a,this.terminal=r,this.days=i}},i=class{constructor(e,t,s,n,a){this.id=e,this.localId=t,this.code=s,this.name=n,this.prices=a}},o=class{constructor(e,t,s,n,a,r,i,o,l){this.token=e,this.hostId=t,this.id=s,this.booked=n,this.canBook=a,this.dayNumber=r,this.message=i,this.reservations=o,this.date=l}async book(e=1,t=!1){return this.booked=e>0,x(this.token,this.hostId,this.id,this.date.getDay(),e,t)}};var l=class{constructor(e,t,s,n,a,r,i,o,l,h,c,u,d,m,p,f,w,g){this.id=e,this.name=t,this.currencySymbol=s,this.code=n,this.logoUrl=a,this.uai=r,this.macAddress=i,this.motd=o,this.minMealsToCredit=l,this.minDebtToCredit=h,this.minAmountToCredit=c,this.disabled=u,this.closures=d,this.location=m,this.contact=p,this.permissions=f,this.sso=w,this.synchronisation=g}},h=class{constructor(e,t,s,n,a,r,i,o,l,h,c,u,d){this.id=e,this.localId=t,this.etabId=s,this.firstName=n,this.lastName=a,this.mode=r,this.quality=i,this.division=o,this.lunchPrice=l,this.type=h,this.cardNumber=c,this.cafeteriaUrl=u,this.permissions=d}};function c(e){return void 0!==e.id}function u(e){return new l(c(e)?e.id??0:0,c(e)?e.nom||"N/A":e.nom,c(e)&&e.currencySymbol||null,c(e)?e.code2p5||null:e.code2p5,c(e)&&e.logoUrl||null,c(e)&&e.numEtab||null,c(e)&&e.pcServeur||null,c(e)?e.configuration?.msgAccueil||"":"You are not logged in so you can't see all data",c(e)?e.configuration?.nbRepasMini||0:null,c(e)?e.configuration?.creanceMini||0:null,c(e)?e.configuration?.montantCreditMini||0:null,c(e)?e.desactive||!1:null,c(e)&&e.configuration?.fermetures?.map((e=>({id:e.id,canBook:!e.rsv,canPay:!e.paiement,from:new Date(e.du),to:new Date(e.au)})))||[],c(e)?{city:e.ville,address:e.adr1+" "+e.adr2,postcode:e.cp}:{city:null,address:null,postcode:null},c(e)?{phoneNumber:e.tel||null,faxNumber:e.fax||null,email:e.configuration?.email||null,website:e.configuration?.url||null}:{phoneNumber:null,faxNumber:null,email:null,website:null},c(e)?{maxReservationsStudentMoney:e.configurationSelf?.nbmultiElvArg||null,maxReservationsStudentPackage:e.configurationSelf?.nbmultiElvFor||null,maxReservationsCommensalMoney:e.configurationSelf?.nbmultiComArg||null,maxReservationsCommensalPackage:e.configurationSelf?.nbmultiComFor||null,maxReservationsTraineeMoney:e.configurationSelf?.nbmultiStgArg||null,maxReservationsTraineePackage:e.configurationSelf?.nbmultiStgFor||null,qrCodeStudent:e.configuration?.autoriseQrCodeEleve||null,qrCodeCommensal:e.configuration?.autoriseQrCodeCommensal||null,qrCodeTrainee:e.configuration?.autoriseQrCodeStagiaire||null,hideHistory:e.configuration?.cacherHistorique||!1}:{maxReservationsStudentMoney:null,maxReservationsStudentPackage:null,maxReservationsCommensalMoney:null,maxReservationsCommensalPackage:null,maxReservationsTraineeMoney:null,maxReservationsTraineePackage:null,qrCodeStudent:null,qrCodeCommensal:null,qrCodeTrainee:null,hideHistory:null},c(e)?{id:e.configuration?.sso?.id||null,entCode:e.configuration?.sso?.entCode||null,entName:e.configuration?.sso?.entName||null,serveurCas:e.configuration?.sso?.serveurCas||null,service:e.configuration?.sso?.service||null}:{id:null,entCode:null,entName:null,serveurCas:null,service:null},c(e)?{firstSync:new Date(e.datePremSynchro||0),lastSync:new Date(e.dateDernSynchro||0)}:{firstSync:new Date(0),lastSync:new Date(0)})}function d(e){return new h(e.id,e.idOrig,e.etab.id,e.prenom,e.nom,e.mode,e.qualite,e.division,e.prixDej,e.type,e.carteCodee,e.urlCafeteria||null,{payment:e.droitPaiement||!1,reservation:e.droitReservation||!1,cafeteria:e.droitCafeteria||!1,bookWithNegativeBalance:e.autoriseReservSoldeIns,maxPassages:e.nbMulti})}var m=new e("https://api-rest-prod.incb.fr/api"),p=async(e,t)=>{const s=await m.get((e=>`v1/hotes/${e}`)(t),{Authorization:`Bearer ${e}`});return d(s)},f=async(e,t)=>{const n=await m.get((e=>`v1/comptes/hotes/${e}/3`)(t),{Authorization:`Bearer ${e}`}),a=[];for(const e of n){const t=e.montantEstimeMsg?e.montantEstimeMsg.match(/(\d{2})\/(\d{2})\/(\d{4})/)?.slice(1,4):void 0;let n=new Date;t&&(n=new Date(parseInt(t[2],10),parseInt(t[1],10)-1,parseInt(t[0],10))),a.push(new s(e.id,e.hote.id,e.appli.lib,e.montant,e.montantEstime,n))}return a},w=async(e,t,s)=>{const a=await m.post((e=>`v2/hotes/${e}/paiements/init`)(t),[{paiementPayline:{hote:{id:t}},montant:s}],{headers:{Authorization:`Bearer ${e}`}});return new n(null,t,s,"INIT",a.token,a.redirectURL,"https://espacenumerique.turbo-self.com/PagePaiementRefuse.aspx?token="+a.token,"https://espacenumerique.turbo-self.com/PagePaiementValide.aspx?token="+a.token,new Date)},g=async(e,s)=>{const n=await m.get(t(s),{Authorization:`Bearer ${e}`}),r=[];for(const e of n)r.push(new a(e.id,new Date(e.date),e.detail,(e.credit??0)-(e.debit??0)));return r},y=async(e,s,n)=>{const r=(await m.get(t(s),{Authorization:`Bearer ${e}`})).find((e=>e.id===n));if(!r)throw new Error("Event not found");return new a(r.id,new Date(r.date),r.detail,(r.credit??0)-(r.debit??0))},k=async(e,t)=>{const s=(await m.get((e=>`v2/hotes/${e}/accueil`)(t),{Authorization:`Bearer ${e}`})).latestPaiement;return new n(s.id,t,s.montant,s.statut,s.token,null,"https://espacenumerique.turbo-self.com/PagePaiementRefuse.aspx?token="+s.token,"https://espacenumerique.turbo-self.com/PagePaiementValide.aspx?token="+s.token,new Date(s.date))},b=async(e,t)=>m.get((e=>`v1/hotes/${e}/resa-soir`)(t),{Authorization:`Bearer ${e}`}),v=async(e,t,s)=>{const n=await m.get(((e,t)=>`v1/reservations/hotes/${e}/semaines${"?num="+t||""}`)(t,s),{Authorization:`Bearer ${e}`});if(!n.rsvWebDto[0])throw new Error("No booking found for this week.");const a=function(e,t){e-=2;const s=new Date(t,0,1),n=s.getDay(),a=0===n?1:8-n,r=new Date(s);r.setDate(s.getDate()+a);const i=new Date(r);i.setDate(r.getDate()+7*e);const o=new Date(i);o.setDate(i.getDate()+6),i.setHours(0,0,0,0),o.setHours(23,59,59,999);const l=6e4*i.getTimezoneOffset();return{from:new Date(i.getTime()-l),to:new Date(o.getTime()-l)}}(n.rsvWebDto[0].semaine,n.rsvWebDto[0].annee),l=[];for(const s of n.rsvWebDto){const n=[];for(const r of s.jours)n.push(new o(e,t,s.id,r.dayReserv>0,r.autorise,r.dayOfWeek,r.msg||"",r.dayReserv,new Date(a.from.getTime()+864e5*(r.dayOfWeek-1))));l.push(new r(s.id,s.semaine,s.hote.id,a.from,a.to,new i(s.borne.id,s.borne.idOrig,s.borne.code2p5,s.borne.lib,s.borne.prix.map((e=>({id:e.id,localId:e.idOrig,name:e.lib,price:e.prix})))),n))}return l},x=async(e,t,s,n,a=1,r=!1)=>{const i=await m.post((e=>`v2/hotes/${e}/reservations-jours`)(t),{dayOfWeek:n,dayReserv:a,web:{id:s},hasHoteResaSoirActive:r},{headers:{Authorization:`Bearer ${e}`}});return new o(e,t,i.id,i.dayReserv>0,!0,i.dayOfWeek,i.msg||"",i.dayReserv,new Date)},D=async(e,t)=>{const s=await m.get((e=>`v1/hotes/${e}/freres-soeurs`)(t),{Authorization:`Bearer ${e}`}),n=[];for(const e of s)n.push(d(e));return n},B=new e("https://api-rest-prod.incb.fr/api"),I=async(e,t,s,n)=>(await B.put("v1/utilisateurs/password",{id:e,password:t,newPassword:s},{headers:{Authorization:`Bearer ${n}`}})).token,P=new e("https://api-rest-prod.incb.fr/api"),$=async(e,t="",s=10,n=!1,a)=>{const r=await P.get(((e,t,s)=>`v1/etablissements?q=${e}&code2p5=${t}&limit=${s}`)(e,t,s)),i=[];if(a&&!n)for(const e of r)i.push(await R(a,e.code2p5));else for(const e of r)i.push(u(e));return i},R=async(e,t)=>{const s=await P.get((n=t,`v2/etablissements?code2p5=${n}`),{Authorization:`Bearer ${e}`});var n;if(0===s.length)throw new Error("Establishment not found");return u(s[0])},T=async(e,t)=>{var s;return u(await P.get((s=t,`v1/etablissements/etabId/${s}`),{Authorization:`Bearer ${e}`}))},C=new e("https://api-rest-prod.incb.fr/api"),S=async(e,t)=>{const s=await C.get((e=>`v1/paiements-payline/${e}`)(t),{Authorization:`Bearer ${e}`});return new n(s.id,s.hote.id,s.montant,s.statut,t,null,"https://espacenumerique.turbo-self.com/PagePaiementRefuse.aspx?token="+t,"https://espacenumerique.turbo-self.com/PagePaiementValide.aspx?token="+t,new Date(s.date))},E=new e("https://api-rest-prod.incb.fr/api"),q=async(e,t,s,n,a)=>{if(a)return new N({token:e.access_token,hostId:e.hoteId,userId:e.userId,username:t?s:null,password:t?n:null,token_expiry:Date.now()+33e5});const r=await p(e.access_token,e.hoteId),[i,o]=await Promise.all([f(e.access_token,e.hoteId),T(e.access_token,r.etabId)]);return new N({token:e.access_token,hostId:e.hoteId,userId:e.userId,username:t?s:null,password:t?n:null,token_expiry:Date.now()+33e5},o,r,i)},A=async(e,t,s=!0,n=!1,a)=>{const r=await E.post("v1/auth/login",{username:e,password:t,hoteId:a});return q(r,s,e,t,n)},N=class{constructor(e,t,s,n){this.credentials=e,this.establishment=t,this.host=s,this.balances=n}async bookMeal(e,t,s,n){return await this.refreshBearerToken(),x(this.credentials.token,this.credentials.hostId,e,t,s,n)}async canBookEvening(){return await this.refreshBearerToken(),b(this.credentials.token,this.credentials.hostId)}async editPassword(e,t){return await this.refreshBearerToken(),I(this.credentials.userId,e,t,this.credentials.token)}async getBalances(){return await this.refreshBearerToken(),f(this.credentials.token,this.credentials.hostId)}async getBookings(e){return await this.refreshBearerToken(),v(this.credentials.token,this.credentials.hostId,e)}async getEstablishment(e){await this.refreshBearerToken();const t=e||this.host?.etabId;if(!t)throw new Error("You need to provide an establishment ID to get the establishment. You can also disable the minimalist mode on authentication.");return T(this.credentials.token,t)}async getHistory(){return await this.refreshBearerToken(),g(this.credentials.token,this.credentials.hostId)}async getHistoryEvent(e){return await this.refreshBearerToken(),y(this.credentials.token,this.credentials.hostId,e)}async getHost(){return await this.refreshBearerToken(),p(this.credentials.token,this.credentials.hostId)}async getLastPayment(){return await this.refreshBearerToken(),k(this.credentials.token,this.credentials.hostId)}async getPayment(e){return await this.refreshBearerToken(),S(this.credentials.token,e)}async getSiblings(){return await this.refreshBearerToken(),D(this.credentials.token,this.credentials.hostId)}async initPayment(e){return await this.refreshBearerToken(),w(this.credentials.token,this.credentials.hostId,e)}async refreshBearerToken(e=!1){if(!e&&this.credentials.token_expiry>Date.now())return!1;if(!this.credentials.password||!this.credentials.username)throw new Error("You need to provide a username and password to refresh the bearer token.");const t=await A(this.credentials.username,this.credentials.password,!0,!1);return this.credentials=t.credentials,!0}async searchEstablishments(e,t="",s=10,n=!1){return await this.refreshBearerToken(),$(e,t,s,n,this.credentials.token)}};exports.Balance=s,exports.Booking=r,exports.BookingDay=o,exports.Client=N,exports.Establishment=l,exports.HistoryEvent=a,exports.Host=h,exports.Payment=n,exports.Terminal=i,exports.authenticateWithCredentials=A,exports.authenticateWithTicket=async(e,t,s=!0,n=!1)=>{const a=(await fetch(`https://espacenumerique.turbo-self.com/Connexion.aspx?ent=${e}&ticket=${t}`)).headers.get("set-cookie"),r=a?.split(";")[0].split("=")[1]??"",i=a?.split(";")[0].split("=")[1]??"",o=await E.post("v1/auth/login",{username:r,password:i});return q(o,s,r,i,n)},exports.bookMeal=x,exports.canBookEvening=b,exports.editPassword=I,exports.getBalances=f,exports.getBookings=v,exports.getEstablishment=T,exports.getEstablishmentBy2P5=R,exports.getHistory=g,exports.getHistoryEvent=y,exports.getHost=p,exports.getHostSiblings=D,exports.getLastPayment=k,exports.getPayment=S,exports.initPayment=w,exports.requestPasswordReset=async e=>{const t=await B.get((e=>`v1/utilisateurs/password?email=${e}`)(e));if(0!==t.rejected.length)throw new Error(`Failed to send password reset email to ${t.rejected.join(", ")}`);return!0},exports.searchEstablishments=$;//# sourceMappingURL=index.js.map