@flumens/models 0.17.2 → 0.18.0

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"),o=require("axios"),i=require("zod"),r=require("@flumens/utils/dist/errors"),n=require("@flumens/utils/dist/uuid"),s=require("../Model.js"),a=require("./helpers.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=l(o);const u=i.object({id:i.z.string(),title:i.z.string(),createdOn:i.z.string(),description:i.z.string().nullable().optional(),groupType:i.z.string().nullable().optional(),joiningMethod:i.z.enum(["P","R","A","I"]).nullable().optional(),websiteId:i.z.string().nullable().optional(),groupTypeId:i.z.string().nullable().optional(),createdById:i.z.string().nullable().optional(),fromDate:i.z.string().nullable().optional(),toDate:i.z.string().nullable().optional(),indexedLocationIds:i.z.array(i.z.number()).nullable().optional(),userIsAdministrator:i.z.enum(["t","f"]).nullable().optional(),userIsMember:i.z.enum(["t","f"]).nullable().optional(),userIsPending:i.z.enum(["t","f"]).nullable().optional()}),c=i.object({id:i.z.string().nullable().optional(),createdOn:i.z.string().nullable().optional(),createdById:i.z.string().nullable().optional(),groupId:i.z.string().nullable().optional(),groupTitle:i.z.string().nullable().optional(),locationId:i.z.string(),locationName:i.z.string(),locationBoundaryGeom:i.z.string(),locationLat:i.z.string(),locationLon:i.z.string(),locationCreatedOn:i.z.string(),locationUpdatedOn:i.z.string(),locationCentroidSref:i.z.string(),locationCentroidSrefSystem:i.z.string(),locationCode:i.z.string().nullable().optional(),locationCreatedById:i.z.string().nullable().optional(),locationUpdatedById:i.z.string().nullable().optional(),locationComment:i.z.string().nullable().optional(),locationExternalKey:i.z.string().nullable().optional()});class g extends s.default{static fromDTO(t,o={}){u.parse(t);const{id:i,createdOn:r}=t,s=e.__rest(t,["id","createdOn"]);return new this(Object.assign({id:i,cid:n.UUIDv7(),data:s,createdAt:new Date(r).getTime()},o))}constructor(o){var{skipStore:i,store:r,url:n,getAccessToken:s,getIndiciaUserId:a}=o,l=e.__rest(o,["skipStore","store","url","getAccessToken","getIndiciaUserId"]);super(Object.assign(Object.assign({},l),{store:i?void 0:r})),this.remote=t.observable({synchronising:!1,url:n,getAccessToken:s,getIndiciaUserId:a})}join(){return e.__awaiter(this,void 0,void 0,(function*(){const e=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users`,t=yield this.remote.getAccessToken(),o={values:{id:yield this.remote.getIndiciaUserId()}},i={headers:{Authorization:`Bearer ${t}`},timeout:8e4};try{yield d.default.post(e,o,i)}catch(e){if(d.default.isCancel(e))return;if(r.isAxiosNetworkError(e))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");throw e}}))}leave(){return e.__awaiter(this,void 0,void 0,(function*(){var e,t,o;const i=yield this.remote.getIndiciaUserId(),n=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users/${i}`,s={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{yield d.default.delete(n,s)}catch(i){if(d.default.isCancel(i))return;if(r.isAxiosNetworkError(i))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");if(null===(o=null===(t=null===(e=i.response)||void 0===e?void 0:e.data)||void 0===t?void 0:t.message)||void 0===o?void 0:o.includes("User is not a member of the group"))return;throw i}}))}addRemoteLocation(t){return e.__awaiter(this,void 0,void 0,(function*(){var e,o,i;console.log("Group location uploading");const r={values:{id:t}},n=`${this.remote.url}/index.php/services/rest/groups/${this.id}/locations`;try{this.remote.synchronising=!0;const e={url:n,method:"post",headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4,data:r};return yield d.default(e),this.remote.synchronising=!1,console.log("Group location uploading done"),this}catch(t){this.remote.synchronising=!1;const r=t;if(409===(null===(e=r.response)||void 0===e?void 0:e.status))return console.log("Location uploading duplicate was found"),this;const n=null===(i=null===(o=r.response)||void 0===o?void 0:o.data)||void 0===i?void 0:i.message;if(!n)throw t;if("object"==typeof n){const e=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),"");throw new Error(e(n))}throw new Error(n)}}))}fetchRemoteLocations(){return e.__awaiter(this,void 0,void 0,(function*(){const e=`${this.remote.url}/index.php/services/rest/groups/${this.id}/locations`,t={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{const o=yield d.default.get(e,t),i=({values:e})=>a.getCamelCaseObj(e),r=o.data.map(i);return r.forEach((e=>c.parse(e))),r}catch(e){if(d.default.isCancel(e))return[];if(r.isAxiosNetworkError(e))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in e){throw new Error(e.issues.map((e=>`${e.path.join(" ")} ${e.message}`)).join(" "))}throw e}}))}}exports.default=g,exports.dtoSchema=u;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),o=require("axios"),i=require("zod"),r=require("@flumens/utils"),n=require("@flumens/utils/dist/errors"),s=require("@flumens/utils/dist/uuid"),a=require("../Model.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=l(o);const d=i.object({id:i.z.string(),title:i.z.string(),createdOn:i.z.string(),description:i.z.string().nullable().optional(),groupType:i.z.string().nullable().optional(),joiningMethod:i.z.enum(["P","R","A","I"]).nullable().optional(),websiteId:i.z.string().nullable().optional(),groupTypeId:i.z.string().nullable().optional(),createdById:i.z.string().nullable().optional(),fromDate:i.z.string().nullable().optional(),toDate:i.z.string().nullable().optional(),indexedLocationIds:i.z.array(i.z.number()).nullable().optional(),userIsAdministrator:i.z.enum(["t","f"]).nullable().optional(),userIsMember:i.z.enum(["t","f"]).nullable().optional(),userIsPending:i.z.enum(["t","f"]).nullable().optional()}),c=i.object({id:i.z.string().nullable().optional(),createdOn:i.z.string().nullable().optional(),createdById:i.z.string().nullable().optional(),groupId:i.z.string().nullable().optional(),groupTitle:i.z.string().nullable().optional(),locationId:i.z.string(),locationName:i.z.string(),locationBoundaryGeom:i.z.string(),locationLat:i.z.string(),locationLon:i.z.string(),locationCreatedOn:i.z.string(),locationUpdatedOn:i.z.string(),locationCentroidSref:i.z.string(),locationCentroidSrefSystem:i.z.string(),locationCode:i.z.string().nullable().optional(),locationCreatedById:i.z.string().nullable().optional(),locationUpdatedById:i.z.string().nullable().optional(),locationComment:i.z.string().nullable().optional(),locationExternalKey:i.z.string().nullable().optional()});class g extends a.default{static fromDTO(t,o={}){d.parse(t);const{id:i,createdOn:r}=t,n=e.__rest(t,["id","createdOn"]);return new this(Object.assign({id:i,cid:s.UUIDv7(),data:n,createdAt:new Date(r).getTime()},o))}constructor(o){var{skipStore:i,store:r,url:n,getAccessToken:s,getIndiciaUserId:a}=o,l=e.__rest(o,["skipStore","store","url","getAccessToken","getIndiciaUserId"]);super(Object.assign(Object.assign({},l),{store:i?void 0:r})),this.remote=t.observable({synchronising:!1,url:n,getAccessToken:s,getIndiciaUserId:a})}join(){return e.__awaiter(this,void 0,void 0,(function*(){const e=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users`,t=yield this.remote.getAccessToken(),o={values:{id:yield this.remote.getIndiciaUserId()}},i={headers:{Authorization:`Bearer ${t}`},timeout:8e4};try{yield u.default.post(e,o,i)}catch(e){if(u.default.isCancel(e))return;if(n.isAxiosNetworkError(e))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");throw e}}))}leave(){return e.__awaiter(this,void 0,void 0,(function*(){var e,t,o;const i=yield this.remote.getIndiciaUserId(),r=`${this.remote.url}/index.php/services/rest/groups/${this.id}/users/${i}`,s={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{yield u.default.delete(r,s)}catch(i){if(u.default.isCancel(i))return;if(n.isAxiosNetworkError(i))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(null===(o=null===(t=null===(e=i.response)||void 0===e?void 0:e.data)||void 0===t?void 0:t.message)||void 0===o?void 0:o.includes("User is not a member of the group"))return;throw i}}))}addRemoteLocation(t){return e.__awaiter(this,void 0,void 0,(function*(){var e,o,i;console.log("Group location uploading");const r={values:{id:t}},n=`${this.remote.url}/index.php/services/rest/groups/${this.id}/locations`;try{this.remote.synchronising=!0;const e={url:n,method:"post",headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4,data:r};return yield u.default(e),this.remote.synchronising=!1,console.log("Group location uploading done"),this}catch(t){this.remote.synchronising=!1;const r=t;if(409===(null===(e=r.response)||void 0===e?void 0:e.status))return console.log("Location uploading duplicate was found"),this;const n=null===(i=null===(o=r.response)||void 0===o?void 0:o.data)||void 0===i?void 0:i.message;if(!n)throw t;if("object"==typeof n){const e=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),"");throw new Error(e(n))}throw new Error(n)}}))}fetchRemoteLocations(){return e.__awaiter(this,void 0,void 0,(function*(){const e=`${this.remote.url}/index.php/services/rest/groups/${this.id}/locations`,t={headers:{Authorization:`Bearer ${yield this.remote.getAccessToken()}`},timeout:8e4};try{const o=yield u.default.get(e,t),i=({values:e})=>r.getCamelCaseObj(e),n=o.data.map(i);return n.forEach((e=>c.parse(e))),n}catch(e){if(u.default.isCancel(e))return[];if(n.isAxiosNetworkError(e))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in e){throw new Error(e.issues.map((e=>`${e.path.join(" ")} ${e.message}`)).join(" "))}throw e}}))}}exports.default=g,exports.dtoSchema=d;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),i=require("@flumens/utils/dist/errors"),r=require("../Collection.js"),o=require("./Group.js"),a=require("./helpers.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=n(s);class d extends r.default{constructor(e){super(Object.assign({id:"groups",Model:o.default},e)),this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken})}fetchRemote(){return e.__awaiter(this,arguments,void 0,(function*(e={}){console.log(`📚 Collection: ${this.id} collection fetching`),this.remote.synchronising=!0;try{const{type:t,form:s,location:i}=e,r=yield this.remote.getAccessToken(),o=`${this.remote.url}/index.php/services/rest/groups`,n={};t&&(n.view=t),s&&(n.page=s.join(",")),Number.isFinite(i)&&(n.indexed_location_ids=i);const d={params:n,headers:{Authorization:`Bearer ${r}`},timeout:8e4},u=yield l.default.get(o,d),c=e=>!e.toDate||new Date(e.toDate)>new Date,h=e=>!e.fromDate||new Date(e.fromDate)<new Date,m=u.data.map((({values:e})=>e)).map(a.getCamelCaseObj).filter(c).filter(h),f=m.map((e=>this.Model.fromDTO(e,{skipStore:"joinable"===t})));if(t){if("member"===t)for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&"t"===t.data.userIsMember&&(yield t.destroy(),this.data.splice(e,1),e--)}else if("pending"===t)for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&"t"===t.data.userIsPending&&(yield t.destroy(),this.data.splice(e,1),e--)}else if("joinable"===t)for(let e=0;e<this.data.length;e++){this.data[e].isStored||(this.data.splice(e,1),e--)}}else for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&(yield t.destroy()),this.data.splice(e,1),e--}"member"===t&&(yield Promise.all(f.map((e=>e.save())))),"pending"===t&&(yield Promise.all(f.map((e=>e.save())))),this.data.push(...f),console.log(`📚 Collection: ${this.id} collection fetching done ${m.length} documents`)}catch(e){if(l.default.isCancel(e))return;if(i.isAxiosNetworkError(e))throw new i.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in e){throw new Error(e.issues.map((e=>`${e.path.join(" ")} ${e.message}`)).join(" "))}throw this.remote.synchronising=!1,e}this.remote.synchronising=!1}))}get isSynchronising(){return this.remote.synchronising}}exports.byGroupMembershipStatus=function(e){return t=>{const s=t.data.userIsMember||t.data.userIsPending;return"member"===e?s:!s}},exports.default=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),s=require("axios"),i=require("@flumens/utils"),r=require("@flumens/utils/dist/errors"),o=require("../Collection.js"),a=require("./Group.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=n(s);class d extends o.default{constructor(e){super(Object.assign({id:"groups",Model:a.default},e)),this.remote=t.observable({synchronising:!1,url:e.url,getAccessToken:e.getAccessToken})}fetchRemote(){return e.__awaiter(this,arguments,void 0,(function*(e={}){console.log(`📚 Collection: ${this.id} collection fetching`),this.remote.synchronising=!0;try{const{type:t,form:s,location:r}=e,o=yield this.remote.getAccessToken(),a=`${this.remote.url}/index.php/services/rest/groups`,n={};t&&(n.view=t),s&&(n.page=s.join(",")),Number.isFinite(r)&&(n.indexed_location_ids=r);const d={params:n,headers:{Authorization:`Bearer ${o}`},timeout:8e4},u=yield l.default.get(a,d),c=e=>!e.toDate||new Date(e.toDate)>new Date,h=e=>!e.fromDate||new Date(e.fromDate)<new Date,m=u.data.map((({values:e})=>e)).map(i.getCamelCaseObj).filter(c).filter(h),f=m.map((e=>this.Model.fromDTO(e,{skipStore:"joinable"===t})));if(t){if("member"===t)for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&"t"===t.data.userIsMember&&(yield t.destroy(),this.data.splice(e,1),e--)}else if("pending"===t)for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&"t"===t.data.userIsPending&&(yield t.destroy(),this.data.splice(e,1),e--)}else if("joinable"===t)for(let e=0;e<this.data.length;e++){this.data[e].isStored||(this.data.splice(e,1),e--)}}else for(let e=0;e<this.data.length;e++){const t=this.data[e];t.isStored&&(yield t.destroy()),this.data.splice(e,1),e--}"member"===t&&(yield Promise.all(f.map((e=>e.save())))),"pending"===t&&(yield Promise.all(f.map((e=>e.save())))),this.data.push(...f),console.log(`📚 Collection: ${this.id} collection fetching done ${m.length} documents`)}catch(e){if(l.default.isCancel(e))return;if(r.isAxiosNetworkError(e))throw new r.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in e){throw new Error(e.issues.map((e=>`${e.path.join(" ")} ${e.message}`)).join(" "))}throw this.remote.synchronising=!1,e}this.remote.synchronising=!1}))}get isSynchronising(){return this.remote.synchronising}}exports.byGroupMembershipStatus=function(e){return t=>{const s=t.data.userIsMember||t.data.userIsPending;return"member"===e?s:!s}},exports.default=d;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var 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
+ "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(),_=new Date(m.updated_on).getTime(),b=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:_,syncedAt:b,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:_,syncedAt:b,metadata:{verification:f},data:Object.assign(Object.assign({},g),{taxon:{warehouseId:parseInt(h.taxa_taxon_list_id,10),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;
@@ -23,7 +23,16 @@ interface RemoteAttr {
23
23
  id: string;
24
24
  }
25
25
  type AttrConfig = any;
26
- export declare const getCamelCaseObj: (dto: any) => import("lodash").Dictionary<any>;
26
+ /**
27
+ * A generic ElasticSearch response type.
28
+ */
29
+ export type ElasticSearchResponse<T> = {
30
+ hits: {
31
+ hits: {
32
+ _source: T;
33
+ }[];
34
+ };
35
+ };
27
36
  export declare const parseRemoteAttrs: (config: {
28
37
  [key: string]: AttrConfig;
29
38
  }, remoteAttrs: RemoteAttr[]) => any;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("lodash");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.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[i]=r,a=isNaN(t.value)?t.value:parseFloat(t.value);return e[i]=a,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},i=(this.samples||[]).reduce(r,{}),a=(this.occurrences||[]).reduce(r,{}),n=(this.media||[]).reduce(r,{});if(Object.keys(s).length||Object.keys(i).length||Object.keys(a).length||Object.keys(n).length){return{attributes:s,model:this,models:Object.assign(Object.assign(Object.assign({},i),a),n)}}return null};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getErrorMessageFromObject=e=>Object.entries(e).reduce(((e,t)=>`${e}${t[0]} ${t[1]}\n`),""),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[i]=r,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 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},i=(this.samples||[]).reduce(r,{}),n=(this.occurrences||[]).reduce(r,{}),o=(this.media||[]).reduce(r,{});if(Object.keys(s).length||Object.keys(i).length||Object.keys(n).length||Object.keys(o).length){return{attributes:s,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.17.2",
3
+ "version": "0.18.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {
@@ -9,6 +9,7 @@
9
9
  "test:eslint": "eslint src --quiet --ext .jsx --ext .ts --ext .tsx --ext .js && echo '\\033[37;42;1m PASS \\033[00m'",
10
10
  "prepare": "npm run build",
11
11
  "postpublish": "TAG_NAME=models-v\"$npm_package_version\" && git tag $TAG_NAME && git push origin \"$TAG_NAME\"",
12
+ "check": "npx tsc --noEmit --skipLibCheck && npm run test:eslint",
12
13
  "test": "jest --passWithNoTests",
13
14
  "test:watch": "jest --watchAll"
14
15
  },