@flumens/models 0.12.0 → 0.12.1

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.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("@flumens/utils"),i=require("./Model.js"),n=function(){function n(t){var n=t.id,o=t.cid,a=t.data,d=void 0===a?[]:a,s=t.store,u=t.Model,p=void 0===u?i.default:u,h=this;this.ready=new r.Deferred,this.data=e.observable.array(d),this.id=this.id||n,this.cid=this.cid||o||n||r.UUIDv7(),this.Model=p,this.store=this.store||s,this.cidMap=new Map,this.idMap=new Map;e.intercept(this.data,(function(t){if(t.added&&t.added.length){t.added.forEach((function(t){h.cidMap.set(t.cid,t),h.idMap.set(t.id,t)}))}if(t.removedCount>0){var e=Array.from(h.cidMap.keys())[t.index];h.cidMap.delete(e),e=Array.from(h.idMap.keys())[t.index],h.idMap.delete(e)}return t}))}return n.prototype.fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r,i,n,o=this;return t.__generator(this,(function(t){switch(t.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return e=t.sent(),r=function(t){return new o.Model(t)},i=e.map(r),(n=this.data).push.apply(n,i),this.ready.resolve(!0),[2]}}))}))},n.prototype.reset=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return this.data.length?[4,null==(e=this.data.pop())?void 0:e.destroy()]:[3,2];case 1:return t.sent(),[3,0];case 2:return[2]}}))}))},n.prototype.filter=function(t){return this.data.filter(t)},n.prototype.push=function(){for(var t,e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return(t=this.data).push.apply(t,e)},n.prototype.pop=function(){return this.data.pop()},n.prototype.find=function(t){return this.data.find(t)},n.prototype.map=function(t){return this.data.map(t)},n.prototype.remove=function(t){return this.data.remove(t)},n.prototype[Symbol.iterator]=function(){return this.data[Symbol.iterator]()},Object.defineProperty(n.prototype,"length",{get:function(){return this.data.length},enumerable:!1,configurable:!0}),n}();exports.default=n;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),i=require("@flumens/utils"),r=require("./Model.js");class d{constructor({id:t,cid:d,data:s=[],store:a,Model:o=r.default}){this.ready=new i.Deferred,this.data=e.observable.array(s),this.id=this.id||t,this.cid=this.cid||d||t||i.UUIDv7(),this.Model=o,this.store=this.store||a,this.cidMap=new Map,this.idMap=new Map;e.intercept(this.data,(t=>{if(t.added&&t.added.length){const e=t=>{this.cidMap.set(t.cid,t),this.idMap.set(t.id,t)};t.added.forEach(e)}if(t.removedCount>0){let e=Array.from(this.cidMap.keys())[t.index];this.cidMap.delete(e),e=Array.from(this.idMap.keys())[t.index],this.idMap.delete(e)}return t}))}fetch(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.store||!this.Model)return void this.ready.resolve(!1);const t=(yield this.store.findAll()).map((t=>new this.Model(t)));this.data.push(...t),this.ready.resolve(!0)}))}reset(){return t.__awaiter(this,void 0,void 0,(function*(){for(;this.data.length;){const t=this.data.pop();yield null==t?void 0:t.destroy()}}))}filter(t){return this.data.filter(t)}push(...t){return this.data.push(...t)}pop(){return this.data.pop()}find(t){return this.data.find(t)}map(t){return this.data.map(t)}remove(t){return this.data.remove(t)}[Symbol.iterator](){return this.data[Symbol.iterator]()}get length(){return this.data.length}}exports.default=d;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("zod"),n=require("@flumens/utils"),i=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=a(t);function c(e){var t={};return Object.keys(e).forEach((function(r){if(r.match(/^field_/)){var s=r.replace("field_","").replace(/_([a-z])/g,(function(e){return e[1].toUpperCase()}));if(!e[r])return;if(Array.isArray(e[r])&&e[r].length)return void(t[s]=e[r][0].value);t[s]=e[r]}})),t}var u=function(e){var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new n.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new n.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new n.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new n.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new n.HandledError("The user has not been activated or is blocked.");throw new Error(e.response.data.message)}if(null===(t=e.message)||void 0===t?void 0:t.includes("timeout"))throw new n.HandledError("Timeout");throw e},d=6e4;var h={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1},l=function(t){function n(r){var s=this,n=r.config,i=e.__rest(r,["config"]);return(s=t.call(this,e.__assign(e.__assign({},i),{data:e.__assign(e.__assign({},h),i.data)}))||this).config=n,s}return e.__extends(n,t),n.prototype.logIn=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this._exchangePasswordToTokens(t,r)];case 1:return s=e.sent(),this.data.tokens=s,[4,this.refreshProfile()];case 2:return e.sent(),[2,this.save()]}}))}))},n.prototype.register=function(t,r,s){return e.__awaiter(this,void 0,void 0,(function(){var i,a,h,l,f;return e.__generator(this,(function(_){switch(_.label){case 0:return i=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),a={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:i,timeout:d},[4,o.default(a).catch(u)];case 1:if(h=_.sent().data,!!n.registerSchemaBackend.safeParse(h).error)throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 2:return l=_.sent(),this.id=h.uid[0].value,f=c(h),Object.assign(this.data,e.__assign({email:t,tokens:l,profileFetched:!0},f)),[2,this.save()]}}))}))},n.prototype.resetPassword=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,n;return e.__generator(this,(function(e){switch(e.label){case 0:r=JSON.stringify({mail:t}),s={method:"post",url:"".concat(this.config.url,"/user/password?_format=json"),headers:{"content-type":"application/json"},data:r},e.label=1;case 1:return e.trys.push([1,3,,6]),[4,o.default(s).catch(u)];case 2:return e.sent(),[3,6];case 3:return"The user has not been activated or is blocked."!==(n=e.sent()).message?[3,5]:[4,this._sendVerificationEmail(t)];case 4:return e.sent(),[2];case 5:return u(n),[3,6];case 6:return[2]}}))}))},n.prototype.delete=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),r={method:"delete",url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)}},[4,o.default(r).catch(u)];case 2:return e.sent(),this.logOut(),[2]}}))}))},n.prototype.updateRemote=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken()];case 1:return r=e.sent(),s={method:"patch",url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),data:t,headers:{Authorization:"Bearer ".concat(r)},timeout:d},[4,o.default(s)];case 2:return e.sent(),[4,this._refreshAccessToken()];case 3:return e.sent(),this.save(),[2]}}))}))},n.prototype.refreshProfile=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,r,s,n;return e.__generator(this,(function(i){switch(i.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=i.sent(),this.data.verified?(r={url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)},timeout:d},[4,o.default(r).catch(u)]):[3,3];case 2:s=i.sent().data,n=c(s),Object.assign(this.data,e.__assign({email:s.mail[0].value,profileFetched:!0},n)),i.label=3;case 3:return[4,this.save()];case 4:return i.sent(),delete this._refreshingProfilePromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingProfilePromise,e}))),[2,this._refreshingProfilePromise]}))}))},n.prototype.hasLogIn=function(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()},n.prototype.isLoggedIn=function(){return this.data.email,!!this.id},n.prototype.logOut=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.reset()]}))}))},n.prototype.reset=function(r){return t.prototype.reset.call(this,e.__assign(e.__assign({},h),r))},n.prototype.getAccessToken=function(t){return e.__awaiter(this,void 0,void 0,(function(){var s,n,i,a,o;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");if(s=(this.data.tokens||{}).access_token,n=function(e){if(!e)return!0;var t=1e3*r.jwtDecode(e).exp;return Date.now()+12e4>t}(s),!(!s||n||t))return[3,6];e.label=1;case 1:return e.trys.push([1,3,,6]),[4,this._refreshAccessToken()];case 2:return e.sent(),[3,6];case 3:return i=e.sent(),console.error(i),a="The refresh token is invalid."===i.message,o="Token has no user email."===i.message,a||o?[4,this.logOut()]:[3,5];case 4:throw e.sent(),new Error("User re-login is required.");case 5:throw i;case 6:return[2,this.data.tokens.access_token]}}))}))},n.prototype._sendVerificationEmail=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s;return e.__generator(this,(function(e){return r=JSON.stringify({mail:[{value:t||this.data.email}]}),s={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json&resendVerificationEmail=true"),headers:{"content-type":"application/json"},data:r,timeout:d},[2,o.default(s).catch(u)]}))}))},n.prototype._exchangePasswordToTokens=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s,n,i;return e.__generator(this,(function(e){switch(e.label){case 0:return(s=new FormData).append("grant_type","password"),s.append("username",t),s.append("password",r),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),(null===(i=this.config.scopes)||void 0===i?void 0:i.length)&&s.append("scope",this.config.scopes.join(" ")),n={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s},[4,o.default(n).catch(u)];case 1:return[2,e.sent().data]}}))}))},n.prototype._refreshAccessToken=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(s){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,s,n,i,a,h,l,f,_,g,p,m;return e.__generator(this,(function(v){switch(v.label){case 0:if(!(t=(this.data.tokens||{}).refresh_token))throw new Error("No user session refresh token was found");return(s=new FormData).append("grant_type","refresh_token"),s.append("refresh_token",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),n={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s,timeout:d},[4,o.default(n).catch(u)];case 1:if(i=v.sent().data,a=e.__assign(e.__assign({},this.data.tokens),i),h=r.jwtDecode(a.access_token),!(l=h.email))throw new Error("Token has no user email.");return f=h.iss,_=h.email_verified,g=h["http://indicia.org.uk/user:id"],p=h.scopes,m=c(h),this.id=h.sub,Object.assign(this.data,e.__assign({email:l,roles:p,verified:_,iss:f,indiciaUserId:g,tokens:a},m)),[4,this.save()];case 2:return v.sent(),delete this._refreshingTokenPromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingTokenPromise,e}))),[2,this._refreshingTokenPromise]}))}))},n.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),n.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),n.resetSchema=s.object({email:s.z.string().email("Please fill in")}),n.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),n.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),n}(i.default);exports.default=l;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),i=require("jwt-decode"),s=require("zod"),r=require("@flumens/utils"),a=require("../Model.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(t);function d(e){const t={};return Object.keys(e).forEach((i=>{if(i.match(/^field_/)){const s=i.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[i])return;if(Array.isArray(e[i])&&e[i].length)return void(t[s]=e[i][0].value);t[s]=e[i]}})),t}const c=e=>{var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new r.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new r.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new r.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new r.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new r.HandledError("The user has not been activated or is blocked.");throw new Error(e.response.data.message)}if(null===(t=e.message)||void 0===t?void 0:t.includes("timeout"))throw new r.HandledError("Timeout");throw e},l=6e4;const h={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1};class u extends a.default{constructor(t){var{config:i}=t,s=e.__rest(t,["config"]);super(Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},h),s.data)})),this.config=i}logIn(t,i){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._exchangePasswordToTokens(t,i);return this.data.tokens=e,yield this.refreshProfile(),this.save()}))}register(t,i,s){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify(Object.assign({name:[{value:t}],pass:[{value:i}],mail:[{value:t}]},s)),r={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:e,timeout:l},{data:a}=yield n.default(r).catch(c);if(!!u.registerSchemaBackend.safeParse(a).error)throw new Error("Invalid backend response.");const o=yield this._exchangePasswordToTokens(t,i);this.id=a.uid[0].value;const h=d(a);return Object.assign(this.data,Object.assign({email:t,tokens:o,profileFetched:!0},h)),this.save()}))}resetPassword(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:t}),i={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:e};try{yield n.default(i).catch(c)}catch(e){if("The user has not been activated or is blocked."===e.message)return void(yield this._sendVerificationEmail(t));c(e)}}))}delete(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),t={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield n.default(t).catch(c),this.logOut()}))}updateRemote(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(),i={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:t,headers:{Authorization:`Bearer ${e}`},timeout:l};yield n.default(i),yield this._refreshAccessToken(),this.save()}))}refreshProfile(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0);if(this.data.verified){const t={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:l},{data:i}=yield n.default(t).catch(c),s=d(i);Object.assign(this.data,Object.assign({email:i.mail[0].value,profileFetched:!0},s))}yield this.save(),delete this._refreshingProfilePromise})))).catch((e=>{throw delete this._refreshingProfilePromise,e}))),this._refreshingProfilePromise}))}hasLogIn(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()}isLoggedIn(){return this.data.email,!!this.id}logOut(){return e.__awaiter(this,void 0,void 0,(function*(){return this.reset()}))}reset(e){return super.reset(Object.assign(Object.assign({},h),e))}getAccessToken(t){return e.__awaiter(this,void 0,void 0,(function*(){if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");const{access_token:e}=this.data.tokens||{},s=function(e){if(!e)return!0;const{exp:t}=i.jwtDecode(e),s=1e3*t;return Date.now()+12e4>s}(e);if(!e||s||t)try{yield this._refreshAccessToken()}catch(e){console.error(e);const t="The refresh token is invalid."===e.message,i="Token has no user email."===e.message;if(t||i)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(t){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:[{value:t||this.data.email}]}),i={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:e,timeout:l};return n.default(i).catch(c)}))}_exchangePasswordToTokens(t,i){return e.__awaiter(this,void 0,void 0,(function*(){var e;const s=new FormData;s.append("grant_type","password"),s.append("username",t),s.append("password",i),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),(null===(e=this.config.scopes)||void 0===e?void 0:e.length)&&s.append("scope",this.config.scopes.join(" "));const r={method:"post",url:`${this.config.url}/oauth/token`,data:s},{data:a}=yield n.default(r).catch(c);return a}))}_refreshAccessToken(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const{refresh_token:e}=this.data.tokens||{};if(!e)throw new Error("No user session refresh token was found");const t=new FormData;t.append("grant_type","refresh_token"),t.append("refresh_token",e),t.append("client_id",this.config.clientId),this.config.clientPass&&t.append("client_secret",this.config.clientPass);const s={method:"post",url:`${this.config.url}/oauth/token`,data:t,timeout:l},{data:r}=yield n.default(s).catch(c),a=Object.assign(Object.assign({},this.data.tokens),r),o=i.jwtDecode(a.access_token),{email:h}=o;if(!h)throw new Error("Token has no user email.");const{iss:u,email_verified:f}=o,g=o["http://indicia.org.uk/user:id"],m=o.scopes,p=d(o);this.id=o.sub,Object.assign(this.data,Object.assign({email:h,roles:m,verified:f,iss:u,indiciaUserId:g,tokens:a},p)),yield this.save(),delete this._refreshingTokenPromise})))).catch((e=>{throw delete this._refreshingTokenPromise,e}))),this._refreshingTokenPromise}))}}u.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),u.resetSchema=s.object({email:s.z.string().email("Please fill in")}),u.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),exports.default=u;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=t(require("axios"));exports.fetchElasticOccurrences=function(t){return e.__awaiter(this,arguments,void 0,(function(t){var n,a,i,o,s,c,u,d,_,l,v=t.parentId,p=t.url,f=t.accessToken;return e.__generator(this,(function(t){switch(t.label){case 0:return n={terms:{"event.parent_event_id":Array.isArray(v)?v:[v]}},a={terms:{"event.event_id":Array.isArray(v)?v:[v]}},i=JSON.stringify({size:5e3,query:{bool:{must:[{bool:{should:[n,a]}}]}},_source:["id","event.event_id","event.parent_event_id","metadata.created_on","metadata.updated_on","identification","occurrence.occurrence_remarks","occurrence.attributes","occurrence.media","taxon.species","taxon.taxon_name","taxon.taxa_taxon_list_id"]}),o={Authorization:"Bearer ".concat(f)},s={method:"post",url:"".concat(p,"/index.php/services/rest/es-occurrences/_search"),headers:e.__assign({"Content-Type":"application/json"},o),data:i},[4,r.default.request(s)];case 1:return c=t.sent(),u=function(e){return e._source},[2,(null===(l=null===(_=null===(d=c.data)||void 0===d?void 0:d.hits)||void 0===_?void 0:_.hits)||void 0===l?void 0:l.map(u))||[]]}}))}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=t(require("axios"));exports.fetchElasticOccurrences=function(t){return e.__awaiter(this,arguments,void 0,(function*({parentId:e,url:t,accessToken:a}){var n,i,o;const s={terms:{"event.parent_event_id":Array.isArray(e)?e:[e]}},c={terms:{"event.event_id":Array.isArray(e)?e:[e]}},u=JSON.stringify({size:5e3,query:{bool:{must:[{bool:{should:[s,c]}}]}},_source:["id","event.event_id","event.parent_event_id","metadata.created_on","metadata.updated_on","identification","occurrence.occurrence_remarks","occurrence.attributes","occurrence.media","taxon.species","taxon.taxon_name","taxon.taxa_taxon_list_id"]}),d={Authorization:`Bearer ${a}`},l={method:"post",url:`${t}/index.php/services/rest/es-occurrences/_search`,headers:Object.assign({"Content-Type":"application/json"},d),data:u};return(null===(o=null===(i=null===(n=(yield r.default.request(l)).data)||void 0===n?void 0:n.hits)||void 0===i?void 0:i.hits)||void 0===o?void 0:o.map((e=>e._source)))||[]}))};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=t(require("axios"));exports.fetchElasticSample=function(t){return e.__awaiter(this,arguments,void 0,(function(t){var r,n,i,o,s,u,c,d,l,v,_=t.id,p=t.cid,m=t.url,h=t.accessToken;return e.__generator(this,(function(t){switch(t.label){case 0:return r=JSON.stringify({size:1e3,query:{bool:{must:[{match:{id:_}}]}}}),_||(r=JSON.stringify({size:1e3,query:{bool:{must:[{match:{"event.source_system_key":p}}]}}})),n={Authorization:"Bearer ".concat(h)},i={method:"post",url:"".concat(m,"/index.php/services/rest/es-samples/_search"),headers:e.__assign({"Content-Type":"application/json"},n),data:r},[4,a.default.request(i)];case 1:if(o=t.sent(),s=function(e){return e._source},u=(null===(v=null===(l=null===(d=o.data)||void 0===d?void 0:d.hits)||void 0===l?void 0:l.hits)||void 0===v?void 0:v.map(s))||[],!(c=u[0]))throw new Error("Remote sample with id ".concat(_||p," was not found"));return[2,c]}}))}))},exports.fetchElasticSubSamples=function(t){return e.__awaiter(this,arguments,void 0,(function(t){var r,n,i,o,s,u,c,d,l=t.parentId,v=t.url,_=t.accessToken;return e.__generator(this,(function(t){switch(t.label){case 0:return r=JSON.stringify({size:2e3,query:{bool:{must:[{terms:{"event.parent_event_id":Array.isArray(l)?l:[l]}}]}},_source:["id","event.event_id","event.parent_event_id","event.source_system_key","event.attributes","event.media","event.event_remarks","event.date_start","metadata.created_on","metadata.updated_on","metadata.survey.id","metadata.group.id","metadata.trial","location.geom","location.output_sref_system","location.output_sref","location.point","location.code","location.name","location.verbatim_locality"]}),n={Authorization:"Bearer ".concat(_)},i={method:"post",url:"".concat(v,"/index.php/services/rest/es-samples/_search"),headers:e.__assign({"Content-Type":"application/json"},n),data:r},[4,a.default.request(i)];case 1:return o=t.sent(),s=function(e){return e._source},[2,(null===(d=null===(c=null===(u=o.data)||void 0===u?void 0:u.hits)||void 0===c?void 0:c.hits)||void 0===d?void 0:d.map(s))||[]]}}))}))};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=t(require("axios"));exports.fetchElasticSample=function(t){return e.__awaiter(this,arguments,void 0,(function*({id:e,cid:t,url:i,accessToken:o}){var r,s,n;let d=JSON.stringify({size:1e3,query:{bool:{must:[{match:{id:e}}]}}});e||(d=JSON.stringify({size:1e3,query:{bool:{must:[{match:{"event.source_system_key":t}}]}}}));const u={Authorization:`Bearer ${o}`},l={method:"post",url:`${i}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},u),data:d},c=((null===(n=null===(s=null===(r=(yield a.default.request(l)).data)||void 0===r?void 0:r.hits)||void 0===s?void 0:s.hits)||void 0===n?void 0:n.map((e=>e._source)))||[])[0];if(!c)throw new Error(`Remote sample with id ${e||t} was not found`);return c}))},exports.fetchElasticSubSamples=function(t){return e.__awaiter(this,arguments,void 0,(function*({parentId:e,url:t,accessToken:i}){var o,r,s;const n=JSON.stringify({size:2e3,query:{bool:{must:[{terms:{"event.parent_event_id":Array.isArray(e)?e:[e]}}]}},_source:["id","event.event_id","event.parent_event_id","event.source_system_key","event.attributes","event.media","event.event_remarks","event.date_start","metadata.created_on","metadata.updated_on","metadata.survey.id","metadata.group.id","metadata.trial","location.geom","location.output_sref_system","location.output_sref","location.point","location.code","location.name","location.verbatim_locality"]}),d={Authorization:`Bearer ${i}`},u={method:"post",url:`${t}/index.php/services/rest/es-samples/_search`,headers:Object.assign({"Content-Type":"application/json"},d),data:n};return(null===(s=null===(r=null===(o=(yield a.default.request(u)).data)||void 0===o?void 0:o.hits)||void 0===r?void 0:r.hits)||void 0===s?void 0:s.map((e=>e._source)))||[]}))};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),n=require("zod"),o=require("@flumens/utils/dist/errors"),i=require("@flumens/utils/dist/uuid"),s=require("../Model.js"),a=require("./helpers.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=l(r),c=n.object({id:n.z.string(),title:n.z.string(),createdOn:n.z.string(),description:n.z.string().nullable().optional(),groupType:n.z.string().nullable().optional(),joiningMethod:n.z.enum(["P","R","A","I"]).nullable().optional(),websiteId:n.z.string().nullable().optional(),groupTypeId:n.z.string().nullable().optional(),createdById:n.z.string().nullable().optional(),fromDate:n.z.string().nullable().optional(),toDate:n.z.string().nullable().optional(),indexedLocationIds:n.z.array(n.z.number()).nullable().optional(),userIsAdministrator:n.z.enum(["t","f"]).nullable().optional(),userIsMember:n.z.enum(["t","f"]).nullable().optional(),userIsPending:n.z.enum(["t","f"]).nullable().optional()}),d=n.object({id:n.z.string().nullable().optional(),createdOn:n.z.string().nullable().optional(),createdById:n.z.string().nullable().optional(),groupId:n.z.string().nullable().optional(),groupTitle:n.z.string().nullable().optional(),locationId:n.z.string(),locationName:n.z.string(),locationBoundaryGeom:n.z.string(),locationLat:n.z.string(),locationLon:n.z.string(),locationCreatedOn:n.z.string(),locationUpdatedOn:n.z.string(),locationCentroidSref:n.z.string(),locationCentroidSrefSystem:n.z.string(),locationCode:n.z.string().nullable().optional(),locationCreatedById:n.z.string().nullable().optional(),locationUpdatedById:n.z.string().nullable().optional(),locationComment:n.z.string().nullable().optional(),locationExternalKey:n.z.string().nullable().optional()}),p=function(r){function n(n){var o=this,i=n.skipStore,s=n.store,a=n.url,l=n.getAccessToken,u=n.getIndiciaUserId,c=e.__rest(n,["skipStore","store","url","getAccessToken","getIndiciaUserId"]);return(o=r.call(this,e.__assign(e.__assign({},c),{store:i?void 0:s}))||this).remote=t.observable({synchronising:!1,url:a,getAccessToken:l,getIndiciaUserId:u}),o}return e.__extends(n,r),n.fromDTO=function(t,r){void 0===r&&(r={}),c.parse(t);var n=t.id,o=t.createdOn,s=e.__rest(t,["id","createdOn"]);return new this(e.__assign({id:n,cid:i.UUIDv7(),data:s,createdAt:new Date(o).getTime()},r))},n.prototype.join=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,i,s,a;return e.__generator(this,(function(e){switch(e.label){case 0:return t="".concat(this.remote.url,"/index.php/services/rest/groups/").concat(this.id,"/users"),[4,this.remote.getAccessToken()];case 1:return r=e.sent(),[4,this.remote.getIndiciaUserId()];case 2:n=e.sent(),i={values:{id:n}},s={headers:{Authorization:"Bearer ".concat(r)},timeout:8e4},e.label=3;case 3:return e.trys.push([3,5,,6]),[4,u.default.post(t,i,s)];case 4:return e.sent(),[3,6];case 5:if(a=e.sent(),u.default.isCancel(a))return[2];if(o.isAxiosNetworkError(a))throw new o.HandledError("Request aborted because of a network issue (timeout or similar).");throw a;case 6:return[2]}}))}))},n.prototype.leave=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,i,s,a,l,c;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.remote.getIndiciaUserId()];case 1:return t=e.sent(),r="".concat(this.remote.url,"/index.php/services/rest/groups/").concat(this.id,"/users/").concat(t),[4,this.remote.getAccessToken()];case 2:n=e.sent(),i={headers:{Authorization:"Bearer ".concat(n)},timeout:8e4},e.label=3;case 3:return e.trys.push([3,5,,6]),[4,u.default.delete(r,i)];case 4:return e.sent(),[3,6];case 5:if(s=e.sent(),u.default.isCancel(s))return[2];if(o.isAxiosNetworkError(s))throw new o.HandledError("Request aborted because of a network issue (timeout or similar).");if(null===(c=null===(l=null===(a=s.response)||void 0===a?void 0:a.data)||void 0===l?void 0:l.message)||void 0===c?void 0:c.includes("User is not a member of the group"))return[2];throw s;case 6:return[2]}}))}))},n.prototype.addRemoteLocation=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,n,o,i,s,a,l,c,d,p,g;return e.__generator(this,(function(e){switch(e.label){case 0:console.log("Group location uploading"),r={values:{id:t}},n="".concat(this.remote.url,"/index.php/services/rest/groups/").concat(this.id,"/locations"),e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this.remote.getAccessToken()];case 2:return o=e.sent(),i={url:n,method:"post",headers:{Authorization:"Bearer ".concat(o)},timeout:8e4,data:r},[4,u.default(i)];case 3:return e.sent(),this.remote.synchronising=!1,console.log("Group location uploading done"),[2,this];case 4:if(s=e.sent(),this.remote.synchronising=!1,409===(null===(d=(a=s).response)||void 0===d?void 0:d.status))return console.log("Location uploading duplicate was found"),[2,this];if(!(l=null===(g=null===(p=a.response)||void 0===p?void 0:p.data)||void 0===g?void 0:g.message))throw s;if("object"==typeof l)throw c=function(e){return Object.entries(e).reduce((function(e,t){return"".concat(e).concat(t[0]," ").concat(t[1],"\n")}),"")},new Error(c(l));throw new Error(l);case 5:return[2]}}))}))},n.prototype.fetchRemoteLocations=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,i,s,l,c;return e.__generator(this,(function(e){switch(e.label){case 0:return t="".concat(this.remote.url,"/index.php/services/rest/groups/").concat(this.id,"/locations"),[4,this.remote.getAccessToken()];case 1:r=e.sent(),n={headers:{Authorization:"Bearer ".concat(r)},timeout:8e4},e.label=2;case 2:return e.trys.push([2,4,,5]),[4,u.default.get(t,n)];case 3:return i=e.sent(),s=function(e){var t=e.values;return a.getCamelCaseObj(t)},(l=i.data.map(s)).forEach((function(e){return d.parse(e)})),[2,l];case 4:if(c=e.sent(),u.default.isCancel(c))return[2,[]];if(o.isAxiosNetworkError(c))throw new o.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in c)throw new Error(c.issues.map((function(e){return"".concat(e.path.join(" ")," ").concat(e.message)})).join(" "));throw c;case 5:return[2]}}))}))},n}(s.default);exports.default=p,exports.dtoSchema=c;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),o=require("axios"),i=require("zod"),r=require("@flumens/utils/dist/errors"),n=require("@flumens/utils/dist/uuid"),s=require("../Model.js"),a=require("./helpers.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=l(o);const u=i.object({id:i.z.string(),title:i.z.string(),createdOn:i.z.string(),description:i.z.string().nullable().optional(),groupType:i.z.string().nullable().optional(),joiningMethod:i.z.enum(["P","R","A","I"]).nullable().optional(),websiteId:i.z.string().nullable().optional(),groupTypeId:i.z.string().nullable().optional(),createdById:i.z.string().nullable().optional(),fromDate:i.z.string().nullable().optional(),toDate:i.z.string().nullable().optional(),indexedLocationIds:i.z.array(i.z.number()).nullable().optional(),userIsAdministrator:i.z.enum(["t","f"]).nullable().optional(),userIsMember:i.z.enum(["t","f"]).nullable().optional(),userIsPending:i.z.enum(["t","f"]).nullable().optional()}),c=i.object({id:i.z.string().nullable().optional(),createdOn:i.z.string().nullable().optional(),createdById:i.z.string().nullable().optional(),groupId:i.z.string().nullable().optional(),groupTitle:i.z.string().nullable().optional(),locationId:i.z.string(),locationName:i.z.string(),locationBoundaryGeom:i.z.string(),locationLat:i.z.string(),locationLon:i.z.string(),locationCreatedOn:i.z.string(),locationUpdatedOn:i.z.string(),locationCentroidSref:i.z.string(),locationCentroidSrefSystem:i.z.string(),locationCode:i.z.string().nullable().optional(),locationCreatedById:i.z.string().nullable().optional(),locationUpdatedById:i.z.string().nullable().optional(),locationComment:i.z.string().nullable().optional(),locationExternalKey:i.z.string().nullable().optional()});class g extends s.default{static fromDTO(t,o={}){u.parse(t);const{id:i,createdOn:r}=t,s=e.__rest(t,["id","createdOn"]);return new this(Object.assign({id:i,cid:n.UUIDv7(),data:s,createdAt:new Date(r).getTime()},o))}constructor(o){var{skipStore:i,store:r,url:n,getAccessToken:s,getIndiciaUserId:a}=o,l=e.__rest(o,["skipStore","store","url","getAccessToken","getIndiciaUserId"]);super(Object.assign(Object.assign({},l),{store:i?void 0:r})),this.remote=t.observable({synchronising:!1,url:n,getAccessToken:s,getIndiciaUserId:a})}join(){return e.__awaiter(this,void 0,void 0,(function*(){const e=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users`,t=yield this.remote.getAccessToken(),o={values:{id:yield this.remote.getIndiciaUserId()}},i={headers:{Authorization:`Bearer ${t}`},timeout:8e4};try{yield d.default.post(e,o,i)}catch(e){if(d.default.isCancel(e))return;if(r.isAxiosNetworkError(e))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");throw e}}))}leave(){return e.__awaiter(this,void 0,void 0,(function*(){var e,t,o;const i=yield this.remote.getIndiciaUserId(),n=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users/${i}`,s={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{yield d.default.delete(n,s)}catch(i){if(d.default.isCancel(i))return;if(r.isAxiosNetworkError(i))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");if(null===(o=null===(t=null===(e=i.response)||void 0===e?void 0:e.data)||void 0===t?void 0:t.message)||void 0===o?void 0:o.includes("User is not a member of the group"))return;throw i}}))}addRemoteLocation(t){return e.__awaiter(this,void 0,void 0,(function*(){var e,o,i;console.log("Group location uploading");const r={values:{id:t}},n=`${this.remote.url}/index.php/services/rest/groups/${this.id}/locations`;try{this.remote.synchronising=!0;const e={url:n,method:"post",headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4,data:r};return yield d.default(e),this.remote.synchronising=!1,console.log("Group location uploading done"),this}catch(t){this.remote.synchronising=!1;const r=t;if(409===(null===(e=r.response)||void 0===e?void 0:e.status))return console.log("Location uploading duplicate was found"),this;const n=null===(i=null===(o=r.response)||void 0===o?void 0:o.data)||void 0===i?void 0:i.message;if(!n)throw t;if("object"==typeof n){const e=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),"");throw new Error(e(n))}throw new Error(n)}}))}fetchRemoteLocations(){return e.__awaiter(this,void 0,void 0,(function*(){const e=`${this.remote.url}/index.php/services/rest/groups/${this.id}/locations`,t={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{const o=yield d.default.get(e,t),i=({values:e})=>a.getCamelCaseObj(e),r=o.data.map(i);return r.forEach((e=>c.parse(e))),r}catch(e){if(d.default.isCancel(e))return[];if(r.isAxiosNetworkError(e))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in e){throw new Error(e.issues.map((e=>`${e.path.join(" ")} ${e.message}`)).join(" "))}throw e}}))}}exports.default=g,exports.dtoSchema=u;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),s=require("@flumens/utils/dist/errors"),n=require("../Collection.js"),i=require("./Group.js"),o=require("./helpers.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=a(r),c=function(r){function n(s){var n=r.call(this,e.__assign({id:"groups",Model:i.default},s))||this;return n.remote=t.observable({synchronising:!1,url:s.url,getAccessToken:s.getAccessToken}),n}return e.__extends(n,r),n.prototype.fetchRemote=function(){return e.__awaiter(this,arguments,void 0,(function(t){var r,n,i,a,c,l,d,h,f,m,p,g,b,y,v,w,j=this;return void 0===t&&(t={}),e.__generator(this,(function(e){switch(e.label){case 0:console.log("📚 Collection: ".concat(this.id," collection fetching")),this.remote.synchronising=!0,e.label=1;case 1:return e.trys.push([1,8,,9]),r=t.type,n=t.form,i=t.location,[4,this.remote.getAccessToken()];case 2:return a=e.sent(),c="".concat(this.remote.url,"/index.php/services/rest/groups"),l={},r&&(l.view=r),n&&(l.page=n.join(",")),Number.isFinite(i)&&(l.indexed_location_ids=i),d={params:l,headers:{Authorization:"Bearer ".concat(a)},timeout:8e4},[4,u.default.get(c,d)];case 3:if(h=e.sent(),f=function(e){return!e.toDate||new Date(e.toDate)>new Date},m=function(e){return!e.fromDate||new Date(e.fromDate)<new Date},p=h.data.map((function(e){return e.values})).map(o.getCamelCaseObj).filter(f).filter(m),g=p.map((function(e){return j.Model.fromDTO(e,{skipStore:"joinable"===r})})),r){if("member"===r)for(b=0;b<this.data.length;b++)(y=this.data[b]).isStored&&"t"===y.data.userIsMember&&(y.destroy(),this.data.splice(b,1),b--);else if("pending"===r)for(b=0;b<this.data.length;b++)(y=this.data[b]).isStored&&"t"===y.data.userIsPending&&(y.destroy(),this.data.splice(b,1),b--);else if("joinable"===r)for(b=0;b<this.data.length;b++)(y=this.data[b]).isStored||(this.data.splice(b,1),b--)}else for(b=0;b<this.data.length;b++)(y=this.data[b]).isStored&&y.destroy(),this.data.splice(b,1),b--;return"member"!==r?[3,5]:[4,Promise.all(g.map((function(e){return e.save()})))];case 4:e.sent(),e.label=5;case 5:return"pending"!==r?[3,7]:[4,Promise.all(g.map((function(e){return e.save()})))];case 6:e.sent(),e.label=7;case 7:return(w=this.data).push.apply(w,g),console.log("📚 Collection: ".concat(this.id," collection fetching done ").concat(p.length," documents")),[3,9];case 8:if(v=e.sent(),u.default.isCancel(v))return[2];if(s.isAxiosNetworkError(v))throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in v)throw new Error(v.issues.map((function(e){return"".concat(e.path.join(" ")," ").concat(e.message)})).join(" "));throw this.remote.synchronising=!1,v;case 9:return this.remote.synchronising=!1,[2]}}))}))},Object.defineProperty(n.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),n}(n.default);exports.byGroupMembershipStatus=function(e){return function(t){var r=t.data.userIsMember||t.data.userIsPending;return"member"===e?r:!r}},exports.default=c;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),i=require("@flumens/utils/dist/errors"),r=require("../Collection.js"),o=require("./Group.js"),a=require("./helpers.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=n(s);class d extends r.default{constructor(e){super(Object.assign({id:"groups",Model:o.default},e)),this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken})}fetchRemote(){return e.__awaiter(this,arguments,void 0,(function*(e={}){console.log(`📚 Collection: ${this.id} collection fetching`),this.remote.synchronising=!0;try{const{type:t,form:s,location:i}=e,r=yield this.remote.getAccessToken(),o=`${this.remote.url}/index.php/services/rest/groups`,n={};t&&(n.view=t),s&&(n.page=s.join(",")),Number.isFinite(i)&&(n.indexed_location_ids=i);const d={params:n,headers:{Authorization:`Bearer ${r}`},timeout:8e4},u=yield l.default.get(o,d),c=e=>!e.toDate||new Date(e.toDate)>new Date,h=e=>!e.fromDate||new Date(e.fromDate)<new Date,m=u.data.map((({values:e})=>e)).map(a.getCamelCaseObj).filter(c).filter(h),f=m.map((e=>this.Model.fromDTO(e,{skipStore:"joinable"===t})));if(t){if("member"===t)for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&"t"===t.data.userIsMember&&(t.destroy(),this.data.splice(e,1),e--)}else if("pending"===t)for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&"t"===t.data.userIsPending&&(t.destroy(),this.data.splice(e,1),e--)}else if("joinable"===t)for(let e=0;e<this.data.length;e++){this.data[e].isStored||(this.data.splice(e,1),e--)}}else for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&t.destroy(),this.data.splice(e,1),e--}"member"===t&&(yield Promise.all(f.map((e=>e.save())))),"pending"===t&&(yield Promise.all(f.map((e=>e.save())))),this.data.push(...f),console.log(`📚 Collection: ${this.id} collection fetching done ${m.length} documents`)}catch(e){if(l.default.isCancel(e))return;if(i.isAxiosNetworkError(e))throw new i.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in e){throw new Error(e.issues.map((e=>`${e.path.join(" ")} ${e.message}`)).join(" "))}throw this.remote.synchronising=!1,e}this.remote.synchronising=!1}))}get isSynchronising(){return this.remote.synchronising}}exports.byGroupMembershipStatus=function(e){return t=>{const s=t.data.userIsMember||t.data.userIsPending;return"member"===e?s:!s}},exports.default=d;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),n=require("axios"),i=require("lodash"),r=require("zod"),o=require("@flumens/utils/dist/uuid"),a=require("../Model.js");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d,u=s(n),l=r.object({lat:r.z.string().min(1),lon:r.z.string().min(1),name:r.z.string().min(1),locationTypeId:r.z.string().min(1),centroidSref:r.z.string().min(1),centroidSrefSystem:r.z.string().min(1),id:r.z.string().optional(),createdOn:r.z.string().optional(),updatedOn:r.z.string().optional(),parentId:r.z.string().nullable().optional(),boundaryGeom:r.z.string().nullable().optional(),code:r.z.string().nullable().optional(),createdById:r.z.string().nullable().optional(),updatedById:r.z.string().nullable().optional(),externalKey:r.z.string().nullable().optional(),centroidGeom:r.z.string().nullable().optional(),public:r.z.string().nullable().optional(),comment:r.z.string().nullable().optional()});exports.LocationType=void 0,(d=exports.LocationType||(exports.LocationType={})).MothTrap="18879",d.Transect="777",d.TransectSection="778",d.GroupSite="14";var c=function(n){function r(i){var r=this,o=i.skipStore,a=i.store,s=i.media,d=void 0===s?[]:s,u=i.metadata,l=void 0===u?{}:u,c=i.url,p=i.getAccessToken,h=e.__rest(i,["skipStore","store","media","metadata","url","getAccessToken"]);return(r=n.call(this,e.__assign(e.__assign({},h),{store:o?void 0:a}))||this).metadata=t.observable(l),r.media=t.observable(d),r.remote=t.observable({synchronising:!1,url:c,getAccessToken:p}),r}return e.__extends(r,n),r.fromDTO=function(t,n){void 0===n&&(n={}),l.parse(t);var i=t.id,r=t.createdOn,a=t.updatedOn,s=t.externalKey,d=e.__rest(t,["id","createdOn","updatedOn","externalKey"]);return new this(e.__assign({cid:s||o.UUIDv7(),id:i,createdAt:new Date(r).getTime(),updatedAt:new Date(a).getTime(),data:d},n))},r.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,n,i,r,o,a,s,d,l,c,p,h,g,m,f;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,4,,5]),this.remote.synchronising=!0,[4,this.uploadMedia()];case 1:return t=e.sent(),n=this.toDTO(t),i="".concat(this.remote.url,"/index.php/services/rest/locations"),[4,this.remote.getAccessToken()];case 2:return r=e.sent(),o={url:i,method:"post",headers:{Authorization:"Bearer ".concat(r)},timeout:8e4,data:n},[4,u.default(o)];case 3:return a=e.sent().data,l=new Date(a.values.updated_on).getTime(),this.updatedAt=l,this.syncedAt=l,this.id=a.values.id,this.remote.synchronising=!1,this.store&&this.save(),console.log("Location uploading done"),[2,this];case 4:if(s=e.sent(),this.remote.synchronising=!1,409===(null===(p=(d=s).response)||void 0===p?void 0:p.status)&&(null===(h=d.response)||void 0===h?void 0:h.data.duplicate_of))return console.log("Location uploading duplicate was found"),l=(new Date).getTime(),this.updatedAt=l,this.syncedAt=l,this.id=null===(g=d.response)||void 0===g?void 0:g.data.duplicate_of.id,[2,this];if(!(c=null===(f=null===(m=d.response)||void 0===m?void 0:m.data)||void 0===f?void 0:f.message))throw s;if("object"==typeof c)throw new Error(function(e){return Object.entries(e).reduce((function(e,t){return"".concat(e).concat(t[0]," ").concat(t[1],"\n")}),"")}(c));throw new Error(c);case 5:return[2]}}))}))},r.prototype.toDTO=function(t){void 0===t&&(t={});var n,r=(n=this.data,Object.entries(n).reduce((function(e,t){var n=t[0],r=t[1];return e[n.includes("locAttr:")?n:i.snakeCase(n)]=r,e}),{})),o={values:e.__assign({external_key:this.cid},r),media:[]};return this.media.forEach((function(e){var n=e.toDTO(t);n&&o.media.push(n)})),o},r.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,Promise.all(this.media.map((function(e){return e.uploadFile()})))];case 1:return e.sent(),t={},this.media.forEach((function(e){t[e.cid]={name:e.data.queued}})),[2,t]}}))}))},Object.defineProperty(r.prototype,"isUploaded",{get:function(){return!!this.syncedAt},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isDraft",{get:function(){return!this.id},enumerable:!1,configurable:!0}),r}(a.default);exports.default=c,exports.dtoSchema=l;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),i=require("axios"),o=require("lodash"),n=require("zod"),s=require("@flumens/utils/dist/uuid"),r=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=a(i);const l=n.object({lat:n.z.string().min(1),lon:n.z.string().min(1),name:n.z.string().min(1),locationTypeId:n.z.string().min(1),centroidSref:n.z.string().min(1),centroidSrefSystem:n.z.string().min(1),id:n.z.string().optional(),createdOn:n.z.string().optional(),updatedOn:n.z.string().optional(),parentId:n.z.string().nullable().optional(),boundaryGeom:n.z.string().nullable().optional(),code:n.z.string().nullable().optional(),createdById:n.z.string().nullable().optional(),updatedById:n.z.string().nullable().optional(),externalKey:n.z.string().nullable().optional(),centroidGeom:n.z.string().nullable().optional(),public:n.z.string().nullable().optional(),comment:n.z.string().nullable().optional()});var u;exports.LocationType=void 0,(u=exports.LocationType||(exports.LocationType={})).MothTrap="18879",u.Transect="777",u.TransectSection="778",u.GroupSite="14";class c extends r.default{static fromDTO(t,i={}){l.parse(t);const{id:o,createdOn:n,updatedOn:r,externalKey:a}=t,d=e.__rest(t,["id","createdOn","updatedOn","externalKey"]);return new this(Object.assign({cid:a||s.UUIDv7(),id:o,createdAt:new Date(n).getTime(),updatedAt:new Date(r).getTime(),data:d},i))}constructor(i){var{skipStore:o,store:n,media:s=[],metadata:r={},url:a,getAccessToken:d}=i,l=e.__rest(i,["skipStore","store","media","metadata","url","getAccessToken"]);super(Object.assign(Object.assign({},l),{store:o?void 0:n})),this.metadata=t.observable(r),this.media=t.observable(s),this.remote=t.observable({synchronising:!1,url:a,getAccessToken:d})}saveRemote(){return e.__awaiter(this,void 0,void 0,(function*(){var e,t,i,o,n;try{this.remote.synchronising=!0;const e=yield this.uploadMedia(),t=this.toDTO(e),i=`${this.remote.url}/index.php/services/rest/locations`,o={url:i,method:"post",headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4,data:t},{data:n}=yield d.default(o),s=new Date(n.values.updated_on).getTime();return this.updatedAt=s,this.syncedAt=s,this.id=n.values.id,this.remote.synchronising=!1,this.store&&this.save(),console.log("Location uploading done"),this}catch(s){this.remote.synchronising=!1;const r=s;if(409===(null===(e=r.response)||void 0===e?void 0:e.status)&&(null===(t=r.response)||void 0===t?void 0:t.data.duplicate_of)){console.log("Location uploading duplicate was found");const e=(new Date).getTime();return this.updatedAt=e,this.syncedAt=e,this.id=null===(i=r.response)||void 0===i?void 0:i.data.duplicate_of.id,this}const a=null===(n=null===(o=r.response)||void 0===o?void 0:o.data)||void 0===n?void 0:n.message;if(!a)throw s;if("object"==typeof a){throw new Error((e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""))(a))}throw new Error(a)}}))}toDTO(e={}){const t=(i=this.data,Object.entries(i).reduce(((e,[t,i])=>(e[t.includes("locAttr:")?t:o.snakeCase(t)]=i,e)),{}));var i;const n={values:Object.assign({external_key:this.cid},t),media:[]};return this.media.forEach((t=>{const i=t.toDTO(e);i&&n.media.push(i)})),n}uploadMedia(){return e.__awaiter(this,void 0,void 0,(function*(){yield Promise.all(this.media.map((e=>e.uploadFile())));const e={};return this.media.forEach((t=>{e[t.cid]={name:t.data.queued}})),e}))}get isUploaded(){return!!this.syncedAt}get isSynchronising(){return this.remote.synchronising}get isDraft(){return!this.id}}exports.default=c,exports.dtoSchema=l;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("../Collection.js"),n=require("./Location.js"),o=function(r){function o(o){var i=r.call(this,e.__assign({id:"locations",Model:n.default},o))||this;return i.remote=t.observable({synchronising:!1,url:o.url,getAccessToken:o.getAccessToken}),i}return e.__extends(o,r),o.prototype.fetchRemote=function(){return e.__awaiter(this,arguments,void 0,(function(t){return void 0===t&&(t={}),e.__generator(this,(function(e){throw console.log(t),new Error("fetchRemote not implemented")}))}))},Object.defineProperty(o.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),o}(r.default);exports.byLocationType=function(e){return function(t){return t.data.locationTypeId===e}},exports.default=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),o=require("../Collection.js"),r=require("./Location.js");class s extends o.default{constructor(e){super(Object.assign({id:"locations",Model:r.default},e)),this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken})}fetchRemote(){return e.__awaiter(this,arguments,void 0,(function*(e={}){throw console.log(e),new Error("fetchRemote not implemented")}))}get isSynchronising(){return this.remote.synchronising}}exports.byLocationType=e=>t=>t.data.locationTypeId===e,exports.default=s;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),i=require("@flumens/utils"),a=require("../Model.js"),n=require("./helpers.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=o(r),d=i.isPlatform("hybrid"),u=function(r){function a(i){void 0===i&&(i={});var a=this,n=i.metadata,o=void 0===n?{}:n,s=e.__rest(i,["metadata"]);return s.createdAt=s.createdAt||(null==o?void 0:o.createdOn),s.updatedAt=s.updatedAt||(null==o?void 0:o.updatedOn),s.syncedAt=s.syncedAt||(null==o?void 0:o.syncedOn),(a=r.call(this,s)||this).debouncedValue=300,a.parent=a.parent,a.remote=t.observable({synchronising:!1,url:s.url,getAccessToken:s.getAccessToken}),a.metadata=t.observable(o),a}return e.__extends(a,r),a.getDataURI=function(e,t){return void 0===t&&(t={}),new Promise((function(r,i){if("string"==typeof e){var n=e.replace(/.*\.([a-z]+)$/i,"$1");return"jpg"===n&&(n="jpeg"),void a.resize(e,n,t.width,t.height).then((function(e){var t=e[0],i=e[1];r([i,n,t.width,t.height])}))}if(window.FileReader){var o=new FileReader;o.onload=function(i){var n,o;if(t.width||t.height)a.resize(null===(n=i.target)||void 0===n?void 0:n.result,e.type,t.width,t.height).then((function(t){var i=t[0],a=t[1];r([a,e.type,i.width,i.height])}));else{var s=new window.Image;s.onload=function(){var t,a=e.type.replace(/.*\/([a-z]+)$/i,"$1");r([null===(t=i.target)||void 0===t?void 0:t.result,a,s.width,s.height])},s.src=null===(o=i.target)||void 0===o?void 0:o.result}},o.readAsDataURL(e)}else i(new Error("No File Reader"))}))},a.resize=function(e,t,r,i){return new Promise((function(a){var n=new window.Image;n.onload=function(){var e,o=n.width,s=n.height,d=null;o/=d=o>s?o/(!r||r>o?o:r):s/(!i||i>s?s:i),s/=d;var u=document.createElement("canvas");u.width=o,u.height=s,null===(e=u.getContext("2d"))||void 0===e||e.drawImage(n,0,0,o,s),a([n,u.toDataURL(t)])},n.src=e}))},a.getImageModel=function(t,r,a){return e.__awaiter(this,void 0,void 0,(function(){var n,o,s,u,c,h,l;return e.__generator(this,(function(e){switch(e.label){case 0:if(n=this,!t)throw new Error("File not found while creating image model.");return d?[4,i.createImage(t)]:[3,2];case 1:return c=e.sent(),o=c.width,s=c.height,u=t.split("/").pop(),[3,4];case 2:return[4,n.getDataURI(t,{width:2e3,height:2e3})];case 3:l=e.sent(),u=l[0],o=l[2],s=l[3],e.label=4;case 4:return h=new n({data:{data:u,type:"jpeg",width:o,height:s,path:r}}),a?[3,6]:[4,h.addThumbnail()];case 5:e.sent(),e.label=6;case 6:return[2,h]}}))}))},a.prototype.toJSON=function(){var i=r.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(e.__assign(e.__assign({},i),{metadata:t.toJS(this.metadata)||{}})))},a.prototype.setupdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},a.prototype.toDTO=function(e){void 0===e&&(e={});var t=e[this.cid];if(!this.id&&!t)throw new Error("Image ID or queued ID is missing.");var r={values:{caption:this.data.caption}};return this.id?r.values.id=this.id:r.values.queued=t.name,r},a.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():r.prototype.sync.call(this)]}))}))},a.prototype.uploadFile=function(){return e.__awaiter(this,arguments,void 0,(function(t){var r,i,a,n,o,d,u,c,h,l;return void 0===t&&(t=!1),e.__generator(this,(function(e){switch(e.label){case 0:if(this.id)throw new Error("A file of a media on the remote cannot be uploaded again.");return r=Date.now()-432e5,i=this.syncedAt>r&&this.data.queued,!t&&i?[2]:[4,this.getFormData()];case 1:if(a=e.sent(),n=new FormData,(c=n).append.apply(c,a),!this.remote.getAccessToken)throw new Error("this.remote.getAccessToken is missing");return h={},d="Bearer ".concat,[4,this.remote.getAccessToken()];case 2:return h.Authorization=d.apply("Bearer ",[e.sent()]),o=h,[4,s.default.post("".concat(this.remote.url,"/index.php/services/rest/media-queue"),n,{headers:o,timeout:12e4})];case 3:if(u=e.sent(),!(null===(l=u.data[this.cid])||void 0===l?void 0:l.name))throw new Error("New remote media name was not be found.");return this.data.queued=u.data[this.cid].name,this.syncedAt=(new Date).getTime(),[2]}}))}))},a.prototype.getFormData=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,i,a,o,s,d;return e.__generator(this,(function(e){switch(e.label){case 0:return t=this.data.type,r=t,i=t,(null==t?void 0:t.match(/image.*/))?(d=t.split("/"),r=d[1]):i="image/".concat(i),a=this.getURL(),[4,n.getBlobFromURL(a,i)];case 1:return o=e.sent(),[2,[s=this.cid,o,"".concat(s,".").concat(r)]]}}))}))},a.prototype.getRemoteURL=function(){if(!this.remote.url)throw new Error("No remote url was set.");if(!this.data.queued&&!this.data.path)throw new Error("No media queued or path attribute.");var e=this.remote.url.replace("/index.php/services/rest","");return this.data.queued?"".concat(e,"/upload-queue/").concat(this.data.queued):"".concat(e,"/upload/").concat(this.data.path)},a.prototype.getURL=function(){return this.data.data},a.prototype.resize=function(e,t){var r=this,i=this;return new Promise((function(n,o){a.resize(r.getURL(),r.data.type,e,t).then((function(e){var t=e[0],r=e[1];i.data.data=r,n([t,r])})).catch(o)}))},a.prototype.addThumbnail=function(e){var t=this,r=this;return new Promise((function(e,i){/^data:/i.test(t.getURL())?a.resize(t.getURL(),t.data.type,100,100).then((function(t){var i=t[1];r.data.thumbnail=i,e()})).catch(i):a.getDataURI(t.getURL(),{width:100,height:100}).then((function(t){r.data.thumbnail=t[0],e()})).catch(i)}))},Object.defineProperty(a.prototype,"isUploaded",{get:function(){if(!this.parent)throw new Error("No media parent to return disabled status.");return this.parent.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),a}(a.default);exports.default=u;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),i=require("axios"),a=require("@flumens/utils"),r=require("../Model.js"),s=require("./helpers.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(i);const d=a.isPlatform("hybrid");class h extends r.default{static getDataURI(e,t={}){return new Promise(((i,a)=>{if("string"==typeof e){let a=e.replace(/.*\.([a-z]+)$/i,"$1");return"jpg"===a&&(a="jpeg"),void h.resize(e,a,t.width,t.height).then((e=>{const[t,r]=e;i([r,a,t.width,t.height])}))}if(!window.FileReader)return void a(new Error("No File Reader"));const r=new FileReader;r.onload=function(a){var r,s;if(t.width||t.height)h.resize(null===(r=a.target)||void 0===r?void 0:r.result,e.type,t.width,t.height).then((t=>{const[a,r]=t;i([r,e.type,a.width,a.height])}));else{const t=new window.Image;t.onload=()=>{var r;const s=e.type.replace(/.*\/([a-z]+)$/i,"$1");i([null===(r=a.target)||void 0===r?void 0:r.result,s,t.width,t.height])},t.src=null===(s=a.target)||void 0===s?void 0:s.result}},r.readAsDataURL(e)}))}static resize(e,t,i,a){return new Promise((r=>{const s=new window.Image;s.onload=()=>{var e;let{width:n}=s,{height:o}=s;let d=null;d=n>o?n/(!i||i>n?n:i):o/(!a||a>o?o:a),n/=d,o/=d;const h=document.createElement("canvas");h.width=n,h.height=o,null===(e=h.getContext("2d"))||void 0===e||e.drawImage(s,0,0,n,o),r([s,h.toDataURL(t)])},s.src=e}))}static getImageModel(t,i,r){return e.__awaiter(this,void 0,void 0,(function*(){const e=this;if(!t)throw new Error("File not found while creating image model.");let s,n,o;if(d){const e=yield a.createImage(t);s=e.width,n=e.height,o=t.split("/").pop()}else[o,,s,n]=yield e.getDataURI(t,{width:2e3,height:2e3});const h=new e({data:{data:o,type:"jpeg",width:s,height:n,path:i}});return r||(yield h.addThumbnail()),h}))}constructor(i={}){var{metadata:a={}}=i,r=e.__rest(i,["metadata"]);r.createdAt=r.createdAt||(null==a?void 0:a.createdOn),r.updatedAt=r.updatedAt||(null==a?void 0:a.updatedOn),r.syncedAt=r.syncedAt||(null==a?void 0:a.syncedOn),super(r),this.debouncedValue=300,this.parent=this.parent,this.remote=t.observable({synchronising:!1,url:r.url,getAccessToken:r.getAccessToken}),this.metadata=t.observable(a)}toJSON(){const e=super.toJSON();return JSON.parse(JSON.stringify(Object.assign(Object.assign({},e),{metadata:t.toJS(this.metadata)||{}})))}setupdatedAtTimestamp(e){var t;super.setUpdatedAtTimestamp(e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)}toDTO(e={}){const t=e[this.cid];if(!this.id&&!t)throw new Error("Image ID or queued ID is missing.");const i={values:{caption:this.data.caption}};return this.id?i.values.id=this.id:i.values.queued=t.name,i}sync(){const t=Object.create(null,{sync:{get:()=>super.sync}});return e.__awaiter(this,void 0,void 0,(function*(){return this.parent?this.parent.sync():t.sync.call(this)}))}uploadFile(){return e.__awaiter(this,arguments,void 0,(function*(e=!1){var t;if(this.id)throw new Error("A file of a media on the remote cannot be uploaded again.");const i=Date.now()-432e5,a=this.syncedAt>i&&this.data.queued;if(!e&&a)return;const r=yield this.getFormData(),s=new FormData;if(s.append(...r),!this.remote.getAccessToken)throw new Error("this.remote.getAccessToken is missing");const n={Authorization:`Bearer ${yield this.remote.getAccessToken()}`},d=yield o.default.post(`${this.remote.url}/index.php/services/rest/media-queue`,s,{headers:n,timeout:12e4});if(!(null===(t=d.data[this.cid])||void 0===t?void 0:t.name))throw new Error("New remote media name was not be found.");this.data.queued=d.data[this.cid].name,this.syncedAt=(new Date).getTime()}))}getFormData(){return e.__awaiter(this,void 0,void 0,(function*(){const{type:e}=this.data;let t=e,i=e;(null==e?void 0:e.match(/image.*/))?[,t]=e.split("/"):i=`image/${i}`;const a=this.getURL(),r=yield s.getBlobFromURL(a,i),n=this.cid;return[n,r,`${n}.${t}`]}))}getRemoteURL(){if(!this.remote.url)throw new Error("No remote url was set.");if(!this.data.queued&&!this.data.path)throw new Error("No media queued or path attribute.");const e=this.remote.url.replace("/index.php/services/rest","");return this.data.queued?`${e}/upload-queue/${this.data.queued}`:`${e}/upload/${this.data.path}`}getURL(){return this.data.data}resize(e,t){const i=this;return new Promise(((a,r)=>{h.resize(this.getURL(),this.data.type,e,t).then((e=>{const[t,r]=e;i.data.data=r,a([t,r])})).catch(r)}))}addThumbnail(e={}){const t=this;return new Promise(((e,i)=>{/^data:/i.test(this.getURL())?h.resize(this.getURL(),this.data.type,100,100).then((i=>{const[,a]=i;t.data.thumbnail=a,e()})).catch(i):h.getDataURI(this.getURL(),{width:100,height:100}).then((i=>{[t.data.thumbnail]=i,e()})).catch(i)}))}get isUploaded(){if(!this.parent)throw new Error("No media parent to return disabled status.");return this.parent.isUploaded}get isDisabled(){return this.isUploaded}get isSynchronising(){return this.remote.synchronising}}exports.default=h;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),n=require("lodash"),a=require("../Model.js"),i=require("./Media.js"),r=require("./helpers.js"),o=function(a){function o(n){void 0===n&&(n={});var r=this,s=n.metadata,d=void 0===s?{}:s,u=n.media,c=void 0===u?[]:u,l=n.Media,p=void 0===l?i.default:l,v=t.__rest(n,["metadata","media","Media"]);v.createdAt=v.createdAt||(null==d?void 0:d.createdOn),v.updatedAt=v.updatedAt||(null==d?void 0:d.updatedOn),v.syncedAt=v.syncedAt||(null==d?void 0:d.syncedOn),(r=a.call(this,v)||this).debouncedValue=300,r.keys=function(){var e;return t.__assign(t.__assign({},o.keys),(e=r.getSurvey().attrs||{},Object.keys(e).reduce((function(n,a){var i;return t.__assign(t.__assign({},n),((i={})[a]=e[a].remote||e[a],i))}),{})))},r.Media=p,r.metadata=e.observable(d);var m,f,_=c.map((m=r.Media,void 0===f&&(f={}),function(e){return e instanceof m?e:new m(t.__assign(t.__assign({},e),f))}));r.media=e.observable(_);var h=function(t){return t.parent=r};r.media.forEach(h);return e.intercept(r.media,(function(t){var e;return(null===(e=t.added)||void 0===e?void 0:e.length)?(t.added.forEach(h),r.setUpdatedAtTimestamp(Date.now())):t.removedCount&&r.setUpdatedAtTimestamp(Date.now()),t})),r}return t.__extends(o,a),o.fromElasticDTO=function(e,n,a){var i,o,s,d,u,c,l,p=e.id,v=e.metadata,m=e.event,f=e.occurrence,_=e.taxon,h=e.identification,y=new Date(v.created_on).getTime(),g=new Date(v.updated_on).getTime(),b=Date.now(),A=m.parent_event_id?null===(o=null===(i=a.smp)||void 0===i?void 0:i.occ)||void 0===o?void 0:o.attrs:null===(s=a.occ)||void 0===s?void 0:s.attrs;A||(A=(null===(u=null===(d=a.smp)||void 0===d?void 0:d.occ)||void 0===u?void 0:u.attrs)||(null===(c=a.occ)||void 0===c?void 0:c.attrs)||{});var w=r.parseRemoteAttrs(A,(null==f?void 0:f.attributes)||[]),O=(null===(l=null==f?void 0:f.media)||void 0===l?void 0:l.map((function(t){var e=t.path;return{id:e,createdAt:y,updatedAt:g,syncedAt:b,data:{data:"".concat(n,"/upload/").concat(e)}}})))||[],x=_.species||_.taxon_name,N=x!==_.taxon_name?_.taxon_name:"";return new this({id:p,cid:p,createdAt:y,updatedAt:g,syncedAt:b,metadata:{verification:h},data:t.__assign(t.__assign({},w),{taxon:{warehouse_id:parseInt(_.taxa_taxon_list_id,10),scientific_name:x,scientificName:x,common_name:N,commonName:N,found_in_name:N?"common_name":"scientific_name",foundInName:N?"commonName":"scientificName"},comment:null==f?void 0:f.occurrence_remarks}),media:O})},o.prototype.setUpdatedAtTimestamp=function(t){var e;a.prototype.setUpdatedAtTimestamp.call(this,t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)},o.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){if(!this.parent)throw new Error("Trying to save locally without a parent");return this.parent.save(),[2]}))}))},o.prototype.destroy=function(e){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.parent)throw new Error("Trying to destroy locally without a parent");return this.parent.occurrences.remove(this),[4,Promise.all(this.media.map((function(t){return t.destroy(!0)})))];case 1:return t.sent(),e?[2]:[4,this.parent.save()];case 2:return t.sent(),[2]}}))}))},o.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,this.parent?this.parent.sync():a.prototype.sync.call(this)]}))}))},o.prototype.toJSON=function(){var n,i=a.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(t.__assign(t.__assign({},i),{media:(null===(n=this.media)||void 0===n?void 0:n.map((function(t){return t.toJSON()})))||[],metadata:e.toJS(this.metadata)||{}})))},o.prototype.getSurvey=function(){return this.parent&&this.parent.getSurvey().occ||{}},Object.defineProperty(o.prototype,"isUploaded",{get:function(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),o.prototype.toDTO=function(e){var a=this;void 0===e&&(e={});var i="function"==typeof this.keys?this.keys():this.keys,r=t.__assign(t.__assign({},o.keys),i),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);Object.keys(this.data).forEach((function(t){var e=a.data[t],i=function(t){return null==t};if(!i(e)){if(!r[t])return t=t.includes("occAttr:")?t:n.snakeCase(t),void(s.values[t]=e);var o=r[t].id||t;if(e=function(t,e){var n=r[t].values;if(!n)return e;if("function"==typeof n)return n(e,s,a);if(n instanceof Array){var i=n.find((function(t){return t.value===e}));if(!i||!i.id)throw new Error('A "'.concat(t,'" attribute "').concat(e,'" value could not be mapped to a remote database field.'));return i.id}return e instanceof Array?e.map((function(t){return n[t]})):n[e]}(t,e),!i(e)){var d=Number.isNaN(Number(o))?o:"occAttr:".concat(o);d=d.includes("occAttr:")?d:n.snakeCase(d),s.values[d]=e}}})),this.media.forEach((function(t){var n=t.toDTO(e);n&&s.media.push(n)}));var d=this.getSurvey();return d.modifySubmission?d.modifySubmission(s,this):s},o.keys={taxon:{id:"taxa_taxon_list_id"}},o}(a.default);exports.default=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),a=require("lodash"),i=require("../Model.js"),s=require("./Media.js"),n=require("./helpers.js");class r extends i.default{static fromElasticDTO(t,e,a){var i,s,r,d,o,c,u;const{id:l,metadata:m,event:p,occurrence:h,taxon:v,identification:f}=t,y=new Date(m.created_on).getTime(),b=new Date(m.updated_on).getTime(),_=Date.now();let O=p.parent_event_id?null===(s=null===(i=a.smp)||void 0===i?void 0:i.occ)||void 0===s?void 0:s.attrs:null===(r=a.occ)||void 0===r?void 0:r.attrs;O||(O=(null===(o=null===(d=a.smp)||void 0===d?void 0:d.occ)||void 0===o?void 0:o.attrs)||(null===(c=a.occ)||void 0===c?void 0:c.attrs)||{});const g=n.parseRemoteAttrs(O,(null==h?void 0:h.attributes)||[]),A=(null===(u=null==h?void 0:h.media)||void 0===u?void 0:u.map((({path:t})=>({id:t,createdAt:y,updatedAt:b,syncedAt:_,data:{data:`${e}/upload/${t}`}}))))||[],w=v.species||v.taxon_name,j=w!==v.taxon_name?v.taxon_name:"";return new this({id:l,cid:l,createdAt:y,updatedAt:b,syncedAt:_,metadata:{verification:f},data:Object.assign(Object.assign({},g),{taxon:{warehouse_id:parseInt(v.taxa_taxon_list_id,10),scientific_name:w,scientificName:w,common_name:j,commonName:j,found_in_name:j?"common_name":"scientific_name",foundInName:j?"commonName":"scientificName"},comment:null==h?void 0:h.occurrence_remarks}),media:A})}constructor(a={}){var{metadata:i={},media:n=[],Media:d=s.default}=a,o=t.__rest(a,["metadata","media","Media"]);o.createdAt=o.createdAt||(null==i?void 0:i.createdOn),o.updatedAt=o.updatedAt||(null==i?void 0:i.updatedOn),o.syncedAt=o.syncedAt||(null==i?void 0:i.syncedOn),super(o),this.debouncedValue=300,this.keys=()=>{return Object.assign(Object.assign({},r.keys),(t=this.getSurvey().attrs||{},Object.keys(t).reduce(((e,a)=>Object.assign(Object.assign({},e),{[a]:t[a].remote||t[a]})),{})));var t},this.Media=d,this.metadata=e.observable(i);const c=n.map(((t,e={})=>a=>a instanceof t?a:new t(Object.assign(Object.assign({},a),e)))(this.Media));this.media=e.observable(c);const u=t=>t.parent=this;this.media.forEach(u);e.intercept(this.media,(t=>{var e;return(null===(e=t.added)||void 0===e?void 0:e.length)?(t.added.forEach(u),this.setUpdatedAtTimestamp(Date.now())):t.removedCount&&this.setUpdatedAtTimestamp(Date.now()),t}))}setUpdatedAtTimestamp(t){var e;super.setUpdatedAtTimestamp(t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)}save(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.parent)throw new Error("Trying to save locally without a parent");this.parent.save()}))}destroy(e){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.parent)throw new Error("Trying to destroy locally without a parent");this.parent.occurrences.remove(this),yield Promise.all(this.media.map((t=>t.destroy(!0)))),e||(yield this.parent.save())}))}sync(){const e=Object.create(null,{sync:{get:()=>super.sync}});return t.__awaiter(this,void 0,void 0,(function*(){return this.parent?this.parent.sync():e.sync.call(this)}))}toJSON(){var t;const a=super.toJSON();return JSON.parse(JSON.stringify(Object.assign(Object.assign({},a),{media:(null===(t=this.media)||void 0===t?void 0:t.map((t=>t.toJSON())))||[],metadata:e.toJS(this.metadata)||{}})))}getSurvey(){if(!this.parent)return{};return this.parent.getSurvey().occ||{}}get isUploaded(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded}get isDisabled(){return this.isUploaded}toDTO(t={}){const e="function"==typeof this.keys?this.keys():this.keys,i=Object.assign(Object.assign({},r.keys),e),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);const n=(t,e)=>{const a=i[t].values;if(!a)return e;if("function"==typeof a)return a(e,s,this);if(a instanceof Array){const i=a.find((({value:t})=>t===e));if(!i||!i.id)throw new Error(`A "${t}" attribute "${e}" value could not be mapped to a remote database field.`);return i.id}return e instanceof Array?e.map((t=>a[t])):a[e]};Object.keys(this.data).forEach((t=>{let e=this.data[t];const r=t=>null==t;if(r(e))return;if(!i[t])return t=t.includes("occAttr:")?t:a.snakeCase(t),void(s.values[t]=e);const d=i[t].id||t;if(e=n(t,e),r(e))return;let o=Number.isNaN(Number(d))?d:`occAttr:${d}`;o=o.includes("occAttr:")?o:a.snakeCase(o),s.values[o]=e})),this.media.forEach((e=>{const a=e.toDTO(t);a&&s.media.push(a)}));const d=this.getSurvey();return d.modifySubmission?d.modifySubmission(s,this):s}}r.keys={taxon:{id:"taxa_taxon_list_id"}},exports.default=r;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),s=require("lodash"),n=require("wellknown"),a=require("@flumens/utils"),i=require("../Model.js"),o=require("./ElasticOccurrence.js"),c=require("./ElasticSample.js"),u=require("./Media.js"),d=require("./Occurrence.js"),l=require("./helpers.js");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var h=p(r),m=p(n),f=function(t,r){return void 0===r&&(r={}),function(s){return s instanceof t?s:new t(e.__assign(e.__assign({},s),r))}};function v(e,t){var r,s,n,a,i;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(n=e.samples)||void 0===n||n.forEach((function(e,r){return v(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(a=e.occurrences)||void 0===a||a.forEach((function(e,r){return v(e,t.occurrences[r])}))),e.media&&t.media&&(null===(i=e.media)||void 0===i||i.forEach((function(e,r){return v(e,t.media[r])})));else{if("process"in window&&"test"===(null===(s=null===(r=window.process)||void 0===r?void 0:r.env)||void 0===s?void 0:s.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}var _=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,s,n;return e.__generator(this,(function(a){switch(a.label){case 0:return r=[],t.media?(s=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,t.getFormData()];case 1:return r=e.sent(),[2,[t,r]]}}))}))},[4,Promise.all(t.media.map(s))]):[3,2];case 1:n=a.sent(),r.push.apply(r,n),a.label=2;case 2:return t.occurrences?[4,Promise.all(t.occurrences.map(_))]:[3,4];case 3:n=a.sent(),r.push.apply(r,n.flat()),a.label=4;case 4:return t.samples?[4,Promise.all(t.samples.map(_))]:[3,6];case 5:n=a.sent(),r.push.apply(r,n.flat()),a.label=6;case 6:return[2,r]}}))}))};function y(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return y(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return y(e)}))),e.media&&(r.media=e.media.map((function(e){return y(e)}))),r}function g(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var w=function(r){function n(s){void 0===s&&(s={});var a=this,i=s.metadata,o=void 0===i?{}:i,c=s.samples,p=void 0===c?[]:c,h=s.occurrences,m=void 0===h?[]:h,v=s.media,_=void 0===v?[]:v,y=s.Occurrence,g=void 0===y?d.default:y,w=s.Media,b=void 0===w?u.default:w,A=s.skipStore,O=e.__rest(s,["metadata","samples","occurrences","media","Occurrence","Media","skipStore"]);O.createdAt=O.createdAt||(null==o?void 0:o.createdOn),O.updatedAt=O.updatedAt||(null==o?void 0:o.updatedOn),O.syncedAt=O.syncedAt||(null==o?void 0:o.syncedOn);var E=A?void 0:O.store;(a=r.call(this,e.__assign(e.__assign({},O),{store:E}))||this).validateRemote=l.validateRemoteModel,a.error=t.observable({message:""}),a.debouncedValue=300,a.keys=function(){var t;return e.__assign(e.__assign({},n.keys),(t=a.getSurvey().attrs||{},Object.keys(t).reduce((function(r,s){var n;return e.__assign(e.__assign({},r),((n={})[s]=t[s].remote||t[s],n))}),{})))},a.requiresRemoteSync=function(){return!a.syncedAt||a.updatedAt>a.syncedAt},a.Occurrence=g,a.Media=b,a.remote=t.observable({synchronising:!1,url:O.url,getAccessToken:O.getAccessToken}),a.metadata=t.observable(o);var S=p.map(f(a.constructor));a.samples=t.observable(S);var k=m.map(f(a.Occurrence,{Media:a.Media}));a.occurrences=t.observable(k);var T=_.map(f(a.Media));a.media=t.observable(T);var D=function(e){return e.parent=a};a.samples.forEach(D),a.occurrences.forEach(D),a.media.forEach(D);var q=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(D),a.setUpdatedAtTimestamp(Date.now())):e.removedCount&&a.setUpdatedAtTimestamp(Date.now()),e};return t.intercept(a.samples,q),t.intercept(a.occurrences,q),t.intercept(a.media,q),a}return e.__extends(n,r),n.fromElasticDTO=function(t,r,s){var n,a;void 0===r&&(r={});var i=t.id,o=t.event,c=t.location,u=t.metadata,d=r.url,p=new Date(o.date_start),h=new Date(u.updated_on).getTime(),f=Date.now(),v=c.point.split(",").map(parseFloat),_=v[0],y=v[1],g="OSGB"===c.output_sref_system?c.output_sref:"",w=c.geom?m.default.parse(c.geom):null,b=o.parent_event_id,A=l.parseRemoteAttrs(b?null==s?void 0:s.smp.attrs:null==s?void 0:s.attrs,o.attributes||[]),O=null===(n=o.media)||void 0===n?void 0:n.map((function(e){var t=e.path;return{id:t,metadata:{updatedOn:p,createdOn:p,syncedOn:p},data:{data:"".concat(d,"/upload/").concat(t)}}}));return new this(e.__assign({id:i,cid:o.source_system_key||i,createdAt:p.getTime(),updatedAt:h,syncedAt:f,metadata:{saved:!0},data:e.__assign(e.__assign({},A),{surveyId:u.survey.id,date:p.toISOString(),location:{code:c.code,name:c.name||c.verbatim_locality,latitude:_,longitude:y,shape:w,gridref:g},enteredSrefSystem:4326,groupId:null===(a=u.group)||void 0===a?void 0:a.id,comment:o.event_remarks,training:"true"===u.trial}),media:O},r))},n.prototype.setUpdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},n.prototype.toJSON=function(){var s,n,a,i=r.prototype.toJSON.call(this);return a=e.__assign(e.__assign({},i),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(s=this.samples)||void 0===s?void 0:s.map((function(e){return e.toJSON()})))||[],media:(null===(n=this.media)||void 0===n?void 0:n.map((function(e){return e.toJSON()})))||[]}),JSON.parse(JSON.stringify(a))},n.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},n.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a,i,o,c;return e.__generator(this,(function(u){switch(u.label){case 0:if(this.data.deleted)return[2];if(this.parent)return this.parent.save(),[2];if(!this.store)throw new Error("Trying to sync locally without a store");return t=this.toJSON(),r=t.data,s=t.metadata,n=t.occurrences,a=t.samples,i=t.media,o=e.__rest(t,["data","metadata","occurrences","samples","media"]),c=e.__assign(e.__assign({},o),{data:{data:r,metadata:s,occurrences:n,samples:a,media:i}}),[4,this.store.save(c)];case 1:return u.sent(),[2]}}))}))},n.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,n=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(n.media.map((function(e){return e.destroy(!0)}))),Promise.all(n.occurrences.map((function(e){return e.destroy(!0)})))])},this.parent?(this.parent.samples.remove(this),[4,r()]):[3,2];case 1:return e.sent(),t?[2]:(this.parent.save(),[2]);case 2:if(!this.store)throw new Error("Trying to sync locally without a store");return[4,this.store.delete(this.cid)];case 3:return e.sent(),null===(s=this.collection)||void 0===s||s.remove(this),[4,r()];case 4:return e.sent(),this.data.deleted=!0,[2]}}))}))},n.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():r.prototype.sync.call(this)]}))}))},n.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this.uploadMedia()];case 2:return t=e.sent(),r=this.toDTO(t),[4,this.postRemote(r)];case 3:return s=e.sent(),this.remote.synchronising=!1,v(this,s),n=(new Date).getTime(),this.updatedAt=n,this.syncedAt=n,this.save(),[3,5];case 4:throw a=e.sent(),this.remote.synchronising=!1,a;case 5:return[2]}}))}))},n.prototype.postRemote=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,n,i,o,c,u,d;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,3,,4]),o={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:return o.Authorization=s.apply("Bearer ",[e.sent()]),r=o,[4,h.default.post("".concat(this.remote.url,"/index.php/services/rest/samples"),t,{headers:r,timeout:12e4})];case 2:return[2,e.sent().data];case 3:if(n=e.sent(),409===(i=n).status&&(null===(c=i.response)||void 0===c?void 0:c.data.duplicate_of))return[2,y(this,i.response.data.duplicate_of.id)];if(a.isAxiosNetworkError(i))throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===i.status)throw g(t),new Error(l.getErrorMessageFromObject(null===(d=null===(u=i.response)||void 0===u?void 0:u.data)||void 0===d?void 0:d.message));throw new Error(i.message);case 4:return[2]}}))}))},n.prototype.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a,i,u,d,l,p,h,m,f,v,_,y,g,w,b,A,O=this;return e.__generator(this,(function(E){switch(E.label){case 0:if(!(t=this.remote.url)||t.includes("index.php"))throw new Error('A "remote" property is not configured.');if(!this.cid)throw new Error("Sample cid or id is missing for fetching remote model.");return[4,this.remote.getAccessToken()];case 1:return r=E.sent(),[4,c.fetchElasticSample({id:this.id,cid:this.cid,url:t,accessToken:r})];case 2:return s=E.sent(),this.data.surveyId||(this.data.surveyId=s.metadata.survey.id),n=this.getSurvey(),a=this.constructor.fromElasticDTO(s,{url:t,skipStore:!0},n),this.id=a.id,this.cid=a.cid||this.cid,Object.assign(this.data,a.data),Object.assign(this.metadata,a.metadata),i=c.fetchElasticSubSamples({parentId:this.id,url:t,accessToken:r}),u=o.fetchElasticOccurrences({parentId:this.id,url:t,accessToken:r}),[4,Promise.all([i,u])];case 3:return d=E.sent(),l=d[0],p=d[1],h=(new Date).getTime(),m=function(e){var r=O.constructor.fromElasticDTO(e,{url:t},O.getSurvey());return r.syncedAt=h,r},f=l.map(m),v=function(t,r){var s;return e.__assign(e.__assign({},t),((s={})[r.id]=r,s))},_=f.reduce(v,((b={})[this.id]=this,b)),this.samples.clear(),(A=this.samples).push.apply(A,f),y=function(e){var t=O.Occurrence.fromElasticDTO(e,O.remote.url,O.getSurvey());return t.syncedAt=h,[t,e.event.event_id]},g=p.map(y),w=function(e){var t=e[0],r=e[1];r!==parseInt(O.id,10)?_[r]?_[r].occurrences.push(t):console.log("Can't attach occ to missing ".concat(r," sample")):O.occurrences.push(t)},g.forEach(w),this.syncedAt=h,[2]}}))}))},n.prototype.updateRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,3,,4]),this.remote.synchronising=!0,t={},r=this.toDTO(t),[4,this.putRemote(this.id,r)];case 2:return v(this,e.sent()),s=(new Date).getTime(),this.updatedAt=s,this.syncedAt=s,this.save(),this.remote.synchronising=!1,[3,4];case 3:throw n=e.sent(),this.remote.synchronising=!1,n;case 4:return[2]}}))}))},n.prototype.putRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s,n,i,o,c,u,d;return e.__generator(this,(function(e){switch(e.label){case 0:return c={},n="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:c.Authorization=n.apply("Bearer ",[e.sent()]),s=c,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,h.default.put("".concat(this.remote.url,"/samples/").concat(t),r,{headers:s,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if(i=e.sent(),o=i,a.isAxiosNetworkError(o))throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===o.status)throw g(r),new Error(l.getErrorMessageFromObject(null===(d=null===(u=o.response)||void 0===u?void 0:u.data)||void 0===d?void 0:d.message));throw new Error(o.message);case 5:return[2]}}))}))},n.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,i,o,c,u,d=this;return e.__generator(this,(function(l){switch(l.label){case 0:return t={},[4,_(this)];case 1:if(r=l.sent(),!r.length)return[2,t];s=function(t){return e.__awaiter(d,void 0,void 0,(function(){var r,s,n,i;return e.__generator(this,(function(e){switch(e.label){case 0:return i={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:i.Authorization=s.apply("Bearer ",[e.sent()]),r=i,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,h.default.post("".concat(this.remote.url,"/index.php/services/rest/media-queue"),t,{headers:r,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if("timeout"===(n=e.sent()).message)throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");throw n;case 5:return[2]}}))}))},n=[],i=Date.now()-432e5,r.forEach((function(e){var r=e[0];r.syncedAt>i&&r.data.queued?t[r.cid]={name:r.data.queued}:n.push(e)})),o=5,c=function(r){var a,i,c,u;return e.__generator(this,(function(d){switch(d.label){case 0:return a=n.slice(r,r+o),i=new FormData,a.forEach((function(e){var t=e[1];return i.append.apply(i,t)})),[4,s(i)];case 1:return c=d.sent(),u=(new Date).getTime(),a.forEach((function(e){var t=e[0];t.syncedAt=u,t.data.queued=c[t.cid].name})),t=e.__assign(e.__assign({},t),c),[2]}}))},u=0,l.label=2;case 2:return u<n.length?[5,c(u)]:[3,5];case 3:l.sent(),l.label=4;case 4:return u+=o,[3,2];case 5:return[2,t]}}))}))},n.prototype.toDTO=function(t){var r=this;void 0===t&&(t={});var a="function"==typeof this.keys?this.keys():this.keys,i=e.__assign(e.__assign({},n.keys),a),o={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(o.values.id=this.id);var c=function(e,t){var s=i[e].values;if(!s)return t;if("function"==typeof s)return s(t,o,r);if(t instanceof Array)return t.map((function(t){return c(e,t)}));if(s instanceof Array){var n=s.find((function(e){return e.value===t}));if(!n||!n.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return n.id}return s[t]};Object.keys(this.data).forEach((function(e){var t=r.data[e],n=function(e){return null==e};if(!n(t)){if(!i[e])return e=e.includes("smpAttr:")?e:s.snakeCase(e),void(o.values[e]=t);if(!n(t=c(e,t))){var a=i[e].id||e,u=Number.isNaN(Number(a))?a:"smpAttr:".concat(a);u=u.includes("smpAttr:")?u:s.snakeCase(u),o.values[u]=t}}})),this.samples.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.toDTO(t);s&&o.samples.push(s)})),this.occurrences.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.toDTO(t);s&&o.occurrences.push(s)})),this.media.forEach((function(e){var r=e.toDTO(t);r&&o.media.push(r)}));var u=this.getSurvey();return u.modifySubmission?u.modifySubmission(o,this):o},Object.defineProperty(n.prototype,"isUploaded",{get:function(){return this.parent?this.parent.isUploaded:!!this.syncedAt},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),n.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}}},n}(i.default);exports.default=w,exports.getMediaFormData=_;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),i=require("lodash"),r=require("wellknown"),a=require("@flumens/utils"),o=require("../Model.js"),n=require("./ElasticOccurrence.js"),d=require("./ElasticSample.js"),c=require("./Media.js"),u=require("./Occurrence.js"),l=require("./helpers.js");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var m=h(s),p=h(r);const v=(e,t={})=>s=>s instanceof e?s:new e(Object.assign(Object.assign({},s),t));function f(e,t){var s,i,r,a,o;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(r=e.samples)||void 0===r||r.forEach(((e,s)=>f(e,t.samples[s])))),e.occurrences&&t.occurrences&&(null===(a=e.occurrences)||void 0===a||a.forEach(((e,s)=>f(e,t.occurrences[s])))),e.media&&t.media&&(null===(o=e.media)||void 0===o||o.forEach(((e,s)=>f(e,t.media[s]))));else{if("process"in window&&"test"===(null===(i=null===(s=window.process)||void 0===s?void 0:s.env)||void 0===i?void 0:i.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}const y=t=>e.__awaiter(void 0,void 0,void 0,(function*(){const s=[];if(t.media){const i=t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=yield t.getFormData();return[t,e]})),r=yield Promise.all(t.media.map(i));s.push(...r)}if(t.occurrences){const e=yield Promise.all(t.occurrences.map(y));s.push(...e.flat())}if(t.samples){const e=yield Promise.all(t.samples.map(y));s.push(...e.flat())}return s}));function g(e,t){const s={values:{id:t||-1}};return e.occurrences&&(s.occurrences=e.occurrences.map((e=>g(e)))),e.samples&&(s.samples=e.samples.map((e=>g(e)))),e.media&&(s.media=e.media.map((e=>g(e)))),s}function w(e){try{const t=2e5;console.warn(JSON.stringify(e).substring(0,t/2))}catch(e){}}class O extends o.default{static fromElasticDTO(e,t={},s){var i,r;const{id:a,event:o,location:n,metadata:d}=e,{url:c}=t,u=new Date(o.date_start),h=new Date(d.updated_on).getTime(),m=Date.now(),[v,f]=n.point.split(",").map(parseFloat),y="OSGB"===n.output_sref_system?n.output_sref:"",g=n.geom?p.default.parse(n.geom):null,w=o.parent_event_id,O=l.parseRemoteAttrs(w?null==s?void 0:s.smp.attrs:null==s?void 0:s.attrs,o.attributes||[]),b=null===(i=o.media)||void 0===i?void 0:i.map((({path:e})=>({id:e,metadata:{updatedOn:u,createdOn:u,syncedOn:u},data:{data:`${c}/upload/${e}`}})));return new this(Object.assign({id:a,cid:o.source_system_key||a,createdAt:u.getTime(),updatedAt:h,syncedAt:m,metadata:{saved:!0},data:Object.assign(Object.assign({},O),{surveyId:d.survey.id,date:u.toISOString(),location:{code:n.code,name:n.name||n.verbatim_locality,latitude:v,longitude:f,shape:g,gridref:y},enteredSrefSystem:4326,groupId:null===(r=d.group)||void 0===r?void 0:r.id,comment:o.event_remarks,training:"true"===d.trial}),media:b},t))}constructor(s={}){var{metadata:i={},samples:r=[],occurrences:a=[],media:o=[],Occurrence:n=u.default,Media:d=c.default,skipStore:h}=s,m=e.__rest(s,["metadata","samples","occurrences","media","Occurrence","Media","skipStore"]);m.createdAt=m.createdAt||(null==i?void 0:i.createdOn),m.updatedAt=m.updatedAt||(null==i?void 0:i.updatedOn),m.syncedAt=m.syncedAt||(null==i?void 0:i.syncedOn);const p=h?void 0:m.store;super(Object.assign(Object.assign({},m),{store:p})),this.validateRemote=l.validateRemoteModel,this.error=t.observable({message:""}),this.debouncedValue=300,this.keys=()=>{return Object.assign(Object.assign({},O.keys),(e=this.getSurvey().attrs||{},Object.keys(e).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:e[s].remote||e[s]})),{})));var e},this.requiresRemoteSync=()=>!this.syncedAt||this.updatedAt>this.syncedAt,this.Occurrence=n,this.Media=d,this.remote=t.observable({synchronising:!1,url:m.url,getAccessToken:m.getAccessToken}),this.metadata=t.observable(i);const f=r.map(v(this.constructor));this.samples=t.observable(f);const y=a.map(v(this.Occurrence,{Media:this.Media}));this.occurrences=t.observable(y);const g=o.map(v(this.Media));this.media=t.observable(g);const w=e=>e.parent=this;this.samples.forEach(w),this.occurrences.forEach(w),this.media.forEach(w);const b=e=>{var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(w),this.setUpdatedAtTimestamp(Date.now())):e.removedCount&&this.setUpdatedAtTimestamp(Date.now()),e};t.intercept(this.samples,b),t.intercept(this.occurrences,b),t.intercept(this.media,b)}setUpdatedAtTimestamp(e){var t;super.setUpdatedAtTimestamp(e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)}toJSON(){var e,s;const i=super.toJSON();return r=Object.assign(Object.assign({},i),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((e=>e.toJSON()))||[],samples:(null===(e=this.samples)||void 0===e?void 0:e.map((e=>e.toJSON())))||[],media:(null===(s=this.media)||void 0===s?void 0:s.map((e=>e.toJSON())))||[]}),JSON.parse(JSON.stringify(r));var r}getSurvey(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}}save(){return e.__awaiter(this,void 0,void 0,(function*(){if(this.data.deleted)return;if(this.parent)return void this.parent.save();if(!this.store)throw new Error("Trying to sync locally without a store");const t=this.toJSON(),{data:s,metadata:i,occurrences:r,samples:a,media:o}=t,n=e.__rest(t,["data","metadata","occurrences","samples","media"]),d=Object.assign(Object.assign({},n),{data:{data:s,metadata:i,occurrences:r,samples:a,media:o}});yield this.store.save(d)}))}destroy(t){return e.__awaiter(this,void 0,void 0,(function*(){var e;const s=()=>Promise.all([Promise.all(this.media.map((e=>e.destroy(!0)))),Promise.all(this.occurrences.map((e=>e.destroy(!0))))]);if(this.parent){if(this.parent.samples.remove(this),yield s(),t)return;this.parent.save()}else{if(!this.store)throw new Error("Trying to sync locally without a store");yield this.store.delete(this.cid),null===(e=this.collection)||void 0===e||e.remove(this),yield s(),this.data.deleted=!0}}))}sync(){const t=Object.create(null,{sync:{get:()=>super.sync}});return e.__awaiter(this,void 0,void 0,(function*(){return this.parent?this.parent.sync():t.sync.call(this)}))}saveRemote(){return e.__awaiter(this,void 0,void 0,(function*(){if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');try{this.remote.synchronising=!0;const e=yield this.uploadMedia(),t=this.toDTO(e),s=yield this.postRemote(t);this.remote.synchronising=!1,f(this,s);const i=(new Date).getTime();this.updatedAt=i,this.syncedAt=i,this.save()}catch(e){throw this.remote.synchronising=!1,e}}))}postRemote(t){return e.__awaiter(this,void 0,void 0,(function*(){var e,s,i;try{const e={Authorization:`Bearer ${yield this.remote.getAccessToken()}`};return(yield m.default.post(`${this.remote.url}/index.php/services/rest/samples`,t,{headers:e,timeout:12e4})).data}catch(r){const o=r;if(409===o.status&&(null===(e=o.response)||void 0===e?void 0:e.data.duplicate_of))return g(this,o.response.data.duplicate_of.id);if(a.isAxiosNetworkError(o))throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===o.status)throw w(t),new Error(l.getErrorMessageFromObject(null===(i=null===(s=o.response)||void 0===s?void 0:s.data)||void 0===i?void 0:i.message));throw new Error(o.message)}}))}fetchRemote(){return e.__awaiter(this,void 0,void 0,(function*(){const{url:e}=this.remote;if(!e||e.includes("index.php"))throw new Error('A "remote" property is not configured.');if(!this.cid)throw new Error("Sample cid or id is missing for fetching remote model.");const t=yield this.remote.getAccessToken(),s=yield d.fetchElasticSample({id:this.id,cid:this.cid,url:e,accessToken:t});this.data.surveyId||(this.data.surveyId=s.metadata.survey.id);const i=this.getSurvey(),r=this.constructor.fromElasticDTO(s,{url:e,skipStore:!0},i);this.id=r.id,this.cid=r.cid||this.cid,Object.assign(this.data,r.data),Object.assign(this.metadata,r.metadata);const a=d.fetchElasticSubSamples({parentId:this.id,url:e,accessToken:t}),o=n.fetchElasticOccurrences({parentId:this.id,url:e,accessToken:t}),[c,u]=yield Promise.all([a,o]),l=(new Date).getTime(),h=c.map((t=>{const s=this.constructor.fromElasticDTO(t,{url:e},this.getSurvey());return s.syncedAt=l,s})),m=h.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.id]:t})),{[this.id]:this});this.samples.clear(),this.samples.push(...h);u.map((e=>{const t=this.Occurrence.fromElasticDTO(e,this.remote.url,this.getSurvey());return t.syncedAt=l,[t,e.event.event_id]})).forEach((([e,t])=>{t!==parseInt(this.id,10)?m[t]?m[t].occurrences.push(e):console.log(`Can't attach occ to missing ${t} sample`):this.occurrences.push(e)})),this.syncedAt=l}))}updateRemote(){return e.__awaiter(this,void 0,void 0,(function*(){if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');try{this.remote.synchronising=!0;const e={},t=this.toDTO(e);f(this,yield this.putRemote(this.id,t));const s=(new Date).getTime();this.updatedAt=s,this.syncedAt=s,this.save(),this.remote.synchronising=!1}catch(e){throw this.remote.synchronising=!1,e}}))}putRemote(t,s){return e.__awaiter(this,void 0,void 0,(function*(){var e,i;const r={Authorization:`Bearer ${yield this.remote.getAccessToken()}`};try{return(yield m.default.put(`${this.remote.url}/samples/${t}`,s,{headers:r,timeout:12e4})).data}catch(t){const r=t;if(a.isAxiosNetworkError(r))throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===r.status)throw w(s),new Error(l.getErrorMessageFromObject(null===(i=null===(e=r.response)||void 0===e?void 0:e.data)||void 0===i?void 0:i.message));throw new Error(r.message)}}))}uploadMedia(){return e.__awaiter(this,void 0,void 0,(function*(){let t={};const s=yield y(this);if(!s.length)return t;const i=t=>e.__awaiter(this,void 0,void 0,(function*(){const e={Authorization:`Bearer ${yield this.remote.getAccessToken()}`};try{return(yield m.default.post(`${this.remote.url}/index.php/services/rest/media-queue`,t,{headers:e,timeout:12e4})).data}catch(e){if("timeout"===e.message)throw new a.HandledError("Request aborted because of a network issue (timeout or similar).");throw e}})),r=[],o=Date.now()-432e5;s.forEach((e=>{const[s]=e;s.syncedAt>o&&s.data.queued?t[s.cid]={name:s.data.queued}:r.push(e)}));for(let e=0;e<r.length;e+=5){const s=r.slice(e,e+5),a=new FormData;s.forEach((([,e])=>a.append(...e)));const o=yield i(a),n=(new Date).getTime();s.forEach((([e])=>{e.syncedAt=n,e.data.queued=o[e.cid].name})),t=Object.assign(Object.assign({},t),o)}return t}))}toDTO(e={}){const t="function"==typeof this.keys?this.keys():this.keys,s=Object.assign(Object.assign({},O.keys),t),r={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(r.values.id=this.id);const a=(e,t)=>{const i=s[e].values;if(!i)return t;if("function"==typeof i)return i(t,r,this);if(t instanceof Array)return t.map((t=>a(e,t)));if(i instanceof Array){const s=i.find((({value:e})=>e===t));if(!s||!s.id)throw new Error(`A "${e}" attribute "${t}" value could not be mapped to a remote database field.`);return s.id}return i[t]};Object.keys(this.data).forEach((e=>{let t=this.data[e];const o=e=>null==e;if(o(t))return;if(!s[e])return e=e.includes("smpAttr:")?e:i.snakeCase(e),void(r.values[e]=t);if(t=a(e,t),o(t))return;const n=s[e].id||e;let d=Number.isNaN(Number(n))?n:`smpAttr:${n}`;d=d.includes("smpAttr:")?d:i.snakeCase(d),r.values[d]=t})),this.samples.forEach((t=>{this.data.training&&(t.data.training=this.data.training);const s=t.toDTO(e);s&&r.samples.push(s)})),this.occurrences.forEach((t=>{this.data.training&&(t.data.training=this.data.training);const s=t.toDTO(e);s&&r.occurrences.push(s)})),this.media.forEach((t=>{const s=t.toDTO(e);s&&r.media.push(s)}));const o=this.getSurvey();return o.modifySubmission?o.modifySubmission(r,this):r}get isUploaded(){return this.parent?this.parent.isUploaded:!!this.syncedAt}get isDisabled(){return this.isUploaded}get isSynchronising(){return this.remote.synchronising}}O.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}}},exports.default=O,exports.getMediaFormData=y;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),n=require("../Collection.js"),a=require("./ElasticOccurrence.js"),s=require("./ElasticSample.js"),i=require("./Sample.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=o(r),u=function(r){function n(n){var a=r.call(this,e.__assign({id:"samples",Model:i.default},n))||this;a.Occurrence=n.Occurrence,a.remote=t.observable({synchronising:!1,url:n.url,getAccessToken:n.getAccessToken});return t.observe(a.data,(function(e){e.addedCount&&e.added.forEach((function(e){return e.collection=a})),e.removedCount&&e.removed.forEach((function(e){return delete e.collection}))})),a}return e.__extends(n,r),n.prototype.fetch=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,a,s=this;return e.__generator(this,(function(i){switch(i.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=i.sent(),r=function(t){var r=t.data,n=r.data,a=r.metadata,i=r.occurrences,o=r.samples,c=r.media,u=r.attrs;return new s.Model(e.__assign(e.__assign({},t),{attrs:u,data:n,metadata:a,occurrences:i,samples:o,media:c}))},n=t.map(r),(a=this.data).push.apply(a,n),this.ready.resolve(!0),[2]}}))}))},n.prototype.fetchRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var n,i,o,u,d,l,f,p,h,m,v,_,y,g,b,O,E,S,j,w,A,T,q,k=this;return e.__generator(this,(function(x){switch(x.label){case 0:return console.log("Fetching remote samples, page",t),n={bool:{must_not:{exists:{field:"event.parent_event_id"}}}},i={match:{"metadata.trial":"false"}},o=function(e){return{match:{"metadata.survey.id":e}}},u={bool:{should:r.map(o)}},d=[u,n,i],l=JSON.stringify({from:t,size:100,query:{bool:{must:d}},sort:[{"metadata.created_on":"desc"}]}),f=this.remote.url,[4,this.remote.getAccessToken()];case 1:return p=x.sent(),h={method:"post",url:"".concat(f,"/index.php/services/rest/es-samples/_search"),headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(p)},data:l},[4,c.default.request(h)];case 2:return m=x.sent(),v=function(e){return e._source},_=m.data.hits.hits.map(v),y=_.map((function(e){return e.id})),g=s.fetchElasticSubSamples({parentId:y,url:f,accessToken:p}),b=a.fetchElasticOccurrences({parentId:y,url:f,accessToken:p}),[4,Promise.all([g,b])];case 3:return O=x.sent(),E=O[0],S=O[1],j=function(e){return!!e},w=_.map(function(t,r,n,a,s){return function(i){var o,c,u=(new Date).getTime();try{var d=new n({skipStore:!0});d.data.surveyId=i.metadata.survey.id;var l=d.getSurvey(),f=n.fromElasticDTO(i,{url:t,skipStore:!0},l);d.id=f.id,d.cid=f.cid||d.cid,Object.assign(d.data,f.data),Object.assign(d.metadata,f.metadata);var p=function(e){return e.event.parent_event_id===d.id||e.event.event_id===d.id},h=a.filter(p).map((function(e){var r=n.fromElasticDTO(e,{url:t},l);return r.syncedAt=u,r})),m=h.reduce((function(t,r){var n;return e.__assign(e.__assign({},t),((n={})[r.id]=r,n))}),((o={})[d.id]=d,o));return s.filter(p).map((function(e){var n=r.fromElasticDTO(e,t,l);return n.syncedAt=u,[n,e.event.event_id]})).forEach((function(e){var t=e[0],r=e[1];r!==parseInt(d.id,10)?m[r]?m[r].occurrences.push(t):console.log("Can't attach occ to missing ".concat(r," sample")):d.occurrences.push(t)})),(c=d.samples).push.apply(c,h),d.syncedAt=u,d}catch(e){return console.warn(JSON.stringify(i)),console.error(e),null}}}(f,this.Occurrence,this.Model,E,S)).filter(j),A=function(e){return!k.cidMap.has(e.cid)},T=w.filter(A),(q=this.data).push.apply(q,T),[2,T]}}))}))},n.prototype.removeAllSynced=function(){var e=[];return this.data.forEach((function(t){t.syncedAt&&e.push(t.destroy())})),Promise.all(e)},n.prototype.reset=function(){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return t=this.data.map((function(e){return e.destroy()})),[4,Promise.all(t)];case 1:return e.sent(),[2]}}))}))},Object.defineProperty(n.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),n}(n.default);exports.default=u;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),r=require("../Collection.js"),a=require("./ElasticOccurrence.js"),i=require("./ElasticSample.js"),c=require("./Sample.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(s);class d extends r.default{constructor(e){super(Object.assign({id:"samples",Model:c.default},e)),this.Occurrence=e.Occurrence,this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken});t.observe(this.data,(e=>{e.addedCount&&e.added.forEach((e=>e.collection=this)),e.removedCount&&e.removed.forEach((e=>delete e.collection))}))}fetch(){return e.__awaiter(this,void 0,void 0,(function*(){if(!this.store||!this.Model)return void this.ready.resolve(!1);const e=(yield this.store.findAll()).map((e=>{const{data:t,metadata:s,occurrences:r,samples:a,media:i,attrs:c}=e.data;return new this.Model(Object.assign(Object.assign({},e),{attrs:c,data:t,metadata:s,occurrences:r,samples:a,media:i}))}));this.data.push(...e),this.ready.resolve(!0)}))}fetchRemote(t,s){return e.__awaiter(this,void 0,void 0,(function*(){console.log("Fetching remote samples, page",t);const e=[{bool:{should:s.map((e=>({match:{"metadata.survey.id":e}})))}},{bool:{must_not:{exists:{field:"event.parent_event_id"}}}},{match:{"metadata.trial":"false"}}],r=JSON.stringify({from:t,size:100,query:{bool:{must:e}},sort:[{"metadata.created_on":"desc"}]}),c=this.remote.url,o=yield this.remote.getAccessToken(),d={method:"post",url:`${c}/index.php/services/rest/es-samples/_search`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},data:r},l=(yield n.default.request(d)).data.hits.hits.map((e=>e._source)),u=l.map((e=>e.id)),h=i.fetchElasticSubSamples({parentId:u,url:c,accessToken:o}),m=a.fetchElasticOccurrences({parentId:u,url:c,accessToken:o}),[p,f]=yield Promise.all([h,m]),v=l.map(((e,t,s,r,a)=>i=>{const c=(new Date).getTime();try{const o=new s({skipStore:!0});o.data.surveyId=i.metadata.survey.id;const n=o.getSurvey(),d=s.fromElasticDTO(i,{url:e,skipStore:!0},n);o.id=d.id,o.cid=d.cid||o.cid,Object.assign(o.data,d.data),Object.assign(o.metadata,d.metadata);const l=t=>{const r=s.fromElasticDTO(t,{url:e},n);return r.syncedAt=c,r},u=e=>e.event.parent_event_id===o.id||e.event.event_id===o.id,h=r.filter(u).map(l),m=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:t}),p=h.reduce(m,{[o.id]:o}),f=s=>{const r=t.fromElasticDTO(s,e,n);return r.syncedAt=c,[r,s.event.event_id]},v=a.filter(u).map(f),y=([e,t])=>{t!==parseInt(o.id,10)?p[t]?p[t].occurrences.push(e):console.log(`Can't attach occ to missing ${t} sample`):o.occurrences.push(e)};return v.forEach(y),o.samples.push(...h),o.syncedAt=c,o}catch(e){return console.warn(JSON.stringify(i)),console.error(e),null}})(c,this.Occurrence,this.Model,p,f)).filter((e=>!!e)),y=v.filter((e=>!this.cidMap.has(e.cid)));return this.data.push(...y),y}))}removeAllSynced(){const e=[];return this.data.forEach((t=>{t.syncedAt&&e.push(t.destroy())})),Promise.all(e)}reset(){return e.__awaiter(this,void 0,void 0,(function*(){const e=this.data.map((e=>e.destroy()));yield Promise.all(e)}))}get isSynchronising(){return this.remote.synchronising}}exports.default=d;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("lodash");function t(e,r){for(var t=atob(e.split(",")[1]),n=[],s=0;s<t.length;s++)n.push(t.charCodeAt(s));return new Blob([new Uint8Array(n)],{type:r})}function n(e){if(!e)return!1;return!!e.toString().match(/^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i)}exports.dataURItoBlob=t,exports.getBlobFromURL=function(e,r){if(n(e)){var s=t(e,r);return Promise.resolve(s)}return new Promise((function(r){var t=new XMLHttpRequest;t.open("GET",e,!0),t.responseType="blob",t.onload=function(){var e=t.response;r(e)},t.send()}))},exports.getCamelCaseObj=function(e){return r.mapKeys(e,(function(e,t){return r.camelCase(t)}))},exports.getErrorMessageFromObject=function(e){return Object.entries(e).reduce((function(e,r){return"".concat(e).concat(r[0]," ").concat(r[1],"\n")}),"")},exports.isDataURL=n,exports.parseRemoteAttrs=function(e,r){e=e||{};var t=Object.entries(e);return r.reduce((function(e,r){var n=t.find((function(e){var t;return(null===(t=e[1].remote)||void 0===t?void 0:t.id)===parseInt(r.id,10)}));if(!n)return e;var s=n[0],a=isNaN(r.value)?r.value:parseFloat(r.value);return e[s]=a,e}),{})},exports.validateRemoteModel=function(){var r=this.getSurvey(),t=r.verify&&r.verify(this.data,this),n={};if(t){var s=t&&"issues"in t;!("ValidationError"===(null==t?void 0:t.name)||"ValidationError"===(null==t?void 0:t.type))&&!s?n.errors=[t.message]:s?n.errors=t.issues.map((function(e){return e.message})):n=e.__assign({},t)}var a=function(e,r){var t=r.validateRemote();return t&&(e[r.cid]=t,e[r.cid].model=r),e},o=(this.samples||[]).reduce(a,{}),i=(this.occurrences||[]).reduce(a,{}),u=(this.media||[]).reduce(a,{});return Object.keys(n).length||Object.keys(o).length||Object.keys(i).length||Object.keys(u).length?{attributes:n,model:this,models:e.__assign(e.__assign(e.__assign({},o),i),u)}:null};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("lodash");function t(e,t){const s=atob(e.split(",")[1]),r=[];for(let e=0;e<s.length;e++)r.push(s.charCodeAt(e));return new Blob([new Uint8Array(r)],{type:t})}function s(e){if(!e)return!1;return!!e.toString().match(/^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i)}exports.dataURItoBlob=t,exports.getBlobFromURL=function(e,r){if(s(e)){const s=t(e,r);return Promise.resolve(s)}return new Promise((t=>{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="blob",s.onload=()=>{const e=s.response;t(e)},s.send()}))},exports.getCamelCaseObj=t=>e.mapKeys(t,((t,s)=>e.camelCase(s))),exports.getErrorMessageFromObject=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""),exports.isDataURL=s,exports.parseRemoteAttrs=(e,t)=>{e=e||{};const s=Object.entries(e);return t.reduce(((e,t)=>{const r=s.find((([,e])=>{var s;return(null===(s=e.remote)||void 0===s?void 0:s.id)===parseInt(t.id,10)}));if(!r)return e;const[n]=r,o=isNaN(t.value)?t.value:parseFloat(t.value);return e[n]=o,e}),{})},exports.validateRemoteModel=function(){const e=this.getSurvey(),t=e.verify&&e.verify(this.data,this);let s={};if(t){const e=t&&"issues"in t;!("ValidationError"===(null==t?void 0:t.name)||"ValidationError"===(null==t?void 0:t.type))&&!e?s.errors=[t.message]:e?s.errors=t.issues.map((({message:e})=>e)):s=Object.assign({},t)}const r=(e,t)=>{const s=t.validateRemote();return s&&(e[t.cid]=s,e[t.cid].model=t),e},n=(this.samples||[]).reduce(r,{}),o=(this.occurrences||[]).reduce(r,{}),a=(this.media||[]).reduce(r,{});if(Object.keys(s).length||Object.keys(n).length||Object.keys(o).length||Object.keys(a).length){return{attributes:s,model:this,models:Object.assign(Object.assign(Object.assign({},n),o),a)}}return null};
package/dist/Model.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("mobx-utils"),s=require("@flumens/utils"),i=function(t){return JSON.parse(JSON.stringify(t))},a={},n=function(){function n(n){var o=n.id,d=void 0===o?"":o,u=n.cid,c=void 0===u?"":u,h=n.createdAt,l=n.updatedAt,v=n.syncedAt,p=n.data,f=void 0===p?{}:p,y=n.attrs,b=void 0===y?{}:y,_=n.store,A=this;this.ready=new s.Deferred,this.debouncedValue=3e3,this._observerPaused=!1,this.id=d,this.cid=c||d||s.UUIDv7();var w,g=Date.now();this.createdAt=h||g,this.updatedAt=l||g,this.syncedAt=v,this.data=i(t.__assign(t.__assign(t.__assign({},a),f),b)),e.makeObservable(this,{createdAt:e.observable,updatedAt:e.observable,syncedAt:e.observable,data:e.observable}),this.store=_;r.deepObserve(this.data,(function(){A._observerPaused||(A.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(w),w=setTimeout((function(){return A.sync.apply(A,t)}),A.debouncedValue)}())}))}return n.prototype.setUpdatedAtTimestamp=function(t){this.updatedAt=t},n.prototype.fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.store.find(this.cid)]:(this.ready.resolve(!1),[2]);case 1:return(r=t.sent())?[3,3]:[4,this.save()];case 2:return t.sent(),this.ready.resolve(!0),[2];case 3:return r.id&&(this.id=r.id),r.cid&&(this.cid=r.cid),this._observerPaused=!0,e.set(this.data,r.data),this._observerPaused=!1,this.createdAt=r.createdAt,this.updatedAt=r.updatedAt,this.syncedAt=r.syncedAt,this.ready.resolve(!0),[2]}}))}))},n.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.store)throw new Error("Trying to save locally without a store");return e=this.toJSON(),[4,this.store.save(e)];case 1:return t.sent(),[2]}}))}))},n.prototype.destroy=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.store)throw new Error("Trying to delete locally without a store");return[4,this.store.delete(this.cid)];case 1:return t.sent(),[2]}}))}))},n.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.save()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},n.prototype.toJSON=function(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,data:e.toJS(this.data)}},n.prototype.reset=function(r){var s=this;this.id="";var i=JSON.parse(JSON.stringify(t.__assign(t.__assign({},a),r)));e.set(this.data,i);var n=Object.keys(i);return Object.keys(this.data).forEach((function(t){n.includes(t)||(s.data[t]=null,delete s.data[t])})),this.save()},Object.defineProperty(n.prototype,"isStored",{get:function(){return!!this.store},enumerable:!1,configurable:!0}),n}();exports.copyObject=i,exports.default=n;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),s=require("mobx-utils"),i=require("@flumens/utils");const d=t=>JSON.parse(JSON.stringify(t)),r={};exports.copyObject=d,exports.default=class{constructor({id:t="",cid:a="",createdAt:o,updatedAt:h,syncedAt:c,data:n={},attrs:u={},store:l}){this.ready=new i.Deferred,this.debouncedValue=3e3,this._observerPaused=!1,this.id=t,this.cid=a||t||i.UUIDv7();const v=Date.now();let y;this.createdAt=o||v,this.updatedAt=h||v,this.syncedAt=c,this.data=d(Object.assign(Object.assign(Object.assign({},r),n),u)),e.makeObservable(this,{createdAt:e.observable,updatedAt:e.observable,syncedAt:e.observable,data:e.observable}),this.store=l;const b=(...t)=>{clearTimeout(y),y=setTimeout((()=>this.sync.apply(this,t)),this.debouncedValue)};s.deepObserve(this.data,(()=>{this._observerPaused||(this.updatedAt=Date.now(),b())}))}setUpdatedAtTimestamp(t){this.updatedAt=t}fetch(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.store)return void this.ready.resolve(!1);const t=yield this.store.find(this.cid);if(!t)return yield this.save(),void this.ready.resolve(!0);t.id&&(this.id=t.id),t.cid&&(this.cid=t.cid),this._observerPaused=!0,e.set(this.data,t.data),this._observerPaused=!1,this.createdAt=t.createdAt,this.updatedAt=t.updatedAt,this.syncedAt=t.syncedAt,this.ready.resolve(!0)}))}save(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.store)throw new Error("Trying to save locally without a store");const t=this.toJSON();yield this.store.save(t)}))}destroy(){return t.__awaiter(this,void 0,void 0,(function*(){if(!this.store)throw new Error("Trying to delete locally without a store");yield this.store.delete(this.cid)}))}sync(...e){return t.__awaiter(this,void 0,void 0,(function*(){this.store&&(yield this.save())}))}toJSON(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,data:e.toJS(this.data)}}reset(t){this.id="";const s=JSON.parse(JSON.stringify(Object.assign(Object.assign({},r),t)));e.set(this.data,s);const i=Object.keys(s);return Object.keys(this.data).forEach((t=>{i.includes(t)||(this.data[t]=null,delete this.data[t])})),this.save()}get isStored(){return!!this.store}};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("localforage"),t=require("localforage-cordovasqlitedriver"),i=require("@flumens/utils"),n=require("./utils.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=o(r),a=o(t),u=["indexeddb","websql","localstorage"];i.isPlatform("hybrid")&&(u=e.__spreadArray([a.default],u,!0));var c={driverOrder:u},d=function(){function r(t){var n=this;if(i.isPlatform("hybrid")&&!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");var o=e.__assign(e.__assign({},c),t);this.debugging=o.debugging,this.localForage=null,this.ready=new Promise((function(e,t){var i=new Promise((function(e){o.driverOrder&&"object"==typeof o.driverOrder[0]?s.default.defineDriver(o.driverOrder[0]).then(e):e(void 0)}));if(!o.storeName)throw new Error("storeName prop is missing");n.storeName=o.storeName,i.then((function(){var i={name:o.name||"indicia",storeName:o.storeName};o.version&&(i.version=o.version);var a=r._getDriverOrder(o.driverOrder),u=o.LocalForage||s.default;n.localForage=u.createInstance(i),n.localForage.setDriver(a).then(e).catch(t)}))}))}return r._getDriverOrder=function(e){return e.map((function(e){switch(e){case"indexeddb":return s.default.INDEXEDDB;case"websql":return s.default.WEBSQL;case"localstorage":return s.default.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))},r.prototype.save=function(r){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r.cid)throw new Error("Invalid key passed to store");return this.debugging?[4,this.find(r.cid)]:[3,3];case 2:t=e.sent(),n.printDiff(t,r,r.cid,this.storeName),e.label=3;case 3:return[2,this.localForage.setItem(r.cid,r)]}}))}))},r.prototype.find=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.getItem(r)]}}))}))},r.prototype.findAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),r=[],[4,this.localForage.iterate((function(e){r.push(e)}))];case 2:return e.sent(),[2,r]}}))}))},r.prototype.delete=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.removeItem(r)]}}))}))},r.prototype.deleteAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r,t=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.findAll()];case 2:return r=e.sent(),[4,Promise.all(r.map((function(e){return t.delete(e)})))];case 3:return e.sent(),[2]}}))}))},r.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=function(r,t){var i;return e.__assign(e.__assign({},r),((i={})[t.cid]=t,i))},[4,this.findAll()];case 2:return[2,t.sent().reduce(r,{})]}}))}))},r.prototype.import=function(r){return e.__awaiter(this,void 0,void 0,(function(){var t,i=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.deleteAll()];case 2:if(e.sent(),"object"!=typeof r)throw new Error("Invalid obj passed to store");return t=Object.entries(r).map((function(e){var r=e[1];return i.save(r)})),[4,Promise.all(t)];case 3:return e.sent(),[2]}}))}))},r}();exports.default=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("localforage"),t=require("localforage-cordovasqlitedriver"),i=require("@flumens/utils"),o=require("./utils.js");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=s(r),a=s(t);let n=["indexeddb","websql","localstorage"];i.isPlatform("hybrid")&&(n=[a.default,...n]);const l={driverOrder:n};class c{constructor(e){if(i.isPlatform("hybrid")&&!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");const r=Object.assign(Object.assign({},l),e);this.debugging=r.debugging,this.localForage=null,this.ready=new Promise(((e,t)=>{const i=new Promise((e=>{r.driverOrder&&"object"==typeof r.driverOrder[0]?d.default.defineDriver(r.driverOrder[0]).then(e):e(void 0)}));if(!r.storeName)throw new Error("storeName prop is missing");this.storeName=r.storeName,i.then((()=>{const i={name:r.name||"indicia",storeName:r.storeName};r.version&&(i.version=r.version);const o=c._getDriverOrder(r.driverOrder),s=r.LocalForage||d.default;this.localForage=s.createInstance(i),this.localForage.setDriver(o).then(e).catch(t)}))}))}static _getDriverOrder(e){return e.map((e=>{switch(e){case"indexeddb":return d.default.INDEXEDDB;case"websql":return d.default.WEBSQL;case"localstorage":return d.default.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))}save(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r.cid)throw new Error("Invalid key passed to store");if(this.debugging){const e=yield this.find(r.cid);o.printDiff(e,r,r.cid,this.storeName)}return this.localForage.setItem(r.cid,r)}))}find(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r)throw new Error("Invalid key passed to store");return this.localForage.getItem(r)}))}findAll(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const e=[];return yield this.localForage.iterate((r=>{e.push(r)})),e}))}delete(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,!r)throw new Error("Invalid key passed to store");return this.localForage.removeItem(r)}))}deleteAll(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const e=yield this.findAll();yield Promise.all(e.map((e=>this.delete(e))))}))}export(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;return(yield this.findAll()).reduce(((e,r)=>Object.assign(Object.assign({},e),{[r.cid]:r})),{})}))}import(r){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,yield this.deleteAll(),"object"!=typeof r)throw new Error("Invalid obj passed to store");const e=Object.entries(r).map((([,e])=>this.save(e)));yield Promise.all(e)}))}}exports.default=c;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),n=require("@capacitor-community/sqlite"),r=require("@capacitor/core"),i=require("@capacitor/filesystem"),s=require("@flumens/utils"),o=function(){function o(e){var t=e.name,r=e.debug,i=e.web;this.sqliteConnection=new n.SQLiteConnection(n.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new s.Deferred,this.name=t||this.name,this.debug=r||this.debug,this.isWeb=i||this.isWeb}return o.migrateCordova=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,i,s,o;return e.__generator(this,(function(e){switch(e.label){case 0:console.log("SQLite: Cordova db migration"),r=new n.SQLiteConnection(n.CapacitorSQLite),e.label=1;case 1:return e.trys.push([1,5,,6]),[4,r.getMigratableDbList(t?"Library/LocalDatabase":void 0)];case 2:return i=e.sent(),(null===(o=i.values)||void 0===o?void 0:o.length)?(console.log("SQLite: migrating",i.values),[4,r.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,i.values)]):(console.log("SQLite: no Cordova db to migrate"),[2]);case 3:return e.sent(),[4,r.deleteOldDatabases(t?"Library/LocalDatabase":void 0,i.values)];case 4:return e.sent(),console.log("SQLite: migrating done",i.values),[3,6];case 5:return s=e.sent(),console.error(s),[3,6];case 6:return[4,r.checkConnectionsConsistency()];case 7:return e.sent(),[4,r.closeAllConnections()];case 8:return e.sent(),[2]}}))}))},Object.defineProperty(o.prototype,"db",{get:function(){return this.connection},enumerable:!1,configurable:!0}),o.prototype.init=function(){return e.__awaiter(this,void 0,void 0,(function(){var n,r;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t.defineCustomElements(window),(n=document.createElement("jeep-sqlite")).setAttribute("autoSave","true"),document.body.appendChild(n),[4,customElements.whenDefined("jeep-sqlite")]):[3,3];case 1:return e.sent(),[4,this.sqliteConnection.initWebStore()];case 2:e.sent(),e.label=3;case 3:return[4,this.sqliteConnection.checkConnectionsConsistency()];case 4:return e.sent(),[4,this.sqliteConnection.closeAllConnections()];case 5:return e.sent(),r=this,[4,this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1)];case 6:return r.connection=e.sent(),[4,this.connection.open()];case 7:return e.sent(),this.ready.resolve(!0),[2]}}))}))},o.prototype.query=function(t){return e.__awaiter(this,arguments,void 0,(function(t){var n,r,i=t.sql,s=t.params;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.db.query(i,s).then((function(e){return e.values||[]}))];case 2:return n=e.sent(),this.debug?(console.groupCollapsed("💾 SQL: ".concat(i.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30),"...")),console.debug(i,s,n),console.groupEnd(),[4,null===(r=this.sqliteConnection)||void 0===r?void 0:r.saveToStore(this.name)]):[3,4];case 3:e.sent(),e.label=4;case 4:return[2,n]}}))}))},o.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,n;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t=this.name,[2,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(n){n.target.result.transaction(["databases"],"readwrite").objectStore("databases").get("".concat(t,"SQLite.db")).onsuccess=function(t){var n=new Blob([t.target.result],{type:"application/vnd.sqlite3"});e(n)}}}))]):[4,this.db.getUrl()];case 1:return n=e.sent().url,[4,fetch(r.Capacitor.convertFileSrc(n))];case 2:return[2,e.sent().blob()]}}))}))},o.prototype.import=function(t){return e.__awaiter(this,void 0,void 0,(function(){var n,r,s,o,a;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(r=Uint8Array.bind,[4,t.arrayBuffer()]):[3,2];case 1:return n=new(r.apply(Uint8Array,[void 0,e.sent()])),s=this.name,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(t){t.target.result.transaction(["databases"],"readwrite").objectStore("databases").put(n,"".concat(s,"SQLite.db"),0).onsuccess=function(){return e()}}})),[2];case 2:return[4,this.db.getUrl()];case 3:return o=e.sent().url,[4,new Promise((function(e){var n=new FileReader;n.onload=e,n.readAsDataURL(t)})).then((function(e){return e.target.result}))];case 4:return a=e.sent(),[4,i.Filesystem.writeFile({path:o,data:a})];case 5:return e.sent(),[2]}}))}))},o}();exports.default=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),i=require("@capacitor-community/sqlite"),n=require("@capacitor/core"),o=require("@capacitor/filesystem"),s=require("@flumens/utils");exports.default=class{static migrateCordova(t){return e.__awaiter(this,void 0,void 0,(function*(){var e;console.log("SQLite: Cordova db migration");const n=new i.SQLiteConnection(i.CapacitorSQLite);try{const i=yield n.getMigratableDbList(t?"Library/LocalDatabase":void 0);if(!(null===(e=i.values)||void 0===e?void 0:e.length))return void console.log("SQLite: no Cordova db to migrate");console.log("SQLite: migrating",i.values),yield n.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,i.values),yield n.deleteOldDatabases(t?"Library/LocalDatabase":void 0,i.values),console.log("SQLite: migrating done",i.values)}catch(e){console.error(e)}yield n.checkConnectionsConsistency(),yield n.closeAllConnections()}))}get db(){return this.connection}constructor({name:e,debug:t,web:n}){this.sqliteConnection=new i.SQLiteConnection(i.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new s.Deferred,this.name=e||this.name,this.debug=t||this.debug,this.isWeb=n||this.isWeb}init(){return e.__awaiter(this,void 0,void 0,(function*(){if(this.isWeb){t.defineCustomElements(window);const e=document.createElement("jeep-sqlite");e.setAttribute("autoSave","true"),document.body.appendChild(e),yield customElements.whenDefined("jeep-sqlite"),yield this.sqliteConnection.initWebStore()}yield this.sqliteConnection.checkConnectionsConsistency(),yield this.sqliteConnection.closeAllConnections(),this.connection=yield this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1),yield this.connection.open(),this.ready.resolve(!0)}))}query(t){return e.__awaiter(this,arguments,void 0,(function*({sql:e,params:t}){var i;yield this.ready;const n=yield this.db.query(e,t).then((e=>e.values||[]));return this.debug&&(console.groupCollapsed(`💾 SQL: ${e.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30)}...`),console.debug(e,t,n),console.groupEnd(),yield null===(i=this.sqliteConnection)||void 0===i?void 0:i.saveToStore(this.name)),n}))}export(){return e.__awaiter(this,void 0,void 0,(function*(){if(this.isWeb){const{name:e}=this;return new Promise((t=>{indexedDB.open("jeepSqliteStore").onsuccess=function(i){i.target.result.transaction(["databases"],"readwrite").objectStore("databases").get(`${e}SQLite.db`).onsuccess=function(e){const i=new Blob([e.target.result],{type:"application/vnd.sqlite3"});t(i)}}}))}const{url:e}=yield this.db.getUrl();return(yield fetch(n.Capacitor.convertFileSrc(e))).blob()}))}import(t){return e.__awaiter(this,void 0,void 0,(function*(){if(this.isWeb){const e=new Uint8Array(yield t.arrayBuffer()),{name:i}=this;return void new Promise((t=>{indexedDB.open("jeepSqliteStore").onsuccess=function(n){n.target.result.transaction(["databases"],"readwrite").objectStore("databases").put(e,`${i}SQLite.db`,0).onsuccess=()=>t()}}))}const{url:e}=yield this.db.getUrl(),i=yield new Promise((e=>{const i=new FileReader;i.onload=e,i.readAsDataURL(t)})).then((e=>e.target.result));yield o.Filesystem.writeFile({path:e,data:i})}))}};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("drizzle-orm"),r=require("drizzle-orm/casing"),n=require("drizzle-orm/sqlite-core"),i=require("@flumens/utils"),a=require("./utils.js");function s(r,n){var i=e.getTableColumns(r);return Object.entries(i).filter((function(t){var e=t[0];return!n.includes(e)})).reduce((function(r,n){var i,a=n[0],s=n[1];return t.__assign(t.__assign({},r),((i={})[a]=e.sql.raw("excluded.".concat(s.name)),i))}),{})}var o=function(t){return n.customType({dataType:function(){return"jsonb"},toDriver:function(t){return JSON.stringify(t)}})(t)},u=new n.SQLiteSyncDialect,c=function(){return{id:n.text(),cid:n.text().primaryKey().notNull().default("id"),data:o("data").notNull(),createdAt:n.integer("created_at").notNull(),updatedAt:n.integer("updated_at").notNull(),syncedAt:n.integer("synced_at")}},d=function(){function o(t){var e=t.db,r=t.name,a=t.debug,s=t.columns,o=void 0===s?c():s;this.ready=new i.Deferred,this.db=e,this.name=r,this.debug=a||!1,this.table=n.sqliteTable(this.name,o),this.init()}return o.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.db.ready];case 1:return t.sent(),e=function(t){return"".concat(t.name," ").concat(t.getSQLType()).concat(t.primary?" primary key":"").concat(t.notNull?" not null":"").concat(t.default?" default ".concat(t.default):"")},r=n.getTableConfig(this.table).columns.map(e).join(",\n"),[4,this.db.query({sql:"CREATE TABLE IF NOT EXISTS ".concat(this.name," (").concat(r,");")})];case 2:return t.sent(),this.ready.resolve(!0),[2]}}))}))},o.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,i,o;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),(Array.isArray(e)?e.length:e)?this.debug&&e.cid?[4,this.find({cid:e.cid})]:[3,3]:[2];case 2:r=t.sent(),a.printDiff(r,e,e.cid,this.name),t.label=3;case 3:return i=new n.SQLiteInsertBuilder(this.table,{},u).values(e),(o=this._getPrimaryCol())&&(i=i.onConflictDoUpdate({target:o,set:s(this.table,[])})),[4,this.db.query(i.toSQL())];case 4:return t.sent(),[2]}}))}))},o.prototype.find=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t).limit(1);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r)).limit(1)}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a)).limit(1)},[4,this.findAll(n)];case 2:return[2,t.sent()[0]]}}))}))},o.prototype.findAll=function(i){return t.__awaiter(this,void 0,void 0,(function(){var a,s,o,u=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),a=(new n.QueryBuilder).select().from(this.table),i&&(a=i(a)),[4,this.db.query(a.toSQL())];case 2:return s=t.sent(),o=function(t){return Object.entries(t).reduce((function(t,n){var i,a=n[0],s=n[1],o="jsonb"===(null===(i=e.getTableColumns(u.table)[a])||void 0===i?void 0:i.sqlName);return t[r.toCamelCase(a)]=o?JSON.parse(s):s,t}),{})},[2,s.map(o)]}}))}))},o.prototype.delete=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r))}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a))},[4,this.deleteAll(n)];case 2:return t.sent(),[2]}}))}))},o.prototype.deleteAll=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=new n.SQLiteDeleteBase(this.table,{},u),e&&(r=e(r)),[4,this.db.query(r.toSQL())];case 2:return t.sent(),[2]}}))}))},o.prototype.export=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(r){switch(r.label){case 0:return[4,this.ready];case 1:return r.sent(),e=function(e,r){var n;return t.__assign(t.__assign({},e),((n={})[r.cid]=r,n))},[4,this.findAll()];case 2:return[2,r.sent().reduce(e,{})]}}))}))},o.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i=this;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,this.ready];case 1:return a.sent(),[4,this.deleteAll()];case 2:if(a.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return r=function(e){var r,n,i,a,s,o;if(!e.createdAt&&(null===(r=e.metadata)||void 0===r?void 0:r.createdOn)&&(e.createdAt=null===(n=e.metadata)||void 0===n?void 0:n.createdOn),!e.updatedAt&&(null===(i=e.metadata)||void 0===i?void 0:i.updatedOn)&&(e.updatedAt=null===(a=e.metadata)||void 0===a?void 0:a.updatedOn),!e.syncedAt&&(null===(s=e.metadata)||void 0===s?void 0:s.syncedOn)&&(e.syncedAt=null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),e.samples){var u=e.id,c=e.cid,d=e.createdAt,l=e.updatedAt,f=e.syncedAt,h=t.__rest(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:u,cid:c,createdAt:d,updatedAt:l,syncedAt:f,data:t.__assign({},h)}}return e},n=Object.entries(e).map((function(t){var e=t[1];return i.save(r(e))})),Promise.all(n),[2]}}))}))},o.prototype._getPrimaryCol=function(){return Object.values(e.getTableColumns(this.table)).find((function(t){return!!t.primary}))},o}();exports.conflictUpdateAllExcept=s,exports.default=d,exports.defaultCols=c,exports.jsonb=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("drizzle-orm"),i=require("drizzle-orm/casing"),r=require("drizzle-orm/sqlite-core"),d=require("@flumens/utils"),n=require("./utils.js");function a(e,i){const r=t.getTableColumns(e);return Object.entries(r).filter((([e])=>!i.includes(e))).reduce(((e,[i,r])=>Object.assign(Object.assign({},e),{[i]:t.sql.raw(`excluded.${r.name}`)})),{})}const s=e=>r.customType({dataType:()=>"jsonb",toDriver:e=>JSON.stringify(e)})(e),l=new r.SQLiteSyncDialect,o=()=>({id:r.text(),cid:r.text().primaryKey().notNull().default("id"),data:s("data").notNull(),createdAt:r.integer("created_at").notNull(),updatedAt:r.integer("updated_at").notNull(),syncedAt:r.integer("synced_at")});exports.conflictUpdateAllExcept=a,exports.default=class{constructor({db:e,name:t,debug:i,columns:n=o()}){this.ready=new d.Deferred,this.db=e,this.name=t,this.debug=i||!1,this.table=r.sqliteTable(this.name,n),this.init()}init(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.db.ready;const e=r.getTableConfig(this.table).columns.map((e=>`${e.name} ${e.getSQLType()}${e.primary?" primary key":""}${e.notNull?" not null":""}${e.default?` default ${e.default}`:""}`)).join(",\n");yield this.db.query({sql:`CREATE TABLE IF NOT EXISTS ${this.name} (${e});`}),this.ready.resolve(!0)}))}save(t){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;if(!(Array.isArray(t)?t.length:t))return;if(this.debug&&t.cid){const e=yield this.find({cid:t.cid});n.printDiff(e,t,t.cid,this.name)}let e=new r.SQLiteInsertBuilder(this.table,{},l).values(t);const i=this._getPrimaryCol();i&&(e=e.onConflictDoUpdate({target:i,set:a(this.table,[])})),yield this.db.query(e.toSQL())}))}find(i){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;const[e]=yield this.findAll((e=>{if("function"==typeof i)return i(e).limit(1);if("string"==typeof i){const r=this._getPrimaryCol();if(!r)throw new Error("Primary col is missing");return e.where(t.eq(r,i)).limit(1)}const r=Object.entries(i).map((([e,i])=>t.eq(this.table[e],i)));return e.where(t.and(...r)).limit(1)}));return e}))}findAll(d){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;let e=(new r.QueryBuilder).select().from(this.table);d&&(e=d(e));return(yield this.db.query(e.toSQL())).map((e=>Object.entries(e).reduce(((e,[r,d])=>{var n;const a="jsonb"===(null===(n=t.getTableColumns(this.table)[r])||void 0===n?void 0:n.sqlName);return e[i.toCamelCase(r)]=a?JSON.parse(d):d,e}),{})))}))}delete(i){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;yield this.deleteAll((e=>{if("function"==typeof i)return i(e);if("string"==typeof i){const r=this._getPrimaryCol();if(!r)throw new Error("Primary col is missing");return e.where(t.eq(r,i))}const r=Object.entries(i).map((([e,i])=>t.eq(this.table[e],i)));return e.where(t.and(...r))}))}))}deleteAll(t){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;let e=new r.SQLiteDeleteBase(this.table,{},l);t&&(e=t(e)),yield this.db.query(e.toSQL())}))}export(){return e.__awaiter(this,void 0,void 0,(function*(){yield this.ready;return(yield this.findAll()).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.cid]:t})),{})}))}import(t){return e.__awaiter(this,void 0,void 0,(function*(){if(yield this.ready,yield this.deleteAll(),"object"!=typeof t)throw new Error("Invalid obj passed to store");const i=Object.entries(t).map((([,t])=>this.save((t=>{var i,r,d,n,a,s;if(!t.createdAt&&(null===(i=t.metadata)||void 0===i?void 0:i.createdOn)&&(t.createdAt=null===(r=t.metadata)||void 0===r?void 0:r.createdOn),!t.updatedAt&&(null===(d=t.metadata)||void 0===d?void 0:d.updatedOn)&&(t.updatedAt=null===(n=t.metadata)||void 0===n?void 0:n.updatedOn),!t.syncedAt&&(null===(a=t.metadata)||void 0===a?void 0:a.syncedOn)&&(t.syncedAt=null===(s=t.metadata)||void 0===s?void 0:s.syncedOn),t.samples){const{id:i,cid:r,createdAt:d,updatedAt:n,syncedAt:a}=t,s=e.__rest(t,["id","cid","createdAt","updatedAt","syncedAt"]);t={id:i,cid:r,createdAt:d,updatedAt:n,syncedAt:a,data:Object.assign({},s)}}return t})(t))));Promise.all(i)}))}_getPrimaryCol(){return Object.values(t.getTableColumns(this.table)).find((({primary:e})=>!!e))}},exports.defaultCols=o,exports.jsonb=s;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=function(){};exports.default=e;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.default=class{};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var o=require("deep-diff"),r=require("lodash");exports.printDiff=function(e,n,c,t){void 0===t&&(t="");var a=o.diff(e,n);if(a){var i={},l=0,s="";if(a.forEach((function(o){var e,n,a=((e={})[t]=((n={})[c]={},n),e);if(!o.path)return a[t][c]=o.rhs,console.groupCollapsed( + ".concat(c)),console.log(a),void console.groupEnd();o.path.reduce((function(r,e,n){if(o.path.length-1>n)return r[e]={},r[e];var c=JSON.stringify(o.lhs,null,2),t=JSON.stringify(o.rhs,null,2);if(c===t)return r[e];l++,r[e]="".concat(c," -> ").concat(t),s="".concat(e,": ").concat(c," -> ").concat(t)}),a[t][c]),i=r.merge(i,a)})),l){var f="Δ ".concat(c);1===l&&(f+=" ".concat(s)),console.groupCollapsed(f),console.log(i),console.groupEnd()}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("deep-diff"),o=require("lodash");exports.printDiff=function(r,n,l,t=""){const s=e.diff(r,n);if(!s)return;let i={},u=0,f="";if(s.forEach((e=>{const r={[t]:{[l]:{}}};if(!e.path)return r[t][l]=e.rhs,console.groupCollapsed( + ${l}`),console.log(r),void console.groupEnd();e.path.reduce(((o,r,n)=>{if(e.path.length-1>n)return o[r]={},o[r];const l=JSON.stringify(e.lhs,null,2),t=JSON.stringify(e.rhs,null,2);if(l===t)return o[r];u++,o[r]=`${l} -> ${t}`,f=`${r}: ${l} -> ${t}`}),r[t][l]),i=o.merge(i,r)})),u){let e=`Δ ${l}`;1===u&&(e+=` ${f}`),console.groupCollapsed(e),console.log(i),console.groupEnd()}};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.12.0",
3
+ "version": "0.12.1",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {