@flumens/models 0.17.1 → 0.17.2

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"),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
+ "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:v,occurrence:p,taxon:h,identification:f}=t,y=new Date(m.created_on).getTime(),b=new Date(m.updated_on).getTime(),_=Date.now();let O=v.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==p?void 0:p.attributes)||[]),A=(null===(u=null==p?void 0:p.media)||void 0===u?void 0:u.map((({path:t})=>({id:t,createdAt:y,updatedAt:b,syncedAt:_,data:{data:`${e}/upload/${t}`}}))))||[],w=h.species||h.taxon_name,j=w!==h.taxon_name?h.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(h.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==p?void 0:p.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)=>{var i;return Object.assign(Object.assign({},e),{[a]:(null===(i=t[a])||void 0===i?void 0:i.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"),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=18e4;console.warn(JSON.stringify(e).substring(0,t))}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.id||!!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
+ "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=18e4;console.warn(JSON.stringify(e).substring(0,t))}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)=>{var i;return Object.assign(Object.assign({},t),{[s]:(null===(i=e[s])||void 0===i?void 0:i.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.id||!!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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.17.1",
3
+ "version": "0.17.2",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {