@flumens/models 0.12.2 → 0.12.4

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 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
+ "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.id||!!this.syncedAt}get isSynchronising(){return this.remote.synchronising}get isDraft(){return!this.id}}exports.default=c,exports.dtoSchema=l;
@@ -64,7 +64,7 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
64
64
  constructor({ metadata, ...options }?: Options);
65
65
  parent?: Sample | Occurrence;
66
66
  toJSON(): any;
67
- setupdatedAtTimestamp(newUpdatedAt: number): void;
67
+ setUpdatedAtTimestamp(newUpdatedAt: number): void;
68
68
  toDTO(warehouseMediaNames?: any): any;
69
69
  sync(): Promise<void>;
70
70
  uploadFile(force?: boolean): Promise<void>;
@@ -1 +1 @@
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
+ "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");require("lodash");var s=require("@flumens/utils/dist/image");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={}){const i=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)}));return i}static resize(e,t,i,a){const r=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}));return r}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,a=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)}));return a}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 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
+ "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,14 +1,5 @@
1
+ export { dataURItoBlob, isDataURL, getBlobFromURL, } from '@flumens/utils/dist/image';
1
2
  export declare const getErrorMessageFromObject: (errors: any) => string;
2
- /**
3
- * Converts DataURI object to a Blob.
4
- *
5
- * @param {type} dataURI
6
- * @param {type} fileType
7
- * @returns {undefined}
8
- */
9
- export declare function dataURItoBlob(dataURI: string, fileType: string): Blob;
10
- export declare function isDataURL(string: string): boolean;
11
- export declare function getBlobFromURL(url: string, mediaType: string): Promise<unknown>;
12
3
  export interface RemoteConfig {
13
4
  id?: number | string;
14
5
  values?: {
@@ -37,4 +28,3 @@ export declare const getCamelCaseObj: (dto: any) => import("lodash").Dictionary<
37
28
  export declare const parseRemoteAttrs: (config: {
38
29
  [key: string]: AttrConfig;
39
30
  }, remoteAttrs: RemoteAttr[]) => any;
40
- export {};
@@ -1 +1 @@
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};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("lodash"),t=require("@flumens/utils/dist/image");Object.defineProperty(exports,"dataURItoBlob",{enumerable:!0,get:function(){return t.dataURItoBlob}}),Object.defineProperty(exports,"getBlobFromURL",{enumerable:!0,get:function(){return t.getBlobFromURL}}),Object.defineProperty(exports,"isDataURL",{enumerable:!0,get:function(){return t.isDataURL}}),exports.getCamelCaseObj=t=>e.mapKeys(t,((t,r)=>e.camelCase(r))),exports.getErrorMessageFromObject=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""),exports.parseRemoteAttrs=(e,t)=>{e=e||{};const r=Object.entries(e);return t.reduce(((e,t)=>{const s=r.find((([,e])=>{var r;return(null===(r=e.remote)||void 0===r?void 0:r.id)===parseInt(t.id,10)}));if(!s)return e;const[i]=s,n=isNaN(t.value)?t.value:parseFloat(t.value);return e[i]=n,e}),{})},exports.validateRemoteModel=function(){const e=this.getSurvey(),t=e.verify&&e.verify(this.data,this);let r={};if(t){const e=t&&"issues"in t;!("ValidationError"===(null==t?void 0:t.name)||"ValidationError"===(null==t?void 0:t.type))&&!e?r.errors=[t.message]:e?r.errors=t.issues.map((({message:e})=>e)):r=Object.assign({},t)}const s=(e,t)=>{const r=t.validateRemote();return r&&(e[t.cid]=r,e[t.cid].model=t),e},i=(this.samples||[]).reduce(s,{}),n=(this.occurrences||[]).reduce(s,{}),o=(this.media||[]).reduce(s,{});if(Object.keys(r).length||Object.keys(i).length||Object.keys(n).length||Object.keys(o).length){return{attributes:r,model:this,models:Object.assign(Object.assign(Object.assign({},i),n),o)}}return null};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.12.2",
3
+ "version": "0.12.4",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {