facturajs
Version:
Comunicación con los web services de AFIP utilizando nodejs.
2 lines • 15.2 kB
JavaScript
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"AfipSoap",{enumerable:true,get:function(){return AfipSoap}});var _moment=_interop_require_default(require("moment"));var _soap=_interop_require_wildcard(require("soap"));var _util=require("../util");var _ntptimesync=require("ntp-time-sync");function _array_like_to_array(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _array_with_holes(arr){if(Array.isArray(arr))return arr}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value}catch(error){reject(error);return}if(info.done){resolve(value)}else{Promise.resolve(value).then(_next,_throw)}}function _async_to_generator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(undefined)})}}function _class_call_check(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _create_class(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _define_property(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap;var cacheNodeInterop=new WeakMap;return(_getRequireWildcardCache=function(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop})(nodeInterop)}function _interop_require_wildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj}}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj)}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc)}else{newObj[key]=obj[key]}}}newObj.default=obj;if(cache){cache.set(obj,newObj)}return newObj}function _iterable_to_array_limit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break}}catch(err){_d=true;_e=err}finally{try{if(!_n&&_i["return"]!=null)_i["return"]()}finally{if(_d)throw _e}}return _arr}function _non_iterable_rest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _object_spread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};var ownKeys=Object.keys(source);if(typeof Object.getOwnPropertySymbols==="function"){ownKeys=ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym){return Object.getOwnPropertyDescriptor(source,sym).enumerable}))}ownKeys.forEach(function(key){_define_property(target,key,source[key])})}return target}function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly){symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})}keys.push.apply(keys,symbols)}return keys}function _object_spread_props(target,source){source=source!=null?source:{};if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}return target}function _sliced_to_array(arr,i){return _array_with_holes(arr)||_iterable_to_array_limit(arr,i)||_unsupported_iterable_to_array(arr,i)||_non_iterable_rest()}function _unsupported_iterable_to_array(o,minLen){if(!o)return;if(typeof o==="string")return _array_like_to_array(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(n);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _array_like_to_array(o,minLen)}function _ts_generator(thisArg,body){var f,y,t,g,_={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]};return g={next:verb(0),"throw":verb(1),"return":verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}}var AfipSoap=function(){"use strict";function AfipSoap(config){_class_call_check(this,AfipSoap);_define_property(this,"config",void 0);_define_property(this,"tokensAliasServices",void 0);_define_property(this,"urls",void 0);this.config=config;this.tokensAliasServices={wsfev1:"wsfe"};this.urls={homo:{login:"https://wsaahomo.afip.gov.ar/ws/services/LoginCms?wsdl",service:"https://wswhomo.afip.gov.ar/{name}/service.asmx?wsdl"},prod:{login:"https://wsaa.afip.gov.ar/ws/services/LoginCms?wsdl",service:"https://servicios1.afip.gov.ar/{name}/service.asmx?WSDL"}}}_create_class(AfipSoap,[{key:"getTokens",value:function getTokens(service){var _this=this;return _async_to_generator(function(){var aliasedService;return _ts_generator(this,function(_state){aliasedService=_this.tokensAliasServices[service]||service;return[2,_this.retrieveTokens(aliasedService)]})})()}},{key:"retrieveTokens",value:function retrieveTokens(service){var _this=this;return _async_to_generator(function(){var cacheTokens,fromNetwork;return _ts_generator(this,function(_state){switch(_state.label){case 0:return[4,_this.getTokensFromCache(service)];case 1:cacheTokens=_state.sent();if(cacheTokens){(0,_util.debug)(_util.LOG.INFO,"Read config from cache");return[2,cacheTokens]}return[4,_this.getTokensFromNetwork(service)];case 2:fromNetwork=_state.sent();(0,_util.debug)(_util.LOG.DEBUG,"Tokens from network:",fromNetwork);if(!fromNetwork)return[3,4];return[4,_this.saveCredentialsCache(service,fromNetwork)];case 3:_state.sent();_state.label=4;case 4:return[2,fromNetwork]}})})()}},{key:"saveCredentialsCache",value:function saveCredentialsCache(service,credential){var _this=this;return _async_to_generator(function(){var cache;return _ts_generator(this,function(_state){switch(_state.label){case 0:return[4,AfipSoap.getCredentialsCacheAll(_this.config.cacheTokensPath)];case 1:cache=_state.sent();cache[service]=credential;(0,_util.debug)(_util.LOG.INFO,"Write config to cache");return[4,(0,_util.writeFile)(_this.config.cacheTokensPath,JSON.stringify(cache))];case 2:_state.sent();return[2]}})})()}},{key:"getLoginXml",value:function getLoginXml(service,networkTime){var expire=(0,_moment.default)(networkTime).add(this.config.tokensExpireInHours,"hours");var formatDate=function(date){return(0,_moment.default)(date).format().replace("-03:00","")};var xml='\n <?xml version="1.0" encoding="UTF-8" ?>\n <loginTicketRequest version="1.0">\n <header>\n <uniqueId>'.concat((0,_moment.default)().format("X"),"</uniqueId>\n <generationTime>").concat(formatDate(networkTime),"</generationTime>\n <expirationTime>").concat(formatDate(expire),"</expirationTime>\n </header>\n <service>").concat(service,"</service>\n </loginTicketRequest>\n ");return xml.trim()}},{key:"signService",value:function signService(service){var _this=this;return _async_to_generator(function(){var date,_ref,cert,privateKey;return _ts_generator(this,function(_state){switch(_state.label){case 0:return[4,AfipSoap.getNetworkHour()];case 1:date=_state.sent();return[4,_this.getKeys()];case 2:_ref=_sliced_to_array.apply(void 0,[_state.sent(),2]),cert=_ref[0],privateKey=_ref[1];return[2,(0,_util.signMessage)(_this.getLoginXml(service,date),cert,privateKey)]}})})()}},{key:"getKeys",value:function getKeys(){var _this=this;return _async_to_generator(function(){var _tmp;return _ts_generator(this,function(_state){switch(_state.label){case 0:return[4,_this.getCert()];case 1:_tmp=[_state.sent()];return[4,_this.getPrivateKey()];case 2:return[2,_tmp.concat([_state.sent()])]}})})()}},{key:"getCert",value:function getCert(){var _this=this;return _async_to_generator(function(){return _ts_generator(this,function(_state){switch(_state.label){case 0:if(_this.config.certContents){return[2,_this.config.certContents]}if(!_this.config.certPath)return[3,2];return[4,(0,_util.readStringFromFile)(_this.config.certPath)];case 1:return[2,_state.sent()];case 2:throw new Error("Not cert")}})})()}},{key:"getPrivateKey",value:function getPrivateKey(){var _this=this;return _async_to_generator(function(){return _ts_generator(this,function(_state){switch(_state.label){case 0:if(_this.config.privateKeyContents){return[2,_this.config.privateKeyContents]}if(!_this.config.privateKeyPath)return[3,2];return[4,(0,_util.readStringFromFile)(_this.config.privateKeyPath)];case 1:return[2,_state.sent()];case 2:throw new Error("Not private key")}})})()}},{key:"getSoapClient",value:function getSoapClient(serviceName){var urls=this.urls[this.getAfipEnvironment()];var type=serviceName==="login"?"login":"service";var url=urls[type].replace("{name}",encodeURIComponent(serviceName));return _soap.createClientAsync(url,{namespaceArrayElements:false})}},{key:"getAfipEnvironment",value:function getAfipEnvironment(){return this.config.homo?"homo":"prod"}},{key:"getTokensFromNetwork",value:function getTokensFromNetwork(service){var _this=this;return _async_to_generator(function(){var _ref,signedData,client,result,loginCmsReturn,res;return _ts_generator(this,function(_state){switch(_state.label){case 0:return[4,Promise.all([_this.signService(service),_this.getSoapClient("login")])];case 1:_ref=_sliced_to_array.apply(void 0,[_state.sent(),2]),signedData=_ref[0],client=_ref[1];(0,_util.debug)(_util.LOG.INFO,"Asking tokens from network");return[4,client.loginCmsAsync({in0:signedData})];case 2:result=_state.sent();loginCmsReturn=result[0].loginCmsReturn;return[4,(0,_util.parseXml)(loginCmsReturn)];case 3:res=_state.sent();return[2,{created:(0,_moment.default)().format(),service:service,tokens:res.loginTicketResponse.credentials}]}})})()}},{key:"isExpired",value:function isExpired(expireStr){var now=(0,_moment.default)(new Date);var expire=(0,_moment.default)(expireStr);var duration=_moment.default.duration(now.diff(expire));return duration.asHours()>this.config.tokensExpireInHours}},{key:"getTokensFromCache",value:function getTokensFromCache(service){var _this=this;return _async_to_generator(function(){var cache,cacheService;return _ts_generator(this,function(_state){switch(_state.label){case 0:return[4,AfipSoap.getCredentialsCacheAll(_this.config.cacheTokensPath)];case 1:cache=_state.sent();cacheService=typeof cache[service]==="undefined"?null:cache[service];if(cacheService&&!_this.isExpired(cacheService.created)){return[2,cacheService]}return[2,null]}})})()}},{key:"execMethod",value:function execMethod(service,method,params){var _this=this;return _async_to_generator(function(){var cred,paramsWithAuth,client,call,_ref,result,rawResponse,methodResponse;return _ts_generator(this,function(_state){switch(_state.label){case 0:(0,_util.debug)(_util.LOG.INFO,"execMethod name",method);(0,_util.debug)(_util.LOG.INFO,"execMethod params",params);return[4,_this.getTokens(service)];case 1:cred=_state.sent();(0,_util.debug)(_util.LOG.INFO,"TOKENS",cred.tokens);paramsWithAuth=_object_spread({Auth:_object_spread_props(_object_spread({},params.Auth),{Token:cred.tokens.token,Sign:cred.tokens.sign})},params.params);(0,_util.debug)(_util.LOG.INFO,"execMethod params with AUTH",params);return[4,_this.getSoapClient(service)];case 2:client=_state.sent();call=client[method+"Async"];return[4,call(paramsWithAuth)];case 3:_ref=_sliced_to_array.apply(void 0,[_state.sent(),2]),result=_ref[0],rawResponse=_ref[1];(0,_util.debug)(_util.LOG.DEBUG,"execMethod rawResponse",rawResponse);methodResponse=result[method+"Result"];AfipSoap.throwOnError(methodResponse);return[2,methodResponse]}})})()}}],[{key:"getCredentialsCacheAll",value:function getCredentialsCacheAll(path){var _this=this;return _async_to_generator(function(){var raw,e;return _ts_generator(this,function(_state){switch(_state.label){case 0:_state.trys.push([0,2,,3]);return[4,(0,_util.readStringFromFile)(path)];case 1:raw=_state.sent();return[2,JSON.parse(raw)];case 2:e=_state.sent();if(_this.isErrnoException(e)&&e.code==="ENOENT"){(0,_util.debug)(_util.LOG.WARN,"Cache file does not exists.")}else{(0,_util.debug)(_util.LOG.ERROR,"Fail to read cache file: ",e)}return[2,{}];case 3:return[2]}})})()}},{key:"isErrnoException",value:function isErrnoException(e){return"code"in e}},{key:"getNetworkHour",value:function getNetworkHour(){return _async_to_generator(function(){var timeSync,res;return _ts_generator(this,function(_state){switch(_state.label){case 0:timeSync=_ntptimesync.NtpTimeSync.getInstance({servers:["time.afip.gov.ar"]});return[4,timeSync.getTime()];case 1:res=_state.sent();return[2,res.now]}})})()}},{key:"throwOnError",value:function throwOnError(response){if(!response.Errors){return}if(!response.Errors.Err){return}var resErr=response.Errors.Err[0];var err=new Error(resErr.Msg);err.name="AfipResponseError";err.code=resErr.Code;throw err}}]);return AfipSoap}();
//# sourceMappingURL=AfipSoap.js.map