@flumens/models 0.12.1 → 0.12.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.
package/dist/Indicia/Sample.js
CHANGED
|
@@ -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=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
|
+
"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.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("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{
|
|
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{let i;try{i=yield n.getMigratableDbList(t?"Library/LocalDatabase":void 0)}catch(e){console.log("SQLite: err",e.message)}if(!(null===(e=null==i?void 0: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})}))}};
|