@flumens/models 0.10.0 → 0.11.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,19 +1,23 @@
1
1
  import { Deferred } from '@flumens/utils';
2
2
  import ModelClass from './Model';
3
3
  import Store from './Stores/Store';
4
- interface ObservableArrayI<T> extends Array<T> {
5
- new (...items: any[]): ObservableArrayI<any>;
6
- name: string;
4
+ interface IObservableArray<T = any> extends Array<T> {
5
+ spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[];
6
+ clear(): T[];
7
+ replace(newItems: T[]): T[];
8
+ remove(value: T): boolean;
9
+ toJSON(): T[];
7
10
  }
8
- declare const ObservableArray: ObservableArrayI<any>;
11
+ type CID = string | number;
12
+ type ID = string | number;
9
13
  export type Options<T extends ModelClass> = {
10
- models?: T[];
14
+ data?: T[];
11
15
  id?: string;
12
16
  cid?: string;
13
17
  store?: Store;
14
18
  Model?: any;
15
19
  };
16
- export default class Collection<T extends ModelClass> extends ObservableArray {
20
+ export default class Collection<T extends ModelClass> {
17
21
  /**
18
22
  * Remote server collection ID.
19
23
  */
@@ -22,6 +26,12 @@ export default class Collection<T extends ModelClass> extends ObservableArray {
22
26
  * Key name of the collection used to save and fetch the model from locally.
23
27
  */
24
28
  cid?: string;
29
+ /**
30
+ * Mobx observable array of model items.
31
+ */
32
+ data: IObservableArray<T>;
33
+ cidMap: Map<CID, T>;
34
+ idMap: Map<ID, T>;
25
35
  /**
26
36
  * The offline store used to save and fetch the model from.
27
37
  */
@@ -30,14 +40,17 @@ export default class Collection<T extends ModelClass> extends ObservableArray {
30
40
  * A promise to flag if all the models were initialised from the store.
31
41
  */
32
42
  readonly ready: Deferred<boolean>;
33
- readonly Model: new (args: any) => T;
34
- constructor({ id, cid, models, store, Model }: Options<T>);
35
- fetch: () => Promise<void>;
36
- reset: () => Promise<void>;
37
- spliceWithArray(...args: any): T[];
38
- clear(): T[];
39
- replace(...args: any): T[];
40
- remove(...args: any): boolean;
41
- toJSON(): T[];
43
+ Model: new (args: any) => T;
44
+ constructor({ id, cid, data, store, Model }: Options<T>);
45
+ fetch(): Promise<void>;
46
+ reset(): Promise<void>;
47
+ filter(predicate: (value: T, index: number, array: T[]) => any): T[];
48
+ push(...items: T[]): number;
49
+ pop(): T | undefined;
50
+ find(predicate: (value: T, index: number, obj: T[]) => unknown): T | undefined;
51
+ map<U>(callbackfn: (value: T, index: number, array: T[]) => U): U[];
52
+ remove(value: T): boolean;
53
+ [Symbol.iterator](): ArrayIterator<T>;
54
+ get length(): number;
42
55
  }
43
56
  export {};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("@flumens/utils"),i=require("./Model.js"),n=function(t){function n(n){var o=n.id,s=n.cid,u=n.models,a=void 0===u?[]:u,l=n.store,c=n.Model,p=void 0===c?i.default:c,h=t.apply(this,a)||this;return h.ready=new r.Deferred,h.fetch=function(){return e.__awaiter(h,void 0,void 0,(function(){var t,r,i,n=this;return e.__generator(this,(function(e){switch(e.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=e.sent(),r=function(e){return new n.Model(e)},i=t.map(r),this.push.apply(this,i),this.ready.resolve(!0),[2]}}))}))},h.reset=function(){return e.__awaiter(h,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return this.length?[4,this.pop().destroy()]:[3,2];case 1:return e.sent(),[3,0];case 2:return[2]}}))}))},h.id=h.id||o,h.cid=h.cid||s||o||r.UUIDv7(),h.Model=p,h.store=h.store||l,h}return e.__extends(n,t),n.prototype.spliceWithArray=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).spliceWithArray.apply(e,t)},n.prototype.clear=function(){return this.clear()},n.prototype.replace=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).replace.apply(e,t)},n.prototype.remove=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).remove.apply(e,t)},n.prototype.toJSON=function(){return this.toJSON()},n}((function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return t.observable(e)}));exports.default=n;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("@flumens/utils"),i=require("./Model.js"),n=function(){function n(t){var n=t.id,o=t.cid,a=t.data,d=void 0===a?[]:a,s=t.store,u=t.Model,p=void 0===u?i.default:u,h=this;this.ready=new r.Deferred,this.data=e.observable.array(d),this.id=this.id||n,this.cid=this.cid||o||n||r.UUIDv7(),this.Model=p,this.store=this.store||s,this.cidMap=new Map,this.idMap=new Map;e.intercept(this.data,(function(t){if(t.added&&t.added.length){t.added.forEach((function(t){h.cidMap.set(t.cid,t),h.idMap.set(t.id,t)}))}if(t.removedCount>0){var e=Array.from(h.cidMap.keys())[t.index];h.cidMap.delete(e),e=Array.from(h.idMap.keys())[t.index],h.idMap.delete(e)}return t}))}return n.prototype.fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r,i,n,o=this;return t.__generator(this,(function(t){switch(t.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return e=t.sent(),r=function(t){return new o.Model(t)},i=e.map(r),(n=this.data).push.apply(n,i),this.ready.resolve(!0),[2]}}))}))},n.prototype.reset=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:return this.data.length?[4,null==(e=this.data.pop())?void 0:e.destroy()]:[3,2];case 1:return t.sent(),[3,0];case 2:return[2]}}))}))},n.prototype.filter=function(t){return this.data.filter(t)},n.prototype.push=function(){for(var t,e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return(t=this.data).push.apply(t,e)},n.prototype.pop=function(){return this.data.pop()},n.prototype.find=function(t){return this.data.find(t)},n.prototype.map=function(t){return this.data.map(t)},n.prototype.remove=function(t){return this.data.remove(t)},n.prototype[Symbol.iterator]=function(){return this.data[Symbol.iterator]()},Object.defineProperty(n.prototype,"length",{get:function(){return this.data.length},enumerable:!1,configurable:!0}),n}();exports.default=n;
@@ -98,7 +98,7 @@ export default class DrupalUserModel<T extends Data = Data> extends Model<T> {
98
98
  constructor({ config, ...options }: Options);
99
99
  logIn(email: string, password: string): Promise<void>;
100
100
  register(email: string, password: string, otherFields: any): Promise<void>;
101
- reset(email: string): Promise<void>;
101
+ resetPassword(email: string): Promise<void>;
102
102
  delete(): Promise<void>;
103
103
  /**
104
104
  * Gets full user profile inc. fresh new tokens.
@@ -110,7 +110,7 @@ export default class DrupalUserModel<T extends Data = Data> extends Model<T> {
110
110
  hasLogIn(): boolean;
111
111
  isLoggedIn(): boolean;
112
112
  logOut(): Promise<void>;
113
- resetDefaults(defaultsToSet?: any): Promise<void>;
113
+ reset(defaultsToSet?: any): Promise<void>;
114
114
  getAccessToken(forceRefresh?: boolean): Promise<string>;
115
115
  protected _sendVerificationEmail(email?: string): Promise<import("axios").AxiosResponse<any, any>>;
116
116
  private _exchangePasswordToTokens;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("zod"),i=require("@flumens/utils"),n=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=a(t);function c(e,t){Object.keys(t).forEach((function(r){if(r.match(/^field_/)){var s=r.replace("field_","").replace(/_([a-z])/g,(function(e){return e[1].toUpperCase()}));if(!t[r])return;if(Array.isArray(t[r])&&t[r].length)return void(e[s]=t[r][0].value);e[s]=t[r]}}))}var u=function(e){var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new i.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new i.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new i.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new i.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new i.HandledError("The user has not been activated or is blocked.");throw new Error(e.response.data.message)}if(null===(t=e.message)||void 0===t?void 0:t.includes("timeout"))throw new i.HandledError("Timeout");throw e},d=6e4;var h={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0},l=function(t){function i(r){var s=this,i=r.config,n=e.__rest(r,["config"]);return(s=t.call(this,e.__assign(e.__assign({},n),{data:e.__assign(e.__assign({},h),n.data)}))||this).config=i,s}return e.__extends(i,t),i.prototype.logIn=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this._exchangePasswordToTokens(t,r)];case 1:return s=e.sent(),this.data.tokens=s,[4,this.refreshProfile()];case 2:return e.sent(),[2,this.save()]}}))}))},i.prototype.register=function(t,r,s){return e.__awaiter(this,void 0,void 0,(function(){var n,a,h,l;return e.__generator(this,(function(f){switch(f.label){case 0:return n=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),a={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:n,timeout:d},[4,o.default(a).catch(u)];case 1:if(h=f.sent().data,!!i.registerSchemaBackend.safeParse(h).error)throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 2:return l=f.sent(),this.data.tokens=l,this.id=h.uid[0].value,this.data.email=t,c(this.data,h),[2,this.save()]}}))}))},i.prototype.reset=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,i;return e.__generator(this,(function(e){switch(e.label){case 0:r=JSON.stringify({mail:t}),s={method:"post",url:"".concat(this.config.url,"/user/password?_format=json"),headers:{"content-type":"application/json"},data:r},e.label=1;case 1:return e.trys.push([1,3,,6]),[4,o.default(s).catch(u)];case 2:return e.sent(),[3,6];case 3:return"The user has not been activated or is blocked."!==(i=e.sent()).message?[3,5]:[4,this._sendVerificationEmail(t)];case 4:return e.sent(),[2];case 5:return u(i),[3,6];case 6:return[2]}}))}))},i.prototype.delete=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),r={method:"delete",url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)}},[4,o.default(r).catch(u)];case 2:return e.sent(),this.logOut(),[2]}}))}))},i.prototype.refreshProfile=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,r,s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),this.data.verified?(r={url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)},timeout:d},[4,o.default(r).catch(u)]):[3,3];case 2:s=e.sent().data,this.data.email=s.mail[0].value,c(this.data,s),e.label=3;case 3:return[4,this.save()];case 4:return e.sent(),delete this._refreshingProfilePromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingProfilePromise,e}))),[2,this._refreshingProfilePromise]}))}))},i.prototype.hasLogIn=function(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()},i.prototype.isLoggedIn=function(){return this.data.email,!!this.id},i.prototype.logOut=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.resetDefaults()]}))}))},i.prototype.resetDefaults=function(r){return t.prototype.resetDefaults.call(this,e.__assign(e.__assign({},h),r))},i.prototype.getAccessToken=function(t){return e.__awaiter(this,void 0,void 0,(function(){var s,i,n,a,o;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");if(s=(this.data.tokens||{}).access_token,i=function(e){if(!e)return!0;var t=1e3*r.jwtDecode(e).exp;return Date.now()+12e4>t}(s),!(!s||i||t))return[3,6];e.label=1;case 1:return e.trys.push([1,3,,6]),[4,this._refreshAccessToken()];case 2:return e.sent(),[3,6];case 3:return n=e.sent(),console.error(n),a="The refresh token is invalid."===n.message,o="Token has no user email."===n.message,a||o?[4,this.logOut()]:[3,5];case 4:throw e.sent(),new Error("User re-login is required.");case 5:throw n;case 6:return[2,this.data.tokens.access_token]}}))}))},i.prototype._sendVerificationEmail=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s;return e.__generator(this,(function(e){return r=JSON.stringify({mail:[{value:t||this.data.email}]}),s={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json&resendVerificationEmail=true"),headers:{"content-type":"application/json"},data:r,timeout:d},[2,o.default(s).catch(u)]}))}))},i.prototype._exchangePasswordToTokens=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s,i,n;return e.__generator(this,(function(e){switch(e.label){case 0:return(s=new FormData).append("grant_type","password"),s.append("username",t),s.append("password",r),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),(null===(n=this.config.scopes)||void 0===n?void 0:n.length)&&s.append("scope",this.config.scopes.join(" ")),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s},[4,o.default(i).catch(u)];case 1:return[2,e.sent().data]}}))}))},i.prototype._refreshAccessToken=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(s){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,s,i,n,a,h;return e.__generator(this,(function(l){switch(l.label){case 0:if(!(t=(this.data.tokens||{}).refresh_token))throw new Error("No user session refresh token was found");return(s=new FormData).append("grant_type","refresh_token"),s.append("refresh_token",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s,timeout:d},[4,o.default(i).catch(u)];case 1:if(n=l.sent().data,this.data.tokens=e.__assign(e.__assign({},this.data.tokens),n),a=r.jwtDecode(null===(h=this.data.tokens)||void 0===h?void 0:h.access_token),this.id=a.sub,this.data.email=a.email,!this.data.email)throw new Error("Token has no user email.");return this.data.verified=a.email_verified,this.data.iss=a.iss,this.data.indiciaUserId=a["http://indicia.org.uk/user:id"],a.scopes&&(this.data.roles=a.scopes),c(this.data,a),[4,this.save()];case 2:return l.sent(),delete this._refreshingTokenPromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingTokenPromise,e}))),[2,this._refreshingTokenPromise]}))}))},i.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),i.resetSchema=s.object({email:s.z.string().email("Please fill in")}),i.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),i}(n.default);exports.default=l;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("zod"),i=require("@flumens/utils"),n=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=a(t);function c(e,t){Object.keys(t).forEach((function(r){if(r.match(/^field_/)){var s=r.replace("field_","").replace(/_([a-z])/g,(function(e){return e[1].toUpperCase()}));if(!t[r])return;if(Array.isArray(t[r])&&t[r].length)return void(e[s]=t[r][0].value);e[s]=t[r]}}))}var d=function(e){var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new i.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new i.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new i.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new i.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new i.HandledError("The user has not been activated or is blocked.");throw new Error(e.response.data.message)}if(null===(t=e.message)||void 0===t?void 0:t.includes("timeout"))throw new i.HandledError("Timeout");throw e},u=6e4;var h={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0},l=function(t){function i(r){var s=this,i=r.config,n=e.__rest(r,["config"]);return(s=t.call(this,e.__assign(e.__assign({},n),{data:e.__assign(e.__assign({},h),n.data)}))||this).config=i,s}return e.__extends(i,t),i.prototype.logIn=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this._exchangePasswordToTokens(t,r)];case 1:return s=e.sent(),this.data.tokens=s,[4,this.refreshProfile()];case 2:return e.sent(),[2,this.save()]}}))}))},i.prototype.register=function(t,r,s){return e.__awaiter(this,void 0,void 0,(function(){var n,a,h,l;return e.__generator(this,(function(f){switch(f.label){case 0:return n=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),a={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:n,timeout:u},[4,o.default(a).catch(d)];case 1:if(h=f.sent().data,!!i.registerSchemaBackend.safeParse(h).error)throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 2:return l=f.sent(),this.data.tokens=l,this.id=h.uid[0].value,this.data.email=t,c(this.data,h),[2,this.save()]}}))}))},i.prototype.resetPassword=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,i;return e.__generator(this,(function(e){switch(e.label){case 0:r=JSON.stringify({mail:t}),s={method:"post",url:"".concat(this.config.url,"/user/password?_format=json"),headers:{"content-type":"application/json"},data:r},e.label=1;case 1:return e.trys.push([1,3,,6]),[4,o.default(s).catch(d)];case 2:return e.sent(),[3,6];case 3:return"The user has not been activated or is blocked."!==(i=e.sent()).message?[3,5]:[4,this._sendVerificationEmail(t)];case 4:return e.sent(),[2];case 5:return d(i),[3,6];case 6:return[2]}}))}))},i.prototype.delete=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),r={method:"delete",url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)}},[4,o.default(r).catch(d)];case 2:return e.sent(),this.logOut(),[2]}}))}))},i.prototype.refreshProfile=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,r,s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),this.data.verified?(r={url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)},timeout:u},[4,o.default(r).catch(d)]):[3,3];case 2:s=e.sent().data,this.data.email=s.mail[0].value,c(this.data,s),e.label=3;case 3:return[4,this.save()];case 4:return e.sent(),delete this._refreshingProfilePromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingProfilePromise,e}))),[2,this._refreshingProfilePromise]}))}))},i.prototype.hasLogIn=function(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()},i.prototype.isLoggedIn=function(){return this.data.email,!!this.id},i.prototype.logOut=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.reset()]}))}))},i.prototype.reset=function(r){return t.prototype.reset.call(this,e.__assign(e.__assign({},h),r))},i.prototype.getAccessToken=function(t){return e.__awaiter(this,void 0,void 0,(function(){var s,i,n,a,o;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");if(s=(this.data.tokens||{}).access_token,i=function(e){if(!e)return!0;var t=1e3*r.jwtDecode(e).exp;return Date.now()+12e4>t}(s),!(!s||i||t))return[3,6];e.label=1;case 1:return e.trys.push([1,3,,6]),[4,this._refreshAccessToken()];case 2:return e.sent(),[3,6];case 3:return n=e.sent(),console.error(n),a="The refresh token is invalid."===n.message,o="Token has no user email."===n.message,a||o?[4,this.logOut()]:[3,5];case 4:throw e.sent(),new Error("User re-login is required.");case 5:throw n;case 6:return[2,this.data.tokens.access_token]}}))}))},i.prototype._sendVerificationEmail=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s;return e.__generator(this,(function(e){return r=JSON.stringify({mail:[{value:t||this.data.email}]}),s={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json&resendVerificationEmail=true"),headers:{"content-type":"application/json"},data:r,timeout:u},[2,o.default(s).catch(d)]}))}))},i.prototype._exchangePasswordToTokens=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s,i,n;return e.__generator(this,(function(e){switch(e.label){case 0:return(s=new FormData).append("grant_type","password"),s.append("username",t),s.append("password",r),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),(null===(n=this.config.scopes)||void 0===n?void 0:n.length)&&s.append("scope",this.config.scopes.join(" ")),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s},[4,o.default(i).catch(d)];case 1:return[2,e.sent().data]}}))}))},i.prototype._refreshAccessToken=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(s){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,s,i,n,a,h;return e.__generator(this,(function(l){switch(l.label){case 0:if(!(t=(this.data.tokens||{}).refresh_token))throw new Error("No user session refresh token was found");return(s=new FormData).append("grant_type","refresh_token"),s.append("refresh_token",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s,timeout:u},[4,o.default(i).catch(d)];case 1:if(n=l.sent().data,this.data.tokens=e.__assign(e.__assign({},this.data.tokens),n),a=r.jwtDecode(null===(h=this.data.tokens)||void 0===h?void 0:h.access_token),this.id=a.sub,this.data.email=a.email,!this.data.email)throw new Error("Token has no user email.");return this.data.verified=a.email_verified,this.data.iss=a.iss,this.data.indiciaUserId=a["http://indicia.org.uk/user:id"],a.scopes&&(this.data.roles=a.scopes),c(this.data,a),[4,this.save()];case 2:return l.sent(),delete this._refreshingTokenPromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingTokenPromise,e}))),[2,this._refreshingTokenPromise]}))}))},i.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),i.resetSchema=s.object({email:s.z.string().email("Please fill in")}),i.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),i}(n.default);exports.default=l;
@@ -0,0 +1,137 @@
1
+ import { z } from 'zod';
2
+ import Model, { Options as OptionsOriginal, Data as ModelData } from '../Model';
3
+ export declare const dtoSchema: z.ZodObject<{
4
+ id: z.ZodString;
5
+ title: z.ZodString;
6
+ createdOn: z.ZodString;
7
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
+ groupType: z.ZodOptional<z.ZodNullable<z.ZodString>>;
9
+ joiningMethod: z.ZodOptional<z.ZodNullable<z.ZodEnum<["P", "R", "A", "I"]>>>;
10
+ websiteId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
11
+ groupTypeId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
12
+ createdById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
13
+ fromDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
14
+ toDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
15
+ indexedLocationIds: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodNumber, "many">>>;
16
+ userIsAdministrator: z.ZodOptional<z.ZodNullable<z.ZodEnum<["t", "f"]>>>;
17
+ userIsMember: z.ZodOptional<z.ZodNullable<z.ZodEnum<["t", "f"]>>>;
18
+ userIsPending: z.ZodOptional<z.ZodNullable<z.ZodEnum<["t", "f"]>>>;
19
+ }, "strip", z.ZodTypeAny, {
20
+ id: string;
21
+ title: string;
22
+ createdOn: string;
23
+ description?: string | null | undefined;
24
+ groupType?: string | null | undefined;
25
+ joiningMethod?: "R" | "P" | "I" | "A" | null | undefined;
26
+ websiteId?: string | null | undefined;
27
+ groupTypeId?: string | null | undefined;
28
+ createdById?: string | null | undefined;
29
+ fromDate?: string | null | undefined;
30
+ toDate?: string | null | undefined;
31
+ indexedLocationIds?: number[] | null | undefined;
32
+ userIsAdministrator?: "t" | "f" | null | undefined;
33
+ userIsMember?: "t" | "f" | null | undefined;
34
+ userIsPending?: "t" | "f" | null | undefined;
35
+ }, {
36
+ id: string;
37
+ title: string;
38
+ createdOn: string;
39
+ description?: string | null | undefined;
40
+ groupType?: string | null | undefined;
41
+ joiningMethod?: "R" | "P" | "I" | "A" | null | undefined;
42
+ websiteId?: string | null | undefined;
43
+ groupTypeId?: string | null | undefined;
44
+ createdById?: string | null | undefined;
45
+ fromDate?: string | null | undefined;
46
+ toDate?: string | null | undefined;
47
+ indexedLocationIds?: number[] | null | undefined;
48
+ userIsAdministrator?: "t" | "f" | null | undefined;
49
+ userIsMember?: "t" | "f" | null | undefined;
50
+ userIsPending?: "t" | "f" | null | undefined;
51
+ }>;
52
+ declare const locationDTOSchema: z.ZodObject<{
53
+ id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
54
+ createdOn: z.ZodOptional<z.ZodNullable<z.ZodString>>;
55
+ createdById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
56
+ groupId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
57
+ groupTitle: z.ZodOptional<z.ZodNullable<z.ZodString>>;
58
+ locationId: z.ZodString;
59
+ locationName: z.ZodString;
60
+ locationBoundaryGeom: z.ZodString;
61
+ locationLat: z.ZodString;
62
+ locationLon: z.ZodString;
63
+ locationCreatedOn: z.ZodString;
64
+ locationUpdatedOn: z.ZodString;
65
+ locationCentroidSref: z.ZodString;
66
+ locationCentroidSrefSystem: z.ZodString;
67
+ locationCode: z.ZodOptional<z.ZodNullable<z.ZodString>>;
68
+ locationCreatedById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
69
+ locationUpdatedById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
70
+ locationComment: z.ZodOptional<z.ZodNullable<z.ZodString>>;
71
+ locationExternalKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
72
+ }, "strip", z.ZodTypeAny, {
73
+ locationId: string;
74
+ locationName: string;
75
+ locationBoundaryGeom: string;
76
+ locationLat: string;
77
+ locationLon: string;
78
+ locationCreatedOn: string;
79
+ locationUpdatedOn: string;
80
+ locationCentroidSref: string;
81
+ locationCentroidSrefSystem: string;
82
+ id?: string | null | undefined;
83
+ createdOn?: string | null | undefined;
84
+ createdById?: string | null | undefined;
85
+ groupId?: string | null | undefined;
86
+ groupTitle?: string | null | undefined;
87
+ locationCode?: string | null | undefined;
88
+ locationCreatedById?: string | null | undefined;
89
+ locationUpdatedById?: string | null | undefined;
90
+ locationComment?: string | null | undefined;
91
+ locationExternalKey?: string | null | undefined;
92
+ }, {
93
+ locationId: string;
94
+ locationName: string;
95
+ locationBoundaryGeom: string;
96
+ locationLat: string;
97
+ locationLon: string;
98
+ locationCreatedOn: string;
99
+ locationUpdatedOn: string;
100
+ locationCentroidSref: string;
101
+ locationCentroidSrefSystem: string;
102
+ id?: string | null | undefined;
103
+ createdOn?: string | null | undefined;
104
+ createdById?: string | null | undefined;
105
+ groupId?: string | null | undefined;
106
+ groupTitle?: string | null | undefined;
107
+ locationCode?: string | null | undefined;
108
+ locationCreatedById?: string | null | undefined;
109
+ locationUpdatedById?: string | null | undefined;
110
+ locationComment?: string | null | undefined;
111
+ locationExternalKey?: string | null | undefined;
112
+ }>;
113
+ type LocationDTO = z.infer<typeof locationDTOSchema>;
114
+ export type LocationData = LocationDTO;
115
+ export interface Options<T = any> extends OptionsOriginal<T> {
116
+ skipStore?: boolean;
117
+ url?: string;
118
+ getAccessToken?: () => Promise<string>;
119
+ getIndiciaUserId?: () => Promise<string | number>;
120
+ }
121
+ export type DTO = z.infer<typeof dtoSchema>;
122
+ export type Data = Omit<DTO, 'id' | 'createdOn'> & ModelData;
123
+ declare class Group<T extends Data = Data> extends Model<T> {
124
+ static fromDTO(dto: DTO, options?: Partial<Options>): Group;
125
+ protected remote: {
126
+ synchronising: boolean;
127
+ url?: string;
128
+ getAccessToken?: () => Promise<string>;
129
+ getIndiciaUserId?: () => Promise<string | number>;
130
+ };
131
+ constructor({ skipStore, store, url, getAccessToken, getIndiciaUserId, ...options }: Options);
132
+ join(): Promise<void>;
133
+ leave(): Promise<void>;
134
+ addRemoteLocation(locationId: string | number): Promise<this>;
135
+ fetchRemoteLocations(): Promise<LocationData[]>;
136
+ }
137
+ export default Group;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),n=require("zod"),o=require("@flumens/utils/dist/errors"),i=require("@flumens/utils/dist/uuid"),s=require("../Model.js"),a=require("./helpers.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=l(r),c=n.object({id:n.z.string(),title:n.z.string(),createdOn:n.z.string(),description:n.z.string().nullable().optional(),groupType:n.z.string().nullable().optional(),joiningMethod:n.z.enum(["P","R","A","I"]).nullable().optional(),websiteId:n.z.string().nullable().optional(),groupTypeId:n.z.string().nullable().optional(),createdById:n.z.string().nullable().optional(),fromDate:n.z.string().nullable().optional(),toDate:n.z.string().nullable().optional(),indexedLocationIds:n.z.array(n.z.number()).nullable().optional(),userIsAdministrator:n.z.enum(["t","f"]).nullable().optional(),userIsMember:n.z.enum(["t","f"]).nullable().optional(),userIsPending:n.z.enum(["t","f"]).nullable().optional()}),d=n.object({id:n.z.string().nullable().optional(),createdOn:n.z.string().nullable().optional(),createdById:n.z.string().nullable().optional(),groupId:n.z.string().nullable().optional(),groupTitle:n.z.string().nullable().optional(),locationId:n.z.string(),locationName:n.z.string(),locationBoundaryGeom:n.z.string(),locationLat:n.z.string(),locationLon:n.z.string(),locationCreatedOn:n.z.string(),locationUpdatedOn:n.z.string(),locationCentroidSref:n.z.string(),locationCentroidSrefSystem:n.z.string(),locationCode:n.z.string().nullable().optional(),locationCreatedById:n.z.string().nullable().optional(),locationUpdatedById:n.z.string().nullable().optional(),locationComment:n.z.string().nullable().optional(),locationExternalKey:n.z.string().nullable().optional()}),p=function(r){function n(n){var o=this,i=n.skipStore,s=n.store,a=n.url,l=n.getAccessToken,u=n.getIndiciaUserId,c=e.__rest(n,["skipStore","store","url","getAccessToken","getIndiciaUserId"]);return(o=r.call(this,e.__assign(e.__assign({},c),{store:i?void 0:s}))||this).remote=t.observable({synchronising:!1,url:a,getAccessToken:l,getIndiciaUserId:u}),o}return e.__extends(n,r),n.fromDTO=function(t,r){void 0===r&&(r={}),c.parse(t);var n=t.id,o=t.createdOn,s=e.__rest(t,["id","createdOn"]);return new this(e.__assign({id:n,cid:i.UUIDv7(),data:s,createdAt:new Date(o).getTime()},r))},n.prototype.join=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,i,s,a;return e.__generator(this,(function(e){switch(e.label){case 0:return t="".concat(this.remote.url,"/index.php/services/rest/groups/").concat(this.id,"/users"),[4,this.remote.getAccessToken()];case 1:return r=e.sent(),[4,this.remote.getIndiciaUserId()];case 2:n=e.sent(),i={values:{id:n}},s={headers:{Authorization:"Bearer ".concat(r)},timeout:8e4},e.label=3;case 3:return e.trys.push([3,5,,6]),[4,u.default.post(t,i,s)];case 4:return e.sent(),[3,6];case 5:if(a=e.sent(),u.default.isCancel(a))return[2];if(o.isAxiosNetworkError(a))throw new o.HandledError("Request aborted because of a network issue (timeout or similar).");throw a;case 6:return[2]}}))}))},n.prototype.leave=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,i,s,a,l,c;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.remote.getIndiciaUserId()];case 1:return t=e.sent(),r="".concat(this.remote.url,"/index.php/services/rest/groups/").concat(this.id,"/users/").concat(t),[4,this.remote.getAccessToken()];case 2:n=e.sent(),i={headers:{Authorization:"Bearer ".concat(n)},timeout:8e4},e.label=3;case 3:return e.trys.push([3,5,,6]),[4,u.default.delete(r,i)];case 4:return e.sent(),[3,6];case 5:if(s=e.sent(),u.default.isCancel(s))return[2];if(o.isAxiosNetworkError(s))throw new o.HandledError("Request aborted because of a network issue (timeout or similar).");if(null===(c=null===(l=null===(a=s.response)||void 0===a?void 0:a.data)||void 0===l?void 0:l.message)||void 0===c?void 0:c.includes("User is not a member of the group"))return[2];throw s;case 6:return[2]}}))}))},n.prototype.addRemoteLocation=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,n,o,i,s,a,l,c,d,p,g;return e.__generator(this,(function(e){switch(e.label){case 0:console.log("Group location uploading"),r={values:{id:t}},n="".concat(this.remote.url,"/index.php/services/rest/groups/").concat(this.id,"/locations"),e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this.remote.getAccessToken()];case 2:return o=e.sent(),i={url:n,method:"post",headers:{Authorization:"Bearer ".concat(o)},timeout:8e4,data:r},[4,u.default(i)];case 3:return e.sent(),this.remote.synchronising=!1,console.log("Group location uploading done"),[2,this];case 4:if(s=e.sent(),this.remote.synchronising=!1,409===(null===(d=(a=s).response)||void 0===d?void 0:d.status))return console.log("Location uploading duplicate was found"),[2,this];if(!(l=null===(g=null===(p=a.response)||void 0===p?void 0:p.data)||void 0===g?void 0:g.message))throw s;if("object"==typeof l)throw c=function(e){return Object.entries(e).reduce((function(e,t){return"".concat(e).concat(t[0]," ").concat(t[1],"\n")}),"")},new Error(c(l));throw new Error(l);case 5:return[2]}}))}))},n.prototype.fetchRemoteLocations=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,i,s,l,c;return e.__generator(this,(function(e){switch(e.label){case 0:return t="".concat(this.remote.url,"/index.php/services/rest/groups/").concat(this.id,"/locations"),[4,this.remote.getAccessToken()];case 1:r=e.sent(),n={headers:{Authorization:"Bearer ".concat(r)},timeout:8e4},e.label=2;case 2:return e.trys.push([2,4,,5]),[4,u.default.get(t,n)];case 3:return i=e.sent(),s=function(e){var t=e.values;return a.getCamelCaseObj(t)},(l=i.data.map(s)).forEach((function(e){return d.parse(e)})),[2,l];case 4:if(c=e.sent(),u.default.isCancel(c))return[2,[]];if(o.isAxiosNetworkError(c))throw new o.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in c)throw new Error(c.issues.map((function(e){return"".concat(e.path.join(" ")," ").concat(e.message)})).join(" "));throw c;case 5:return[2]}}))}))},n}(s.default);exports.default=p,exports.dtoSchema=c;
@@ -0,0 +1,23 @@
1
+ import Collection, { Options as BaseOptions } from '../Collection';
2
+ import Group from './Group';
3
+ export interface Options<T extends Group> extends BaseOptions<T> {
4
+ url?: string | null;
5
+ getAccessToken: () => Promise<string>;
6
+ }
7
+ type RemoteFetchParams = {
8
+ type?: 'member' | 'joinable';
9
+ form?: string[];
10
+ location?: number;
11
+ };
12
+ declare class GroupCollection<T extends Group> extends Collection<T> {
13
+ protected remote: {
14
+ synchronising: boolean;
15
+ url: string;
16
+ getAccessToken: () => Promise<string>;
17
+ };
18
+ constructor(options: Options<T>);
19
+ fetchRemote(params?: RemoteFetchParams): Promise<void>;
20
+ get isSynchronising(): boolean;
21
+ }
22
+ export declare function byGroupMembershipStatus(type: 'member' | 'joinable'): (group: Group) => boolean | "t" | "f" | null | undefined;
23
+ export default GroupCollection;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),n=require("@flumens/utils/dist/errors"),i=require("../Collection.js"),s=require("./Group.js"),o=require("./helpers.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=a(r),c=function(r){function i(n){var i=r.call(this,e.__assign({id:"groups",Model:s.default},n))||this;return i.remote=t.observable({synchronising:!1,url:n.url,getAccessToken:n.getAccessToken}),i}return e.__extends(i,r),i.prototype.fetchRemote=function(){return e.__awaiter(this,arguments,void 0,(function(t){var r,i,s,a,c,l,d,h,f,m,p,g,b,y,w,v,_=this;return void 0===t&&(t={}),e.__generator(this,(function(e){switch(e.label){case 0:console.log("📚 Collection: ".concat(this.id," collection fetching")),this.remote.synchronising=!0,e.label=1;case 1:return e.trys.push([1,6,,7]),r=t.type,i=t.form,s=t.location,[4,this.remote.getAccessToken()];case 2:return a=e.sent(),c="".concat(this.remote.url,"/index.php/services/rest/groups"),l={},r&&(l.view=r),i&&(l.page=i.join(",")),Number.isFinite(s)&&(l.indexed_location_ids=s),d={params:l,headers:{Authorization:"Bearer ".concat(a)},timeout:8e4},[4,u.default.get(c,d)];case 3:if(h=e.sent(),f=function(e){return!e.toDate||new Date(e.toDate)>new Date},m=function(e){return!e.fromDate||new Date(e.fromDate)<new Date},p=h.data.map((function(e){return e.values})).map(o.getCamelCaseObj).filter(f).filter(m),g=p.map((function(e){return _.Model.fromDTO(e,{skipStore:"member"!==r})})),r){if("member"===r)for(b=0;b<this.data.length;b++)(y=this.data[b]).isStored&&(y.destroy(),this.data.splice(b,1),b--);else if("joinable"===r)for(b=0;b<this.data.length;b++)(y=this.data[b]).isStored||(this.data.splice(b,1),b--)}else for(b=0;b<this.data.length;b++)(y=this.data[b]).isStored&&y.destroy(),this.data.splice(b,1),b--;return"member"!==r?[3,5]:[4,Promise.all(g.map((function(e){return e.save()})))];case 4:e.sent(),e.label=5;case 5:return(v=this.data).push.apply(v,g),console.log("📚 Collection: ".concat(this.id," collection fetching done ").concat(p.length," documents")),[3,7];case 6:if(w=e.sent(),u.default.isCancel(w))return[2];if(n.isAxiosNetworkError(w))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if("issues"in w)throw new Error(w.issues.map((function(e){return"".concat(e.path.join(" ")," ").concat(e.message)})).join(" "));throw this.remote.synchronising=!1,w;case 7:return this.remote.synchronising=!1,[2]}}))}))},Object.defineProperty(i.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),i}(i.default);exports.byGroupMembershipStatus=function(e){return function(t){var r=t.data.userIsMember||t.data.userIsPending;return"member"===e?r:!r}},exports.default=c;
@@ -0,0 +1,108 @@
1
+ import { IObservableArray } from 'mobx';
2
+ import { z } from 'zod';
3
+ import Model, { Options as OptionsOriginal, Data as ModelData } from '../Model';
4
+ import Media from './Media';
5
+ export declare const dtoSchema: z.ZodObject<{
6
+ lat: z.ZodString;
7
+ lon: z.ZodString;
8
+ /**
9
+ * Location name.
10
+ */
11
+ name: z.ZodString;
12
+ /**
13
+ * Location type e.g. transect = 777, transect section = 778 etc.
14
+ */
15
+ locationTypeId: z.ZodString;
16
+ centroidSref: z.ZodString;
17
+ centroidSrefSystem: z.ZodString;
18
+ /**
19
+ * Entity ID.
20
+ */
21
+ id: z.ZodOptional<z.ZodString>;
22
+ createdOn: z.ZodOptional<z.ZodString>;
23
+ updatedOn: z.ZodOptional<z.ZodString>;
24
+ parentId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
25
+ boundaryGeom: z.ZodOptional<z.ZodNullable<z.ZodString>>;
26
+ code: z.ZodOptional<z.ZodNullable<z.ZodString>>;
27
+ createdById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
28
+ updatedById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
29
+ externalKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
30
+ centroidGeom: z.ZodOptional<z.ZodNullable<z.ZodString>>;
31
+ public: z.ZodOptional<z.ZodNullable<z.ZodString>>;
32
+ comment: z.ZodOptional<z.ZodNullable<z.ZodString>>;
33
+ }, "strip", z.ZodTypeAny, {
34
+ name: string;
35
+ lat: string;
36
+ lon: string;
37
+ locationTypeId: string;
38
+ centroidSref: string;
39
+ centroidSrefSystem: string;
40
+ id?: string | undefined;
41
+ code?: string | null | undefined;
42
+ parentId?: string | null | undefined;
43
+ createdOn?: string | undefined;
44
+ createdById?: string | null | undefined;
45
+ updatedOn?: string | undefined;
46
+ boundaryGeom?: string | null | undefined;
47
+ updatedById?: string | null | undefined;
48
+ externalKey?: string | null | undefined;
49
+ centroidGeom?: string | null | undefined;
50
+ public?: string | null | undefined;
51
+ comment?: string | null | undefined;
52
+ }, {
53
+ name: string;
54
+ lat: string;
55
+ lon: string;
56
+ locationTypeId: string;
57
+ centroidSref: string;
58
+ centroidSrefSystem: string;
59
+ id?: string | undefined;
60
+ code?: string | null | undefined;
61
+ parentId?: string | null | undefined;
62
+ createdOn?: string | undefined;
63
+ createdById?: string | null | undefined;
64
+ updatedOn?: string | undefined;
65
+ boundaryGeom?: string | null | undefined;
66
+ updatedById?: string | null | undefined;
67
+ externalKey?: string | null | undefined;
68
+ centroidGeom?: string | null | undefined;
69
+ public?: string | null | undefined;
70
+ comment?: string | null | undefined;
71
+ }>;
72
+ export type Metadata = {
73
+ saved?: boolean;
74
+ groupId?: string;
75
+ };
76
+ export declare enum LocationType {
77
+ MothTrap = "18879",
78
+ Transect = "777",
79
+ TransectSection = "778",
80
+ GroupSite = "14"
81
+ }
82
+ export type DTO = z.infer<typeof dtoSchema>;
83
+ export type Data = Omit<DTO, 'createdOn' | 'updatedOn'> & ModelData;
84
+ export interface Options<T = Data, S = Metadata> extends OptionsOriginal<T> {
85
+ metadata?: S;
86
+ media?: any[];
87
+ skipStore?: boolean;
88
+ url?: string;
89
+ getAccessToken?: () => Promise<string>;
90
+ }
91
+ declare class Location<T extends Data = Data> extends Model<T> {
92
+ static fromDTO(dto: DTO, options?: Partial<Options>): Location;
93
+ protected remote: {
94
+ synchronising: boolean;
95
+ url?: string;
96
+ getAccessToken?: () => Promise<string>;
97
+ };
98
+ media: IObservableArray<Media>;
99
+ metadata: Metadata;
100
+ constructor({ skipStore, store, media, metadata, url, getAccessToken, ...options }: Options);
101
+ saveRemote(): Promise<this>;
102
+ toDTO(warehouseMediaNames?: {}): any;
103
+ protected uploadMedia(): Promise<any>;
104
+ get isUploaded(): boolean;
105
+ get isSynchronising(): boolean;
106
+ get isDraft(): boolean;
107
+ }
108
+ export default Location;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),n=require("axios"),i=require("lodash"),r=require("zod"),o=require("@flumens/utils/dist/uuid"),a=require("../Model.js");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d,u=s(n),l=r.object({lat:r.z.string().min(1),lon:r.z.string().min(1),name:r.z.string().min(1),locationTypeId:r.z.string().min(1),centroidSref:r.z.string().min(1),centroidSrefSystem:r.z.string().min(1),id:r.z.string().optional(),createdOn:r.z.string().optional(),updatedOn:r.z.string().optional(),parentId:r.z.string().nullable().optional(),boundaryGeom:r.z.string().nullable().optional(),code:r.z.string().nullable().optional(),createdById:r.z.string().nullable().optional(),updatedById:r.z.string().nullable().optional(),externalKey:r.z.string().nullable().optional(),centroidGeom:r.z.string().nullable().optional(),public:r.z.string().nullable().optional(),comment:r.z.string().nullable().optional()});exports.LocationType=void 0,(d=exports.LocationType||(exports.LocationType={})).MothTrap="18879",d.Transect="777",d.TransectSection="778",d.GroupSite="14";var c=function(n){function r(i){var r=this,o=i.skipStore,a=i.store,s=i.media,d=void 0===s?[]:s,u=i.metadata,l=void 0===u?{}:u,c=i.url,p=i.getAccessToken,h=e.__rest(i,["skipStore","store","media","metadata","url","getAccessToken"]);return(r=n.call(this,e.__assign(e.__assign({},h),{store:o?void 0:a}))||this).metadata=t.observable(l),r.media=t.observable(d),r.remote=t.observable({synchronising:!1,url:c,getAccessToken:p}),r}return e.__extends(r,n),r.fromDTO=function(t,n){void 0===n&&(n={}),l.parse(t);var i=t.id,r=t.createdOn,a=t.updatedOn,s=t.externalKey,d=e.__rest(t,["id","createdOn","updatedOn","externalKey"]);return new this(e.__assign({cid:s||o.UUIDv7(),id:i,createdAt:new Date(r).getTime(),updatedAt:new Date(a).getTime(),data:d},n))},r.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,n,i,r,o,a,s,d,l,c,p,h,g,m,f;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,4,,5]),this.remote.synchronising=!0,[4,this.uploadMedia()];case 1:return t=e.sent(),n=this.toDTO(t),i="".concat(this.remote.url,"/index.php/services/rest/locations"),[4,this.remote.getAccessToken()];case 2:return r=e.sent(),o={url:i,method:"post",headers:{Authorization:"Bearer ".concat(r)},timeout:8e4,data:n},[4,u.default(o)];case 3:return a=e.sent().data,l=new Date(a.values.updated_on).getTime(),this.updatedAt=l,this.syncedAt=l,this.id=a.values.id,this.remote.synchronising=!1,this.store&&this.save(),console.log("Location uploading done"),[2,this];case 4:if(s=e.sent(),this.remote.synchronising=!1,409===(null===(p=(d=s).response)||void 0===p?void 0:p.status)&&(null===(h=d.response)||void 0===h?void 0:h.data.duplicate_of))return console.log("Location uploading duplicate was found"),l=(new Date).getTime(),this.updatedAt=l,this.syncedAt=l,this.id=null===(g=d.response)||void 0===g?void 0:g.data.duplicate_of.id,[2,this];if(!(c=null===(f=null===(m=d.response)||void 0===m?void 0:m.data)||void 0===f?void 0:f.message))throw s;if("object"==typeof c)throw new Error(function(e){return Object.entries(e).reduce((function(e,t){return"".concat(e).concat(t[0]," ").concat(t[1],"\n")}),"")}(c));throw new Error(c);case 5:return[2]}}))}))},r.prototype.toDTO=function(t){void 0===t&&(t={});var n,r=(n=this.data,Object.entries(n).reduce((function(e,t){var n=t[0],r=t[1];return e[n.includes("locAttr:")?n:i.snakeCase(n)]=r,e}),{})),o={values:e.__assign({external_key:this.cid},r),media:[]};return this.media.forEach((function(e){var n=e.toDTO(t);n&&o.media.push(n)})),o},r.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,Promise.all(this.media.map((function(e){return e.uploadFile()})))];case 1:return e.sent(),t={},this.media.forEach((function(e){t[e.cid]={name:e.data.queued}})),[2,t]}}))}))},Object.defineProperty(r.prototype,"isUploaded",{get:function(){return!!this.syncedAt},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"isDraft",{get:function(){return!this.id},enumerable:!1,configurable:!0}),r}(a.default);exports.default=c,exports.dtoSchema=l;
@@ -0,0 +1,20 @@
1
+ import Collection, { Options as BaseOptions } from '../Collection';
2
+ import Location, { LocationType } from './Location';
3
+ type RemoteFetchParams = any;
4
+ export interface Options<T extends Location> extends BaseOptions<T> {
5
+ url?: string | null;
6
+ getAccessToken: () => Promise<string>;
7
+ }
8
+ declare class LocationCollection<T extends Location> extends Collection<T> {
9
+ protected remote: {
10
+ synchronising: boolean;
11
+ url: string;
12
+ getAccessToken: () => Promise<string>;
13
+ };
14
+ constructor(options: Options<T>);
15
+ fetchRemote(params?: RemoteFetchParams): Promise<void>;
16
+ get isSynchronising(): boolean;
17
+ }
18
+ type ILocationType = `${LocationType}`;
19
+ export declare const byLocationType: (type: ILocationType) => (location: Location) => boolean;
20
+ export default LocationCollection;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("../Collection.js"),n=require("./Location.js"),o=function(r){function o(o){var i=r.call(this,e.__assign({id:"locations",Model:n.default},o))||this;return i.remote=t.observable({synchronising:!1,url:o.url,getAccessToken:o.getAccessToken}),i}return e.__extends(o,r),o.prototype.fetchRemote=function(){return e.__awaiter(this,arguments,void 0,(function(t){return void 0===t&&(t={}),e.__generator(this,(function(e){throw console.log(t),new Error("fetchRemote not implemented")}))}))},Object.defineProperty(o.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),o}(r.default);exports.byLocationType=function(e){return function(t){return t.data.locationTypeId===e}},exports.default=o;
@@ -7,6 +7,8 @@ export type DataURI = string;
7
7
  export type URL = string;
8
8
  export interface Options<T = any, S = any> extends OptionsOriginal<T> {
9
9
  metadata?: S;
10
+ url?: string;
11
+ getAccessToken?: () => Promise<string>;
10
12
  }
11
13
  export interface Data extends DataOriginal {
12
14
  type?: string;
@@ -52,14 +54,18 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
52
54
  * @returns
53
55
  */
54
56
  static getImageModel(imageURL: URL, dataDirPath: string, skipThumbnail?: boolean): Promise<Media>;
57
+ protected remote: {
58
+ synchronising: boolean;
59
+ url: string;
60
+ getAccessToken: () => Promise<string>;
61
+ };
55
62
  metadata: S;
56
- remote: Remote;
57
63
  debouncedValue: number;
58
64
  constructor({ metadata, ...options }?: Options);
59
65
  parent?: Sample | Occurrence;
60
66
  toJSON(): any;
61
67
  setupdatedAtTimestamp(newUpdatedAt: number): void;
62
- getSubmission(warehouseMediaNames?: any): any;
68
+ toDTO(warehouseMediaNames?: any): any;
63
69
  sync(): Promise<void>;
64
70
  uploadFile(force?: boolean): Promise<void>;
65
71
  getFormData(): Promise<unknown[]>;
@@ -82,5 +88,6 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
82
88
  }): Promise<void>;
83
89
  get isUploaded(): boolean;
84
90
  get isDisabled(): boolean;
91
+ get isSynchronising(): boolean;
85
92
  }
86
93
  export default Media;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),i=require("axios"),r=require("@flumens/utils"),a=require("../Model.js"),n=require("./helpers.js");function o(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var s=o(i),u=r.isPlatform("hybrid"),d=function(i){function a(r){void 0===r&&(r={});var a=this,n=r.metadata,o=void 0===n?{}:n,s=t.__rest(r,["metadata"]);return s.createdAt=s.createdAt||(null==o?void 0:o.createdOn),s.updatedAt=s.updatedAt||(null==o?void 0:o.updatedOn),s.syncedAt=s.syncedAt||(null==o?void 0:o.syncedOn),(a=i.call(this,s)||this).remote={synchronising:!1,url:null,getAccessToken:function(){return Promise.resolve("auth token is missing")},timeout:12e4},a.debouncedValue=300,a.parent=a.parent,a.metadata=e.observable(o),a}return t.__extends(a,i),a.getDataURI=function(t,e){return void 0===e&&(e={}),new Promise((function(i,r){if("string"==typeof t){var n=t.replace(/.*\.([a-z]+)$/i,"$1");return"jpg"===n&&(n="jpeg"),void a.resize(t,n,e.width,e.height).then((function(t){var e=t[0],r=t[1];i([r,n,e.width,e.height])}))}if(window.FileReader){var o=new FileReader;o.onload=function(r){var n,o;if(e.width||e.height)a.resize(null===(n=r.target)||void 0===n?void 0:n.result,t.type,e.width,e.height).then((function(e){var r=e[0],a=e[1];i([a,t.type,r.width,r.height])}));else{var s=new window.Image;s.onload=function(){var e,a=t.type.replace(/.*\/([a-z]+)$/i,"$1");i([null===(e=r.target)||void 0===e?void 0:e.result,a,s.width,s.height])},s.src=null===(o=r.target)||void 0===o?void 0:o.result}},o.readAsDataURL(t)}else r(new Error("No File Reader"))}))},a.resize=function(t,e,i,r){return new Promise((function(a){var n=new window.Image;n.onload=function(){var t,o=n.width,s=n.height,u=null;o/=u=o>s?o/(!i||i>o?o:i):s/(!r||r>s?s:r),s/=u;var d=document.createElement("canvas");d.width=o,d.height=s,null===(t=d.getContext("2d"))||void 0===t||t.drawImage(n,0,0,o,s),a([n,d.toDataURL(e)])},n.src=t}))},a.getImageModel=function(e,i,a){return t.__awaiter(this,void 0,void 0,(function(){var n,o,s,d,c,h,l;return t.__generator(this,(function(t){switch(t.label){case 0:if(n=this,!e)throw new Error("File not found while creating image model.");return u?[4,r.createImage(e)]:[3,2];case 1:return c=t.sent(),o=c.width,s=c.height,d=e.split("/").pop(),[3,4];case 2:return[4,n.getDataURI(e,{width:2e3,height:2e3})];case 3:l=t.sent(),d=l[0],o=l[2],s=l[3],t.label=4;case 4:return h=new n({data:{data:d,type:"jpeg",width:o,height:s,path:i}}),a?[3,6]:[4,h.addThumbnail()];case 5:t.sent(),t.label=6;case 6:return[2,h]}}))}))},a.prototype.toJSON=function(){var r=i.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(t.__assign(t.__assign({},r),{metadata:e.toJS(this.metadata)||{}})))},a.prototype.setupdatedAtTimestamp=function(t){var e;i.prototype.setUpdatedAtTimestamp.call(this,t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)},a.prototype.getSubmission=function(t){void 0===t&&(t={});var e=t[this.cid];if(!this.id&&!e)throw new Error("Image ID or queued ID is missing.");var i={values:{caption:this.data.caption}};return this.id?i.values.id=this.id:i.values.queued=e.name,i},a.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,this.parent?this.parent.sync():i.prototype.sync.call(this)]}))}))},a.prototype.uploadFile=function(){return t.__awaiter(this,arguments,void 0,(function(e){var i,r,a,n,o,u,d,c,h,l;return void 0===e&&(e=!1),t.__generator(this,(function(t){switch(t.label){case 0:if(this.id)throw new Error("A file of a media on the remote cannot be uploaded again.");return i=Date.now()-432e5,r=this.syncedAt>i&&this.data.queued,!e&&r?[2]:[4,this.getFormData()];case 1:if(a=t.sent(),n=new FormData,(c=n).append.apply(c,a),!this.remote.getAccessToken)throw new Error("this.remote.getAccessToken is missing");return h={},u="Bearer ".concat,[4,this.remote.getAccessToken()];case 2:return h.Authorization=u.apply("Bearer ",[t.sent()]),o=h,[4,s.default.post("".concat(this.remote.url,"/index.php/services/rest/media-queue"),n,{headers:o,timeout:12e4})];case 3:if(d=t.sent(),!(null===(l=d.data[this.cid])||void 0===l?void 0:l.name))throw new Error("New remote media name was not be found.");return this.data.queued=d.data[this.cid].name,this.syncedAt=(new Date).getTime(),[2]}}))}))},a.prototype.getFormData=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,i,r,a,o,s,u;return t.__generator(this,(function(t){switch(t.label){case 0:return e=this.data.type,i=e,r=e,(null==e?void 0:e.match(/image.*/))?(u=e.split("/"),i=u[1]):r="image/".concat(r),a=this.getURL(),[4,n.getBlobFromURL(a,r)];case 1:return o=t.sent(),[2,[s=this.cid,o,"".concat(s,".").concat(i)]]}}))}))},a.prototype.getRemoteURL=function(){if(!this.remote.url)throw new Error("No remote url was set.");if(!this.data.queued&&!this.data.path)throw new Error("No media queued or path attribute.");var t=this.remote.url.replace("/index.php/services/rest","");return this.data.queued?"".concat(t,"/upload-queue/").concat(this.data.queued):"".concat(t,"/upload/").concat(this.data.path)},a.prototype.getURL=function(){return this.data.data},a.prototype.resize=function(t,e){var i=this,r=this;return new Promise((function(n,o){a.resize(i.getURL(),i.data.type,t,e).then((function(t){var e=t[0],i=t[1];r.data.data=i,n([e,i])})).catch(o)}))},a.prototype.addThumbnail=function(t){var e=this,i=this;return new Promise((function(t,r){/^data:/i.test(e.getURL())?a.resize(e.getURL(),e.data.type,100,100).then((function(e){var r=e[1];i.data.thumbnail=r,t()})).catch(r):a.getDataURI(e.getURL(),{width:100,height:100}).then((function(e){i.data.thumbnail=e[0],t()})).catch(r)}))},Object.defineProperty(a.prototype,"isUploaded",{get:function(){if(!this.parent)throw new Error("No media parent to return disabled status.");return this.parent.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),a}(a.default);exports.default=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),i=require("@flumens/utils"),a=require("../Model.js"),n=require("./helpers.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=o(r),d=i.isPlatform("hybrid"),u=function(r){function a(i){void 0===i&&(i={});var a=this,n=i.metadata,o=void 0===n?{}:n,s=e.__rest(i,["metadata"]);return s.createdAt=s.createdAt||(null==o?void 0:o.createdOn),s.updatedAt=s.updatedAt||(null==o?void 0:o.updatedOn),s.syncedAt=s.syncedAt||(null==o?void 0:o.syncedOn),(a=r.call(this,s)||this).debouncedValue=300,a.parent=a.parent,a.remote=t.observable({synchronising:!1,url:s.url,getAccessToken:s.getAccessToken}),a.metadata=t.observable(o),a}return e.__extends(a,r),a.getDataURI=function(e,t){return void 0===t&&(t={}),new Promise((function(r,i){if("string"==typeof e){var n=e.replace(/.*\.([a-z]+)$/i,"$1");return"jpg"===n&&(n="jpeg"),void a.resize(e,n,t.width,t.height).then((function(e){var t=e[0],i=e[1];r([i,n,t.width,t.height])}))}if(window.FileReader){var o=new FileReader;o.onload=function(i){var n,o;if(t.width||t.height)a.resize(null===(n=i.target)||void 0===n?void 0:n.result,e.type,t.width,t.height).then((function(t){var i=t[0],a=t[1];r([a,e.type,i.width,i.height])}));else{var s=new window.Image;s.onload=function(){var t,a=e.type.replace(/.*\/([a-z]+)$/i,"$1");r([null===(t=i.target)||void 0===t?void 0:t.result,a,s.width,s.height])},s.src=null===(o=i.target)||void 0===o?void 0:o.result}},o.readAsDataURL(e)}else i(new Error("No File Reader"))}))},a.resize=function(e,t,r,i){return new Promise((function(a){var n=new window.Image;n.onload=function(){var e,o=n.width,s=n.height,d=null;o/=d=o>s?o/(!r||r>o?o:r):s/(!i||i>s?s:i),s/=d;var u=document.createElement("canvas");u.width=o,u.height=s,null===(e=u.getContext("2d"))||void 0===e||e.drawImage(n,0,0,o,s),a([n,u.toDataURL(t)])},n.src=e}))},a.getImageModel=function(t,r,a){return e.__awaiter(this,void 0,void 0,(function(){var n,o,s,u,c,h,l;return e.__generator(this,(function(e){switch(e.label){case 0:if(n=this,!t)throw new Error("File not found while creating image model.");return d?[4,i.createImage(t)]:[3,2];case 1:return c=e.sent(),o=c.width,s=c.height,u=t.split("/").pop(),[3,4];case 2:return[4,n.getDataURI(t,{width:2e3,height:2e3})];case 3:l=e.sent(),u=l[0],o=l[2],s=l[3],e.label=4;case 4:return h=new n({data:{data:u,type:"jpeg",width:o,height:s,path:r}}),a?[3,6]:[4,h.addThumbnail()];case 5:e.sent(),e.label=6;case 6:return[2,h]}}))}))},a.prototype.toJSON=function(){var i=r.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(e.__assign(e.__assign({},i),{metadata:t.toJS(this.metadata)||{}})))},a.prototype.setupdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},a.prototype.toDTO=function(e){void 0===e&&(e={});var t=e[this.cid];if(!this.id&&!t)throw new Error("Image ID or queued ID is missing.");var r={values:{caption:this.data.caption}};return this.id?r.values.id=this.id:r.values.queued=t.name,r},a.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():r.prototype.sync.call(this)]}))}))},a.prototype.uploadFile=function(){return e.__awaiter(this,arguments,void 0,(function(t){var r,i,a,n,o,d,u,c,h,l;return void 0===t&&(t=!1),e.__generator(this,(function(e){switch(e.label){case 0:if(this.id)throw new Error("A file of a media on the remote cannot be uploaded again.");return r=Date.now()-432e5,i=this.syncedAt>r&&this.data.queued,!t&&i?[2]:[4,this.getFormData()];case 1:if(a=e.sent(),n=new FormData,(c=n).append.apply(c,a),!this.remote.getAccessToken)throw new Error("this.remote.getAccessToken is missing");return h={},d="Bearer ".concat,[4,this.remote.getAccessToken()];case 2:return h.Authorization=d.apply("Bearer ",[e.sent()]),o=h,[4,s.default.post("".concat(this.remote.url,"/index.php/services/rest/media-queue"),n,{headers:o,timeout:12e4})];case 3:if(u=e.sent(),!(null===(l=u.data[this.cid])||void 0===l?void 0:l.name))throw new Error("New remote media name was not be found.");return this.data.queued=u.data[this.cid].name,this.syncedAt=(new Date).getTime(),[2]}}))}))},a.prototype.getFormData=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,i,a,o,s,d;return e.__generator(this,(function(e){switch(e.label){case 0:return t=this.data.type,r=t,i=t,(null==t?void 0:t.match(/image.*/))?(d=t.split("/"),r=d[1]):i="image/".concat(i),a=this.getURL(),[4,n.getBlobFromURL(a,i)];case 1:return o=e.sent(),[2,[s=this.cid,o,"".concat(s,".").concat(r)]]}}))}))},a.prototype.getRemoteURL=function(){if(!this.remote.url)throw new Error("No remote url was set.");if(!this.data.queued&&!this.data.path)throw new Error("No media queued or path attribute.");var e=this.remote.url.replace("/index.php/services/rest","");return this.data.queued?"".concat(e,"/upload-queue/").concat(this.data.queued):"".concat(e,"/upload/").concat(this.data.path)},a.prototype.getURL=function(){return this.data.data},a.prototype.resize=function(e,t){var r=this,i=this;return new Promise((function(n,o){a.resize(r.getURL(),r.data.type,e,t).then((function(e){var t=e[0],r=e[1];i.data.data=r,n([t,r])})).catch(o)}))},a.prototype.addThumbnail=function(e){var t=this,r=this;return new Promise((function(e,i){/^data:/i.test(t.getURL())?a.resize(t.getURL(),t.data.type,100,100).then((function(t){var i=t[1];r.data.thumbnail=i,e()})).catch(i):a.getDataURI(t.getURL(),{width:100,height:100}).then((function(t){r.data.thumbnail=t[0],e()})).catch(i)}))},Object.defineProperty(a.prototype,"isUploaded",{get:function(){if(!this.parent)throw new Error("No media parent to return disabled status.");return this.parent.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),a}(a.default);exports.default=u;
@@ -1,6 +1,6 @@
1
1
  import { IObservableArray } from 'mobx';
2
2
  import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
3
- import ElasticOccurrence from './ElasticOccurrence';
3
+ import ElasticOccurrenceDTO from './ElasticOccurrence';
4
4
  import Media from './Media';
5
5
  import Sample from './Sample';
6
6
  import { RemoteConfig, Keys } from './helpers';
@@ -54,28 +54,9 @@ export interface Data extends DataOriginal {
54
54
  }
55
55
  export default class Occurrence<T extends Data = Data, S extends Metadata = Metadata> extends Model {
56
56
  /**
57
- * Transform ES document into local structure.
57
+ * Transform ES document into local model.
58
58
  */
59
- static dto({ id, metadata, event, occurrence, taxon, identification, }: ElasticOccurrence, remoteUrl: string, survey: any): {
60
- id: string;
61
- cid: string;
62
- createdAt: number;
63
- updatedAt: number;
64
- syncedAt: number;
65
- metadata: {
66
- verification: any;
67
- };
68
- data: any;
69
- media: {
70
- id: string;
71
- createdAt: number;
72
- updatedAt: number;
73
- syncedAt: number;
74
- data: {
75
- data: string;
76
- };
77
- }[] | undefined;
78
- };
59
+ static fromElasticDTO(dto: ElasticOccurrenceDTO, remoteUrl: string, survey: any): Occurrence<Data, Metadata>;
79
60
  /**
80
61
  * Warehouse attributes and their values.
81
62
  */
@@ -83,22 +64,6 @@ export default class Occurrence<T extends Data = Data, S extends Metadata = Meta
83
64
  taxon: {
84
65
  id: string;
85
66
  };
86
- training: {
87
- id: string;
88
- values: (val?: boolean | "t" | "f" | null) => "t" | "f";
89
- };
90
- deleted: {
91
- id: string;
92
- values: (val?: boolean | "t" | "f" | null) => "t" | "f";
93
- };
94
- confidential: {
95
- id: string;
96
- values: (val?: boolean | "t" | "f" | null) => "t" | "f";
97
- };
98
- zeroAbundance: {
99
- id: string;
100
- values: (val?: boolean | "t" | "f" | null) => "t" | "f";
101
- };
102
67
  };
103
68
  Media: typeof Media<any, any>;
104
69
  metadata: S;
@@ -136,5 +101,5 @@ export default class Occurrence<T extends Data = Data, S extends Metadata = Meta
136
101
  * Returns an object with attributes and their values
137
102
  * mapped for warehouse submission.
138
103
  */
139
- getSubmission(warehouseMediaNames?: {}): any;
104
+ toDTO(warehouseMediaNames?: {}): any;
140
105
  }
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),a=require("lodash"),n=require("../Model.js"),i=require("./Media.js"),r=require("./helpers.js"),o=function(n){function o(a){void 0===a&&(a={});var r=this,s=a.metadata,d=void 0===s?{}:s,u=a.media,c=void 0===u?[]:u,l=a.Media,p=void 0===l?i.default:l,v=e.__rest(a,["metadata","media","Media"]);v.createdAt=v.createdAt||(null==d?void 0:d.createdOn),v.updatedAt=v.updatedAt||(null==d?void 0:d.updatedOn),v.syncedAt=v.syncedAt||(null==d?void 0:d.syncedOn),(r=n.call(this,v)||this).debouncedValue=300,r.keys=function(){var t;return e.__assign(e.__assign({},o.keys),(t=r.getSurvey().attrs||{},Object.keys(t).reduce((function(a,n){var i;return e.__assign(e.__assign({},a),((i={})[n]=t[n].remote||t[n],i))}),{})))},r.Media=p,r.metadata=t.observable(d);var m,f,_=c.map((m=r.Media,void 0===f&&(f={}),function(t){return t instanceof m?t:new m(e.__assign(e.__assign({},t),f))}));r.media=t.observable(_);var h=function(e){return e.parent=r};r.media.forEach(h);return t.intercept(r.media,(function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(h),r.setUpdatedAtTimestamp(Date.now())):e.removedCount&&r.setUpdatedAtTimestamp(Date.now()),e})),r}return e.__extends(o,n),o.dto=function(t,a,n){var i,o,s,d,u,c,l,p=t.id,v=t.metadata,m=t.event,f=t.occurrence,_=t.taxon,h=t.identification,y=new Date(v.created_on).getTime(),b=new Date(v.updated_on).getTime(),g=Date.now(),A=m.parent_event_id?null===(o=null===(i=n.smp)||void 0===i?void 0:i.occ)||void 0===o?void 0:o.attrs:null===(s=n.occ)||void 0===s?void 0:s.attrs;A||(A=(null===(u=null===(d=n.smp)||void 0===d?void 0:d.occ)||void 0===u?void 0:u.attrs)||(null===(c=n.occ)||void 0===c?void 0:c.attrs)||{});var w=r.parseRemoteAttrs(A,f.attributes||[]),x=null===(l=f.media)||void 0===l?void 0:l.map((function(e){var t=e.path;return{id:t,createdAt:y,updatedAt:b,syncedAt:g,data:{data:"".concat(a,"/upload/").concat(t)}}})),N=_.species||_.taxon_name,S=N!==_.taxon_name?_.taxon_name:"";return{id:p,cid:p,createdAt:y,updatedAt:b,syncedAt:g,metadata:{verification:h},data:e.__assign(e.__assign({},w),{taxon:{warehouse_id:parseInt(_.taxa_taxon_list_id,10),scientific_name:N,scientificName:N,common_name:S,commonName:S,found_in_name:S?"common_name":"scientific_name",foundInName:S?"commonName":"scientificName"},comment:f.occurrence_remarks}),media:x}},o.prototype.setUpdatedAtTimestamp=function(e){var t;n.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},o.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){if(!this.parent)throw new Error("Trying to save locally without a parent");return this.parent.save(),[2]}))}))},o.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.parent)throw new Error("Trying to destroy locally without a parent");return this.parent.occurrences.remove(this),[4,Promise.all(this.media.map((function(e){return e.destroy(!0)})))];case 1:return e.sent(),t?[2]:[4,this.parent.save()];case 2:return e.sent(),[2]}}))}))},o.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():n.prototype.sync.call(this)]}))}))},o.prototype.toJSON=function(){var a,i=n.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(e.__assign(e.__assign({},i),{media:(null===(a=this.media)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[],metadata:t.toJS(this.metadata)||{}})))},o.prototype.getSurvey=function(){return this.parent&&this.parent.getSurvey().occ||{}},Object.defineProperty(o.prototype,"isUploaded",{get:function(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),o.prototype.getSubmission=function(t){var n=this;void 0===t&&(t={});var i="function"==typeof this.keys?this.keys():this.keys,r=e.__assign(e.__assign({},o.keys),i),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);Object.keys(this.data).forEach((function(e){var t=n.data[e],i=function(e){return null==e};if(!i(t)){if(!r[e])return e=e.includes("occAttr:")?e:a.snakeCase(e),void(s.values[e]=t);var o=r[e].id||e;if(t=function(e,t){var a=r[e].values;if(!a)return t;if("function"==typeof a)return a(t,s,n);if(a instanceof Array){var i=a.find((function(e){return e.value===t}));if(!i||!i.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return i.id}return t instanceof Array?t.map((function(e){return a[e]})):a[t]}(e,t),!i(t)){var d=Number.isNaN(Number(o))?o:"occAttr:".concat(o);d=d.includes("occAttr:")?d:a.snakeCase(d),s.values[d]=t}}})),this.media.forEach((function(e){var a=e.getSubmission(t);a&&s.media.push(a)}));var d=this.getSurvey();return d.modifySubmission?d.modifySubmission(s,this):s},o.keys={taxon:{id:"taxa_taxon_list_id"},training:{id:"training",values:r.boolToWarehouseValue},deleted:{id:"deleted",values:r.boolToWarehouseValue},confidential:{id:"confidential",values:r.boolToWarehouseValue},zeroAbundance:{id:"zero_abundance",values:r.boolToWarehouseValue}},o}(n.default);exports.default=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),a=require("lodash"),n=require("../Model.js"),i=require("./Media.js"),r=require("./helpers.js"),o=function(n){function o(a){void 0===a&&(a={});var r=this,s=a.metadata,d=void 0===s?{}:s,u=a.media,c=void 0===u?[]:u,p=a.Media,l=void 0===p?i.default:p,m=t.__rest(a,["metadata","media","Media"]);m.createdAt=m.createdAt||(null==d?void 0:d.createdOn),m.updatedAt=m.updatedAt||(null==d?void 0:d.updatedOn),m.syncedAt=m.syncedAt||(null==d?void 0:d.syncedOn),(r=n.call(this,m)||this).debouncedValue=300,r.keys=function(){var e;return t.__assign(t.__assign({},o.keys),(e=r.getSurvey().attrs||{},Object.keys(e).reduce((function(a,n){var i;return t.__assign(t.__assign({},a),((i={})[n]=e[n].remote||e[n],i))}),{})))},r.Media=l,r.metadata=e.observable(d);var v,f,_=c.map((v=r.Media,void 0===f&&(f={}),function(e){return e instanceof v?e:new v(t.__assign(t.__assign({},e),f))}));r.media=e.observable(_);var h=function(t){return t.parent=r};r.media.forEach(h);return e.intercept(r.media,(function(t){var e;return(null===(e=t.added)||void 0===e?void 0:e.length)?(t.added.forEach(h),r.setUpdatedAtTimestamp(Date.now())):t.removedCount&&r.setUpdatedAtTimestamp(Date.now()),t})),r}return t.__extends(o,n),o.fromElasticDTO=function(e,a,n){var i,o,s,d,u,c,p,l=e.id,m=e.metadata,v=e.event,f=e.occurrence,_=e.taxon,h=e.identification,y=new Date(m.created_on).getTime(),g=new Date(m.updated_on).getTime(),b=Date.now(),A=v.parent_event_id?null===(o=null===(i=n.smp)||void 0===i?void 0:i.occ)||void 0===o?void 0:o.attrs:null===(s=n.occ)||void 0===s?void 0:s.attrs;A||(A=(null===(u=null===(d=n.smp)||void 0===d?void 0:d.occ)||void 0===u?void 0:u.attrs)||(null===(c=n.occ)||void 0===c?void 0:c.attrs)||{});var w=r.parseRemoteAttrs(A,f.attributes||[]),O=null===(p=f.media)||void 0===p?void 0:p.map((function(t){var e=t.path;return{id:e,createdAt:y,updatedAt:g,syncedAt:b,data:{data:"".concat(a,"/upload/").concat(e)}}})),x=_.species||_.taxon_name,N=x!==_.taxon_name?_.taxon_name:"";return new this({id:l,cid:l,createdAt:y,updatedAt:g,syncedAt:b,metadata:{verification:h},data:t.__assign(t.__assign({},w),{taxon:{warehouse_id:parseInt(_.taxa_taxon_list_id,10),scientific_name:x,scientificName:x,common_name:N,commonName:N,found_in_name:N?"common_name":"scientific_name",foundInName:N?"commonName":"scientificName"},comment:f.occurrence_remarks}),media:O})},o.prototype.setUpdatedAtTimestamp=function(t){var e;n.prototype.setUpdatedAtTimestamp.call(this,t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)},o.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){if(!this.parent)throw new Error("Trying to save locally without a parent");return this.parent.save(),[2]}))}))},o.prototype.destroy=function(e){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.parent)throw new Error("Trying to destroy locally without a parent");return this.parent.occurrences.remove(this),[4,Promise.all(this.media.map((function(t){return t.destroy(!0)})))];case 1:return t.sent(),e?[2]:[4,this.parent.save()];case 2:return t.sent(),[2]}}))}))},o.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,this.parent?this.parent.sync():n.prototype.sync.call(this)]}))}))},o.prototype.toJSON=function(){var a,i=n.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(t.__assign(t.__assign({},i),{media:(null===(a=this.media)||void 0===a?void 0:a.map((function(t){return t.toJSON()})))||[],metadata:e.toJS(this.metadata)||{}})))},o.prototype.getSurvey=function(){return this.parent&&this.parent.getSurvey().occ||{}},Object.defineProperty(o.prototype,"isUploaded",{get:function(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),o.prototype.toDTO=function(e){var n=this;void 0===e&&(e={});var i="function"==typeof this.keys?this.keys():this.keys,r=t.__assign(t.__assign({},o.keys),i),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);Object.keys(this.data).forEach((function(t){var e=n.data[t],i=function(t){return null==t};if(!i(e)){if(!r[t])return t=t.includes("occAttr:")?t:a.snakeCase(t),void(s.values[t]=e);var o=r[t].id||t;if(e=function(t,e){var a=r[t].values;if(!a)return e;if("function"==typeof a)return a(e,s,n);if(a instanceof Array){var i=a.find((function(t){return t.value===e}));if(!i||!i.id)throw new Error('A "'.concat(t,'" attribute "').concat(e,'" value could not be mapped to a remote database field.'));return i.id}return e instanceof Array?e.map((function(t){return a[t]})):a[e]}(t,e),!i(e)){var d=Number.isNaN(Number(o))?o:"occAttr:".concat(o);d=d.includes("occAttr:")?d:a.snakeCase(d),s.values[d]=e}}})),this.media.forEach((function(t){var a=t.toDTO(e);a&&s.media.push(a)}));var d=this.getSurvey();return d.modifySubmission?d.modifySubmission(s,this):s},o.keys={taxon:{id:"taxa_taxon_list_id"}},o}(n.default);exports.default=o;
@@ -1,6 +1,6 @@
1
1
  import { IObservableArray } from 'mobx';
2
2
  import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
3
- import ElasticSample from './ElasticSample';
3
+ import ElasticSampleDTO from './ElasticSample';
4
4
  import Media from './Media';
5
5
  import Occurrence from './Occurrence';
6
6
  import { RemoteConfig, Keys } from './helpers';
@@ -22,6 +22,8 @@ export interface Options<T = any, S = any> extends OptionsOriginal<T> {
22
22
  Occurrence?: typeof Occurrence<any, any>;
23
23
  Media?: typeof Media<any, any>;
24
24
  skipStore?: boolean;
25
+ url?: string;
26
+ getAccessToken?: () => Promise<string>;
25
27
  }
26
28
  export interface Data extends DataOriginal {
27
29
  /**
@@ -45,20 +47,6 @@ export interface Data extends DataOriginal {
45
47
  training?: boolean;
46
48
  comment?: string;
47
49
  }
48
- export interface Remote {
49
- synchronising?: boolean;
50
- url?: string | null;
51
- getAccessToken: () => Promise<string>;
52
- timeout?: number;
53
- /**
54
- * @deprecated
55
- */
56
- host_url?: any;
57
- /**
58
- * @deprecated
59
- */
60
- api_key?: any;
61
- }
62
50
  type BaseSurvey = {
63
51
  attrs?: {
64
52
  [key: string]: {
@@ -73,30 +61,9 @@ export interface Survey extends BaseSurvey {
73
61
  }
74
62
  declare class Sample<T extends Data = Data, S extends Metadata = Metadata> extends Model<T> {
75
63
  /**
76
- * Transform ES document into local structure.
64
+ * Transform ES document into local model.
77
65
  */
78
- static dto({ id, event, location, metadata }: ElasticSample, remoteUrl: string, survey?: any): {
79
- id: string;
80
- cid: string;
81
- createdAt: number;
82
- updatedAt: number;
83
- syncedAt: number;
84
- metadata: {
85
- saved: boolean;
86
- };
87
- data: any;
88
- media: {
89
- id: string;
90
- metadata: {
91
- updatedOn: Date;
92
- createdOn: Date;
93
- syncedOn: Date;
94
- };
95
- data: {
96
- data: string;
97
- };
98
- }[] | undefined;
99
- };
66
+ static fromElasticDTO(dto: ElasticSampleDTO, options?: Partial<Options>, survey?: any): Sample<Data, Metadata>;
100
67
  /**
101
68
  * Warehouse attributes and their values.
102
69
  */
@@ -113,15 +80,13 @@ declare class Sample<T extends Data = Data, S extends Metadata = Metadata> exten
113
80
  latlon: number;
114
81
  };
115
82
  };
116
- training: {
117
- id: string;
118
- values: (val?: boolean | "t" | "f" | null) => "t" | "f";
119
- };
120
- deleted: {
121
- id: string;
122
- values: (val?: boolean | "t" | "f" | null) => "t" | "f";
123
- };
124
83
  };
84
+ protected remote: {
85
+ synchronising: boolean;
86
+ url: string;
87
+ getAccessToken: () => Promise<string>;
88
+ };
89
+ protected survey?: Survey;
125
90
  Sample: typeof Sample<any, any>;
126
91
  Occurrence: typeof Occurrence<any, any>;
127
92
  Media: typeof Media<any, any>;
@@ -129,7 +94,6 @@ declare class Sample<T extends Data = Data, S extends Metadata = Metadata> exten
129
94
  * Model persistent observable metadata.
130
95
  */
131
96
  metadata: S;
132
- remote: Remote;
133
97
  validateRemote: any;
134
98
  error: {
135
99
  message: string;
@@ -139,17 +103,8 @@ declare class Sample<T extends Data = Data, S extends Metadata = Metadata> exten
139
103
  occurrences: IObservableArray<Occurrence>;
140
104
  media: IObservableArray<Media>;
141
105
  parent?: Sample<T, S>;
142
- private survey?;
143
106
  debouncedValue: number;
144
107
  constructor({ metadata, samples, occurrences, media, Sample: SampleClass, Occurrence: OccurrenceClass, Media: MediaClass, skipStore, ...options }?: Options);
145
- get isStored(): import("..").IStore<{
146
- id?: string;
147
- cid: string;
148
- data: T;
149
- createdAt: number;
150
- updatedAt: number;
151
- syncedAt?: number | null;
152
- }> | undefined;
153
108
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
154
109
  /**
155
110
  * Returns a clean (no observables) JSON representation of the model.
@@ -168,13 +123,14 @@ declare class Sample<T extends Data = Data, S extends Metadata = Metadata> exten
168
123
  sync(): Promise<void>;
169
124
  requiresRemoteSync: () => boolean;
170
125
  saveRemote(): Promise<void>;
171
- private postRemote;
126
+ protected postRemote(data: any): Promise<any>;
172
127
  fetchRemote(): Promise<void>;
173
128
  updateRemote(): Promise<void>;
174
- private putRemote;
175
- private uploadMedia;
176
- getSubmission(warehouseMediaNames?: {}): any;
129
+ protected putRemote(sampleId: string | number, data: any): Promise<any>;
130
+ protected uploadMedia(): Promise<any>;
131
+ toDTO(warehouseMediaNames?: {}): any;
177
132
  get isUploaded(): boolean;
178
133
  get isDisabled(): boolean;
134
+ get isSynchronising(): boolean;
179
135
  }
180
136
  export default Sample;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),s=require("lodash"),a=require("wellknown"),n=require("@flumens/utils"),i=require("../Model.js"),o=require("./ElasticOccurrence.js"),u=require("./ElasticSample.js"),c=require("./Media.js"),d=require("./Occurrence.js"),l=require("./helpers.js");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var h=p(r),m=p(a),f=function(t,r){return void 0===r&&(r={}),function(s){return s instanceof t?s:new t(e.__assign(e.__assign({},s),r))}};function v(e,t){var r,s,a,n,i;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(a=e.samples)||void 0===a||a.forEach((function(e,r){return v(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(n=e.occurrences)||void 0===n||n.forEach((function(e,r){return v(e,t.occurrences[r])}))),e.media&&t.media&&(null===(i=e.media)||void 0===i||i.forEach((function(e,r){return v(e,t.media[r])})));else{if("process"in window&&"test"===(null===(s=null===(r=window.process)||void 0===r?void 0:r.env)||void 0===s?void 0:s.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}var _=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,s,a;return e.__generator(this,(function(n){switch(n.label){case 0:return r=[],t.media?(s=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,t.getFormData()];case 1:return r=e.sent(),[2,[t,r]]}}))}))},[4,Promise.all(t.media.map(s))]):[3,2];case 1:a=n.sent(),r.push.apply(r,a),n.label=2;case 2:return t.occurrences?[4,Promise.all(t.occurrences.map(_))]:[3,4];case 3:a=n.sent(),r.push.apply(r,a.flat()),n.label=4;case 4:return t.samples?[4,Promise.all(t.samples.map(_))]:[3,6];case 5:a=n.sent(),r.push.apply(r,a.flat()),n.label=6;case 6:return[2,r]}}))}))};function g(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return g(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return g(e)}))),e.media&&(r.media=e.media.map((function(e){return g(e)}))),r}function y(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var w=function(r){function a(s){void 0===s&&(s={});var n=this,i=s.metadata,o=void 0===i?{}:i,u=s.samples,p=void 0===u?[]:u,h=s.occurrences,m=void 0===h?[]:h,v=s.media,_=void 0===v?[]:v,g=s.Sample,y=void 0===g?a:g,w=s.Occurrence,b=void 0===w?d.default:w,S=s.Media,A=void 0===S?c.default:S,E=s.skipStore,O=e.__rest(s,["metadata","samples","occurrences","media","Sample","Occurrence","Media","skipStore"]);O.createdAt=O.createdAt||(null==o?void 0:o.createdOn),O.updatedAt=O.updatedAt||(null==o?void 0:o.updatedOn),O.syncedAt=O.syncedAt||(null==o?void 0:o.syncedOn);var k=E?void 0:O.store;(n=r.call(this,e.__assign(e.__assign({},O),{store:k}))||this).remote=t.observable({synchronising:!1,url:null,getAccessToken:function(){return Promise.resolve("auth token is missing")},timeout:12e4}),n.validateRemote=l.validateRemoteModel,n.error=t.observable({message:""}),n.debouncedValue=300,n.keys=function(){var t;return e.__assign(e.__assign({},a.keys),(t=n.getSurvey().attrs||{},Object.keys(t).reduce((function(r,s){var a;return e.__assign(e.__assign({},r),((a={})[s]=t[s].remote||t[s],a))}),{})))},n.requiresRemoteSync=function(){return!n.syncedAt||n.updatedAt>n.syncedAt},n.Sample=y,n.Occurrence=b,n.Media=A,n.metadata=t.observable(o);var T=p.map(f(n.Sample));n.samples=t.observable(T);var q=m.map(f(n.Occurrence,{Media:n.Media}));n.occurrences=t.observable(q);var j=_.map(f(n.Media));n.media=t.observable(j);var N=function(e){return e.parent=n};n.samples.forEach(N),n.occurrences.forEach(N),n.media.forEach(N);var M=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(N),n.setUpdatedAtTimestamp(Date.now())):e.removedCount&&n.setUpdatedAtTimestamp(Date.now()),e};return t.intercept(n.samples,M),t.intercept(n.occurrences,M),t.intercept(n.media,M),n}return e.__extends(a,r),a.dto=function(t,r,s){var a,n,i=t.id,o=t.event,u=t.location,c=t.metadata,d=new Date(o.date_start),p=new Date(c.updated_on).getTime(),h=Date.now(),f=u.point.split(",").map(parseFloat),v=f[0],_=f[1],g="OSGB"===u.output_sref_system?u.output_sref:"",y=u.geom?m.default.parse(u.geom):null,w=o.parent_event_id,b=l.parseRemoteAttrs(w?null==s?void 0:s.smp.attrs:null==s?void 0:s.attrs,o.attributes||[]),S=null===(a=o.media)||void 0===a?void 0:a.map((function(e){var t=e.path;return{id:t,metadata:{updatedOn:d,createdOn:d,syncedOn:d},data:{data:"".concat(r,"/upload/").concat(t)}}}));return{id:i,cid:o.source_system_key||i,createdAt:d.getTime(),updatedAt:p,syncedAt:h,metadata:{saved:!0},data:e.__assign(e.__assign({},b),{surveyId:c.survey.id,date:d.toISOString(),location:{code:u.code,name:u.name||u.verbatim_locality,latitude:v,longitude:_,shape:y,gridref:g},enteredSrefSystem:4326,groupId:null===(n=c.group)||void 0===n?void 0:n.id,comment:o.event_remarks,training:"true"===c.trial}),media:S}},Object.defineProperty(a.prototype,"isStored",{get:function(){return this.store},enumerable:!1,configurable:!0}),a.prototype.setUpdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},a.prototype.toJSON=function(){var s,a,n,i=r.prototype.toJSON.call(this);return n=e.__assign(e.__assign({},i),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(s=this.samples)||void 0===s?void 0:s.map((function(e){return e.toJSON()})))||[],media:(null===(a=this.media)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[]}),JSON.parse(JSON.stringify(n))},a.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},a.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,n,i,o,u;return e.__generator(this,(function(c){switch(c.label){case 0:if(this.data.deleted)return[2];if(this.parent)return this.parent.save(),[2];if(!this.store)throw new Error("Trying to sync locally without a store");return t=this.toJSON(),r=t.data,s=t.metadata,a=t.occurrences,n=t.samples,i=t.media,o=e.__rest(t,["data","metadata","occurrences","samples","media"]),u=e.__assign(e.__assign({},o),{data:{data:r,metadata:s,occurrences:a,samples:n,media:i}}),[4,this.store.save(u)];case 1:return c.sent(),[2]}}))}))},a.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,a=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(a.media.map((function(e){return e.destroy(!0)}))),Promise.all(a.occurrences.map((function(e){return e.destroy(!0)})))])},this.parent?(this.parent.samples.remove(this),[4,r()]):[3,2];case 1:return e.sent(),t?[2]:(this.parent.save(),[2]);case 2:if(!this.store)throw new Error("Trying to sync locally without a store");return[4,this.store.delete(this.cid)];case 3:return e.sent(),null===(s=this.collection)||void 0===s||s.remove(this),[4,r()];case 4:return e.sent(),this.data.deleted=!0,[2]}}))}))},a.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():r.prototype.sync.call(this)]}))}))},a.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,n;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this.uploadMedia()];case 2:return t=e.sent(),r=this.getSubmission(t),[4,this.postRemote(r)];case 3:return s=e.sent(),this.remote.synchronising=!1,v(this,s),a=(new Date).getTime(),this.updatedAt=a,this.syncedAt=a,this.save(),[3,5];case 4:throw n=e.sent(),this.remote.synchronising=!1,n;case 5:return[2]}}))}))},a.prototype.postRemote=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,a,i,o,u,c,d;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,3,,4]),o={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:return o.Authorization=s.apply("Bearer ",[e.sent()]),r=o,[4,h.default.post("".concat(this.remote.url,"/index.php/services/rest/samples"),t,{headers:r,timeout:12e4})];case 2:return[2,e.sent().data];case 3:if(a=e.sent(),409===(i=a).status&&(null===(u=i.response)||void 0===u?void 0:u.data.duplicate_of))return[2,g(this,i.response.data.duplicate_of.id)];if(n.isAxiosNetworkError(i))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===i.status)throw y(t),new Error(l.getErrorMessageFromObject(null===(d=null===(c=i.response)||void 0===c?void 0:c.data)||void 0===d?void 0:d.message));throw new Error(i.message);case 4:return[2]}}))}))},a.prototype.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,n,i,c,d,l,p,h,m,f,v,_,g,y,w,b,S,A=this;return e.__generator(this,(function(E){switch(E.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');if(!this.cid)throw new Error("Sample cid or id is missing for fetching remote model.");return t=this.remote.url,[4,this.remote.getAccessToken()];case 1:return r=E.sent(),[4,u.fetchElasticSample({id:this.id,cid:this.cid,url:t,accessToken:r})];case 2:return s=E.sent(),this.data.surveyId||(this.data.surveyId=s.metadata.survey.id),a=this.getSurvey(),n=this.Sample.dto(s,this.remote.url,a),this.id=n.id,this.cid=n.cid||this.cid,Object.assign(this.data,n.data),Object.assign(this.metadata,n.metadata),i=u.fetchElasticSubSamples({parentId:this.id,url:t,accessToken:r}),c=o.fetchElasticOccurrences({parentId:this.id,url:t,accessToken:r}),[4,Promise.all([i,c])];case 3:return d=E.sent(),l=d[0],p=d[1],h=(new Date).getTime(),m=function(e){var t=A.Sample.dto(e,A.remote.url,A.getSurvey()),r=new A.Sample(t);return r.syncedAt=h,r},f=l.map(m),v=function(t,r){var s;return e.__assign(e.__assign({},t),((s={})[r.id]=r,s))},_=f.reduce(v,((b={})[this.id]=this,b)),this.samples.clear(),(S=this.samples).push.apply(S,f),g=function(e){var t=A.Occurrence.dto(e,A.remote.url,A.getSurvey()),r=new A.Occurrence(t);return r.syncedAt=h,[r,e.event.event_id]},y=p.map(g),w=function(e){var t=e[0],r=e[1];r!==parseInt(A.id,10)?_[r]?_[r].occurrences.push(t):console.log("Can't attach occ to missing ".concat(r," sample")):A.occurrences.push(t)},y.forEach(w),this.syncedAt=h,[2]}}))}))},a.prototype.updateRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,3,,4]),this.remote.synchronising=!0,t={},r=this.getSubmission(t),[4,this.putRemote(this.id,r)];case 2:return v(this,e.sent()),s=(new Date).getTime(),this.updatedAt=s,this.syncedAt=s,this.save(),this.remote.synchronising=!1,[3,4];case 3:throw a=e.sent(),this.remote.synchronising=!1,a;case 4:return[2]}}))}))},a.prototype.putRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s,a,i,o,u,c,d;return e.__generator(this,(function(e){switch(e.label){case 0:return u={},a="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:u.Authorization=a.apply("Bearer ",[e.sent()]),s=u,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,h.default.put("".concat(this.remote.url,"/samples/").concat(t),r,{headers:s,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if(i=e.sent(),o=i,n.isAxiosNetworkError(o))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===o.status)throw y(r),new Error(l.getErrorMessageFromObject(null===(d=null===(c=o.response)||void 0===c?void 0:c.data)||void 0===d?void 0:d.message));throw new Error(o.message);case 5:return[2]}}))}))},a.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,i,o,u,c,d=this;return e.__generator(this,(function(l){switch(l.label){case 0:return t={},[4,_(this)];case 1:if(r=l.sent(),!r.length)return[2,t];s=function(t){return e.__awaiter(d,void 0,void 0,(function(){var r,s,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:return i={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:i.Authorization=s.apply("Bearer ",[e.sent()]),r=i,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,h.default.post("".concat(this.remote.url,"/index.php/services/rest/media-queue"),t,{headers:r,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if("timeout"===(a=e.sent()).message)throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");throw a;case 5:return[2]}}))}))},a=[],i=Date.now()-432e5,r.forEach((function(e){var r=e[0];r.syncedAt>i&&r.data.queued?t[r.cid]={name:r.data.queued}:a.push(e)})),o=5,u=function(r){var n,i,u,c;return e.__generator(this,(function(d){switch(d.label){case 0:return n=a.slice(r,r+o),i=new FormData,n.forEach((function(e){var t=e[1];return i.append.apply(i,t)})),[4,s(i)];case 1:return u=d.sent(),c=(new Date).getTime(),n.forEach((function(e){var t=e[0];t.syncedAt=c,t.data.queued=u[t.cid].name})),t=e.__assign(e.__assign({},t),u),[2]}}))},c=0,l.label=2;case 2:return c<a.length?[5,u(c)]:[3,5];case 3:l.sent(),l.label=4;case 4:return c+=o,[3,2];case 5:return[2,t]}}))}))},a.prototype.getSubmission=function(t){var r=this;void 0===t&&(t={});var n="function"==typeof this.keys?this.keys():this.keys,i=e.__assign(e.__assign({},a.keys),n),o={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(o.values.id=this.id);var u=function(e,t){var s=i[e].values;if(!s)return t;if("function"==typeof s)return s(t,o,r);if(t instanceof Array)return t.map((function(t){return u(e,t)}));if(s instanceof Array){var a=s.find((function(e){return e.value===t}));if(!a||!a.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return a.id}return s[t]};Object.keys(this.data).forEach((function(e){var t=r.data[e],a=function(e){return null==e};if(!a(t)){if(!i[e])return e=e.includes("smpAttr:")?e:s.snakeCase(e),void(o.values[e]=t);if(!a(t=u(e,t))){var n=i[e].id||e,c=Number.isNaN(Number(n))?n:"smpAttr:".concat(n);c=c.includes("smpAttr:")?c:s.snakeCase(c),o.values[c]=t}}})),this.samples.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.getSubmission(t);s&&o.samples.push(s)})),this.occurrences.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.getSubmission(t);s&&o.occurrences.push(s)})),this.media.forEach((function(e){var r=e.getSubmission(t);r&&o.media.push(r)}));var c=this.getSurvey();return c.modifySubmission?c.modifySubmission(o,this):o},Object.defineProperty(a.prototype,"isUploaded",{get:function(){return this.parent?this.parent.isUploaded:!!this.syncedAt},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),a.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}},training:{id:"training",values:l.boolToWarehouseValue},deleted:{id:"deleted",values:l.boolToWarehouseValue}},a}(i.default);exports.default=w,exports.getMediaFormData=_;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),s=require("lodash"),a=require("wellknown"),n=require("@flumens/utils"),i=require("../Model.js"),o=require("./ElasticOccurrence.js"),c=require("./ElasticSample.js"),u=require("./Media.js"),d=require("./Occurrence.js"),l=require("./helpers.js");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var h=p(r),m=p(a),f=function(t,r){return void 0===r&&(r={}),function(s){return s instanceof t?s:new t(e.__assign(e.__assign({},s),r))}};function v(e,t){var r,s,a,n,i;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(a=e.samples)||void 0===a||a.forEach((function(e,r){return v(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(n=e.occurrences)||void 0===n||n.forEach((function(e,r){return v(e,t.occurrences[r])}))),e.media&&t.media&&(null===(i=e.media)||void 0===i||i.forEach((function(e,r){return v(e,t.media[r])})));else{if("process"in window&&"test"===(null===(s=null===(r=window.process)||void 0===r?void 0:r.env)||void 0===s?void 0:s.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}var _=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,s,a;return e.__generator(this,(function(n){switch(n.label){case 0:return r=[],t.media?(s=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,t.getFormData()];case 1:return r=e.sent(),[2,[t,r]]}}))}))},[4,Promise.all(t.media.map(s))]):[3,2];case 1:a=n.sent(),r.push.apply(r,a),n.label=2;case 2:return t.occurrences?[4,Promise.all(t.occurrences.map(_))]:[3,4];case 3:a=n.sent(),r.push.apply(r,a.flat()),n.label=4;case 4:return t.samples?[4,Promise.all(t.samples.map(_))]:[3,6];case 5:a=n.sent(),r.push.apply(r,a.flat()),n.label=6;case 6:return[2,r]}}))}))};function y(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return y(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return y(e)}))),e.media&&(r.media=e.media.map((function(e){return y(e)}))),r}function g(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var w=function(r){function a(s){void 0===s&&(s={});var n=this,i=s.metadata,o=void 0===i?{}:i,c=s.samples,p=void 0===c?[]:c,h=s.occurrences,m=void 0===h?[]:h,v=s.media,_=void 0===v?[]:v,y=s.Sample,g=void 0===y?a:y,w=s.Occurrence,b=void 0===w?d.default:w,A=s.Media,O=void 0===A?u.default:A,E=s.skipStore,S=e.__rest(s,["metadata","samples","occurrences","media","Sample","Occurrence","Media","skipStore"]);S.createdAt=S.createdAt||(null==o?void 0:o.createdOn),S.updatedAt=S.updatedAt||(null==o?void 0:o.updatedOn),S.syncedAt=S.syncedAt||(null==o?void 0:o.syncedOn);var T=E?void 0:S.store;(n=r.call(this,e.__assign(e.__assign({},S),{store:T}))||this).validateRemote=l.validateRemoteModel,n.error=t.observable({message:""}),n.debouncedValue=300,n.keys=function(){var t;return e.__assign(e.__assign({},a.keys),(t=n.getSurvey().attrs||{},Object.keys(t).reduce((function(r,s){var a;return e.__assign(e.__assign({},r),((a={})[s]=t[s].remote||t[s],a))}),{})))},n.requiresRemoteSync=function(){return!n.syncedAt||n.updatedAt>n.syncedAt},n.Sample=g,n.Occurrence=b,n.Media=O,n.remote=t.observable({synchronising:!1,url:S.url,getAccessToken:S.getAccessToken}),n.metadata=t.observable(o);var k=p.map(f(n.Sample));n.samples=t.observable(k);var D=m.map(f(n.Occurrence,{Media:n.Media}));n.occurrences=t.observable(D);var q=_.map(f(n.Media));n.media=t.observable(q);var j=function(e){return e.parent=n};n.samples.forEach(j),n.occurrences.forEach(j),n.media.forEach(j);var N=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(j),n.setUpdatedAtTimestamp(Date.now())):e.removedCount&&n.setUpdatedAtTimestamp(Date.now()),e};return t.intercept(n.samples,N),t.intercept(n.occurrences,N),t.intercept(n.media,N),n}return e.__extends(a,r),a.fromElasticDTO=function(t,r,s){var a,n;void 0===r&&(r={});var i=t.id,o=t.event,c=t.location,u=t.metadata,d=r.url,p=new Date(o.date_start),h=new Date(u.updated_on).getTime(),f=Date.now(),v=c.point.split(",").map(parseFloat),_=v[0],y=v[1],g="OSGB"===c.output_sref_system?c.output_sref:"",w=c.geom?m.default.parse(c.geom):null,b=o.parent_event_id,A=l.parseRemoteAttrs(b?null==s?void 0:s.smp.attrs:null==s?void 0:s.attrs,o.attributes||[]),O=null===(a=o.media)||void 0===a?void 0:a.map((function(e){var t=e.path;return{id:t,metadata:{updatedOn:p,createdOn:p,syncedOn:p},data:{data:"".concat(d,"/upload/").concat(t)}}}));return new this(e.__assign({id:i,cid:o.source_system_key||i,createdAt:p.getTime(),updatedAt:h,syncedAt:f,metadata:{saved:!0},data:e.__assign(e.__assign({},A),{surveyId:u.survey.id,date:p.toISOString(),location:{code:c.code,name:c.name||c.verbatim_locality,latitude:_,longitude:y,shape:w,gridref:g},enteredSrefSystem:4326,groupId:null===(n=u.group)||void 0===n?void 0:n.id,comment:o.event_remarks,training:"true"===u.trial}),media:O},r))},a.prototype.setUpdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},a.prototype.toJSON=function(){var s,a,n,i=r.prototype.toJSON.call(this);return n=e.__assign(e.__assign({},i),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(s=this.samples)||void 0===s?void 0:s.map((function(e){return e.toJSON()})))||[],media:(null===(a=this.media)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[]}),JSON.parse(JSON.stringify(n))},a.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},a.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,n,i,o,c;return e.__generator(this,(function(u){switch(u.label){case 0:if(this.data.deleted)return[2];if(this.parent)return this.parent.save(),[2];if(!this.store)throw new Error("Trying to sync locally without a store");return t=this.toJSON(),r=t.data,s=t.metadata,a=t.occurrences,n=t.samples,i=t.media,o=e.__rest(t,["data","metadata","occurrences","samples","media"]),c=e.__assign(e.__assign({},o),{data:{data:r,metadata:s,occurrences:a,samples:n,media:i}}),[4,this.store.save(c)];case 1:return u.sent(),[2]}}))}))},a.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,a=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(a.media.map((function(e){return e.destroy(!0)}))),Promise.all(a.occurrences.map((function(e){return e.destroy(!0)})))])},this.parent?(this.parent.samples.remove(this),[4,r()]):[3,2];case 1:return e.sent(),t?[2]:(this.parent.save(),[2]);case 2:if(!this.store)throw new Error("Trying to sync locally without a store");return[4,this.store.delete(this.cid)];case 3:return e.sent(),null===(s=this.collection)||void 0===s||s.remove(this),[4,r()];case 4:return e.sent(),this.data.deleted=!0,[2]}}))}))},a.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():r.prototype.sync.call(this)]}))}))},a.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,n;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this.uploadMedia()];case 2:return t=e.sent(),r=this.toDTO(t),[4,this.postRemote(r)];case 3:return s=e.sent(),this.remote.synchronising=!1,v(this,s),a=(new Date).getTime(),this.updatedAt=a,this.syncedAt=a,this.save(),[3,5];case 4:throw n=e.sent(),this.remote.synchronising=!1,n;case 5:return[2]}}))}))},a.prototype.postRemote=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,a,i,o,c,u,d;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,3,,4]),o={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:return o.Authorization=s.apply("Bearer ",[e.sent()]),r=o,[4,h.default.post("".concat(this.remote.url,"/index.php/services/rest/samples"),t,{headers:r,timeout:12e4})];case 2:return[2,e.sent().data];case 3:if(a=e.sent(),409===(i=a).status&&(null===(c=i.response)||void 0===c?void 0:c.data.duplicate_of))return[2,y(this,i.response.data.duplicate_of.id)];if(n.isAxiosNetworkError(i))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===i.status)throw g(t),new Error(l.getErrorMessageFromObject(null===(d=null===(u=i.response)||void 0===u?void 0:u.data)||void 0===d?void 0:d.message));throw new Error(i.message);case 4:return[2]}}))}))},a.prototype.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,n,i,u,d,l,p,h,m,f,v,_,y,g,w,b,A,O=this;return e.__generator(this,(function(E){switch(E.label){case 0:if(!(t=this.remote.url)||t.includes("index.php"))throw new Error('A "remote" property is not configured.');if(!this.cid)throw new Error("Sample cid or id is missing for fetching remote model.");return[4,this.remote.getAccessToken()];case 1:return r=E.sent(),[4,c.fetchElasticSample({id:this.id,cid:this.cid,url:t,accessToken:r})];case 2:return s=E.sent(),this.data.surveyId||(this.data.surveyId=s.metadata.survey.id),a=this.getSurvey(),n=this.Sample.fromElasticDTO(s,{url:t},a),this.id=n.id,this.cid=n.cid||this.cid,Object.assign(this.data,n.data),Object.assign(this.metadata,n.metadata),i=c.fetchElasticSubSamples({parentId:this.id,url:t,accessToken:r}),u=o.fetchElasticOccurrences({parentId:this.id,url:t,accessToken:r}),[4,Promise.all([i,u])];case 3:return d=E.sent(),l=d[0],p=d[1],h=(new Date).getTime(),m=function(e){var r=O.Sample.fromElasticDTO(e,{url:t},O.getSurvey());return r.syncedAt=h,r},f=l.map(m),v=function(t,r){var s;return e.__assign(e.__assign({},t),((s={})[r.id]=r,s))},_=f.reduce(v,((b={})[this.id]=this,b)),this.samples.clear(),(A=this.samples).push.apply(A,f),y=function(e){var t=O.Occurrence.fromElasticDTO(e,O.remote.url,O.getSurvey());return t.syncedAt=h,[t,e.event.event_id]},g=p.map(y),w=function(e){var t=e[0],r=e[1];r!==parseInt(O.id,10)?_[r]?_[r].occurrences.push(t):console.log("Can't attach occ to missing ".concat(r," sample")):O.occurrences.push(t)},g.forEach(w),this.syncedAt=h,[2]}}))}))},a.prototype.updateRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,3,,4]),this.remote.synchronising=!0,t={},r=this.toDTO(t),[4,this.putRemote(this.id,r)];case 2:return v(this,e.sent()),s=(new Date).getTime(),this.updatedAt=s,this.syncedAt=s,this.save(),this.remote.synchronising=!1,[3,4];case 3:throw a=e.sent(),this.remote.synchronising=!1,a;case 4:return[2]}}))}))},a.prototype.putRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s,a,i,o,c,u,d;return e.__generator(this,(function(e){switch(e.label){case 0:return c={},a="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:c.Authorization=a.apply("Bearer ",[e.sent()]),s=c,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,h.default.put("".concat(this.remote.url,"/samples/").concat(t),r,{headers:s,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if(i=e.sent(),o=i,n.isAxiosNetworkError(o))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===o.status)throw g(r),new Error(l.getErrorMessageFromObject(null===(d=null===(u=o.response)||void 0===u?void 0:u.data)||void 0===d?void 0:d.message));throw new Error(o.message);case 5:return[2]}}))}))},a.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,i,o,c,u,d=this;return e.__generator(this,(function(l){switch(l.label){case 0:return t={},[4,_(this)];case 1:if(r=l.sent(),!r.length)return[2,t];s=function(t){return e.__awaiter(d,void 0,void 0,(function(){var r,s,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:return i={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:i.Authorization=s.apply("Bearer ",[e.sent()]),r=i,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,h.default.post("".concat(this.remote.url,"/index.php/services/rest/media-queue"),t,{headers:r,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if("timeout"===(a=e.sent()).message)throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");throw a;case 5:return[2]}}))}))},a=[],i=Date.now()-432e5,r.forEach((function(e){var r=e[0];r.syncedAt>i&&r.data.queued?t[r.cid]={name:r.data.queued}:a.push(e)})),o=5,c=function(r){var n,i,c,u;return e.__generator(this,(function(d){switch(d.label){case 0:return n=a.slice(r,r+o),i=new FormData,n.forEach((function(e){var t=e[1];return i.append.apply(i,t)})),[4,s(i)];case 1:return c=d.sent(),u=(new Date).getTime(),n.forEach((function(e){var t=e[0];t.syncedAt=u,t.data.queued=c[t.cid].name})),t=e.__assign(e.__assign({},t),c),[2]}}))},u=0,l.label=2;case 2:return u<a.length?[5,c(u)]:[3,5];case 3:l.sent(),l.label=4;case 4:return u+=o,[3,2];case 5:return[2,t]}}))}))},a.prototype.toDTO=function(t){var r=this;void 0===t&&(t={});var n="function"==typeof this.keys?this.keys():this.keys,i=e.__assign(e.__assign({},a.keys),n),o={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(o.values.id=this.id);var c=function(e,t){var s=i[e].values;if(!s)return t;if("function"==typeof s)return s(t,o,r);if(t instanceof Array)return t.map((function(t){return c(e,t)}));if(s instanceof Array){var a=s.find((function(e){return e.value===t}));if(!a||!a.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return a.id}return s[t]};Object.keys(this.data).forEach((function(e){var t=r.data[e],a=function(e){return null==e};if(!a(t)){if(!i[e])return e=e.includes("smpAttr:")?e:s.snakeCase(e),void(o.values[e]=t);if(!a(t=c(e,t))){var n=i[e].id||e,u=Number.isNaN(Number(n))?n:"smpAttr:".concat(n);u=u.includes("smpAttr:")?u:s.snakeCase(u),o.values[u]=t}}})),this.samples.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.toDTO(t);s&&o.samples.push(s)})),this.occurrences.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.toDTO(t);s&&o.occurrences.push(s)})),this.media.forEach((function(e){var r=e.toDTO(t);r&&o.media.push(r)}));var u=this.getSurvey();return u.modifySubmission?u.modifySubmission(o,this):o},Object.defineProperty(a.prototype,"isUploaded",{get:function(){return this.parent?this.parent.isUploaded:!!this.syncedAt},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),a.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}}},a}(i.default);exports.default=w,exports.getMediaFormData=_;
@@ -1,26 +1,26 @@
1
1
  import Collection, { Options as CollectionOptions } from '../Collection';
2
2
  import Store from '../Stores/Store';
3
3
  import Occurrence from './Occurrence';
4
- import Sample, { Remote } from './Sample';
4
+ import Sample from './Sample';
5
5
  export type Options<T extends Sample> = {
6
6
  models?: T[];
7
7
  store?: Store;
8
8
  Model?: typeof Sample<any, any>;
9
9
  Occurrence?: typeof Occurrence<any, any>;
10
- url?: Remote['url'];
11
- getAccessToken?: Remote['getAccessToken'];
10
+ url?: string;
11
+ getAccessToken?: () => Promise<string>;
12
12
  } & CollectionOptions<T>;
13
13
  export default class SampleCollection<T extends Sample> extends Collection<T> {
14
- remote: Remote;
14
+ protected remote: {
15
+ synchronising: boolean;
16
+ url: string;
17
+ getAccessToken: () => Promise<string>;
18
+ };
15
19
  Occurrence?: typeof Occurrence<any, any>;
16
- cidMap: Map<string, Sample>;
17
20
  constructor(options: Options<T>);
18
- fetch: () => Promise<void>;
19
- fetchRemote: (from: number, surveyIDs: any[]) => Promise<T[]>;
20
- removeAllSynced: () => Promise<any[]>;
21
- /**
22
- * Reverse order so that newest are at the top of list.
23
- */
24
- comparator: (a: any) => number;
25
- reset: () => Promise<void>;
21
+ fetch(): Promise<void>;
22
+ fetchRemote(from: number, surveyIDs: any[]): Promise<T[]>;
23
+ removeAllSynced(): Promise<any[]>;
24
+ reset(): Promise<void>;
25
+ get isSynchronising(): boolean;
26
26
  }
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),n=require("../Collection.js"),a=require("./ElasticOccurrence.js"),s=require("./ElasticSample.js");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=i(r),o=function(r){function n(n){var i=r.call(this,n)||this;i.remote=t.observable({synchronising:!1,url:null,getAccessToken:function(){return Promise.resolve("auth token is missing")},timeout:12e4}),i.fetch=function(){return e.__awaiter(i,void 0,void 0,(function(){var t,r,n,a=this;return e.__generator(this,(function(s){switch(s.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=s.sent(),r=function(t){var r=t.data,n=r.data,s=r.metadata,i=r.occurrences,c=r.samples,o=r.media,u=r.attrs;return new a.Model(e.__assign(e.__assign({},t),{attrs:u,data:n,metadata:s,occurrences:i,samples:c,media:o}))},n=t.map(r),this.push.apply(this,n),this.ready.resolve(!0),[2]}}))}))},i.fetchRemote=function(t,r){return e.__awaiter(i,void 0,void 0,(function(){var n,i,o,u,d,l,f,h,m,p,v,_,g,y,b,w,A,M,O,k,E,T,j=this;return e.__generator(this,(function(q){switch(q.label){case 0:return console.log("Fetching remote samples, page",t),n={bool:{must_not:{exists:{field:"event.parent_event_id"}}}},i={match:{"metadata.trial":"false"}},o=function(e){return{match:{"metadata.survey.id":e}}},u={bool:{should:r.map(o)}},d=[u,n,i],l=JSON.stringify({from:t,size:100,query:{bool:{must:d}},sort:[{"metadata.created_on":"desc"}]}),f=this.remote.url,[4,this.remote.getAccessToken()];case 1:return h=q.sent(),m={method:"post",url:"".concat(f,"/index.php/services/rest/es-samples/_search"),headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(h)},data:l},[4,c.default.request(m)];case 2:return p=q.sent(),v=function(e){return e._source},_=p.data.hits.hits.map(v),g=_.map((function(e){return e.id})),y=s.fetchElasticSubSamples({parentId:g,url:f,accessToken:h}),b=a.fetchElasticOccurrences({parentId:g,url:f,accessToken:h}),[4,Promise.all([y,b])];case 3:return w=q.sent(),A=w[0],M=w[1],O=function(e){return!!e},k=_.map(function(t,r,n,a,s){return function(i){var c,o,u=(new Date).getTime();try{var d=new n({skipStore:!0});d.data.surveyId=i.metadata.survey.id;var l=d.getSurvey(),f=n.dto(i,t,l);d.id=f.id,d.cid=f.cid||d.cid,Object.assign(d.data,f.data),Object.assign(d.metadata,f.metadata);var h=function(e){return e.event.parent_event_id===d.id||e.event.event_id===d.id},m=a.filter(h).map((function(e){var r=n.dto(e,t,l),a=new n(r);return a.syncedAt=u,a})),p=m.reduce((function(t,r){var n;return e.__assign(e.__assign({},t),((n={})[r.id]=r,n))}),((c={})[d.id]=d,c));return s.filter(h).map((function(e){var n=r.dto(e,t,l),a=new r(n);return a.syncedAt=u,[a,e.event.event_id]})).forEach((function(e){var t=e[0],r=e[1];r!==parseInt(d.id,10)?p[r]?p[r].occurrences.push(t):console.log("Can't attach occ to missing ".concat(r," sample")):d.occurrences.push(t)})),(o=d.samples).push.apply(o,m),d.syncedAt=u,d}catch(e){return console.warn(JSON.stringify(i)),console.error(e),null}}}(f,this.Occurrence,this.Model,A,M)).filter(O),E=function(e){return!j.cidMap.has(e.cid)},T=k.filter(E),this.push.apply(this,T),[2,T]}}))}))},i.removeAllSynced=function(){var e=[];return i.forEach((function(t){t.syncedAt&&e.push(t.destroy())})),Promise.all(e)},i.comparator=function(e){return-new Date(e.createdAt).getTime()},i.reset=function(){return e.__awaiter(i,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return t=this.map((function(e){return e.destroy()})),[4,Promise.all(t)];case 1:return e.sent(),[2]}}))}))},i.Occurrence=n.Occurrence,i.remote.url=n.url,i.remote.getAccessToken=n.getAccessToken,i.cidMap=new Map;t.intercept(i,(function(e){if(e.added&&e.added.length){e.added.forEach((function(e){i.cidMap.set(e.cid,e)}))}if(e.removedCount>0){var t=Array.from(i.cidMap.keys())[e.index];i.cidMap.delete(t)}return e}));return t.observe(i,(function(e){e.addedCount&&e.added.forEach((function(e){return e.collection=i})),e.removedCount&&e.removed.forEach((function(e){return delete e.collection}))})),i}return e.__extends(n,r),n}(n.default);exports.default=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),n=require("../Collection.js"),a=require("./ElasticOccurrence.js"),s=require("./ElasticSample.js"),i=require("./Sample.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=o(r),u=function(r){function n(n){var a=r.call(this,e.__assign({id:"samples",Model:i.default},n))||this;a.Occurrence=n.Occurrence,a.remote=t.observable({synchronising:!1,url:n.url,getAccessToken:n.getAccessToken});return t.observe(a.data,(function(e){e.addedCount&&e.added.forEach((function(e){return e.collection=a})),e.removedCount&&e.removed.forEach((function(e){return delete e.collection}))})),a}return e.__extends(n,r),n.prototype.fetch=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,a,s=this;return e.__generator(this,(function(i){switch(i.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=i.sent(),r=function(t){var r=t.data,n=r.data,a=r.metadata,i=r.occurrences,o=r.samples,c=r.media,u=r.attrs;return new s.Model(e.__assign(e.__assign({},t),{attrs:u,data:n,metadata:a,occurrences:i,samples:o,media:c}))},n=t.map(r),(a=this.data).push.apply(a,n),this.ready.resolve(!0),[2]}}))}))},n.prototype.fetchRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var n,i,o,u,d,l,f,p,h,m,v,_,y,g,b,O,E,j,w,A,S,T,q,x=this;return e.__generator(this,(function(k){switch(k.label){case 0:return console.log("Fetching remote samples, page",t),n={bool:{must_not:{exists:{field:"event.parent_event_id"}}}},i={match:{"metadata.trial":"false"}},o=function(e){return{match:{"metadata.survey.id":e}}},u={bool:{should:r.map(o)}},d=[u,n,i],l=JSON.stringify({from:t,size:100,query:{bool:{must:d}},sort:[{"metadata.created_on":"desc"}]}),f=this.remote.url,[4,this.remote.getAccessToken()];case 1:return p=k.sent(),h={method:"post",url:"".concat(f,"/index.php/services/rest/es-samples/_search"),headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(p)},data:l},[4,c.default.request(h)];case 2:return m=k.sent(),v=function(e){return e._source},_=m.data.hits.hits.map(v),y=_.map((function(e){return e.id})),g=s.fetchElasticSubSamples({parentId:y,url:f,accessToken:p}),b=a.fetchElasticOccurrences({parentId:y,url:f,accessToken:p}),[4,Promise.all([g,b])];case 3:return O=k.sent(),E=O[0],j=O[1],w=function(e){return!!e},A=_.map(function(t,r,n,a,s){return function(i){var o,c,u=(new Date).getTime();try{var d=new n({skipStore:!0});d.data.surveyId=i.metadata.survey.id;var l=d.getSurvey(),f=n.fromElasticDTO(i,{url:t},l);d.id=f.id,d.cid=f.cid||d.cid,Object.assign(d.data,f.data),Object.assign(d.metadata,f.metadata);var p=function(e){return e.event.parent_event_id===d.id||e.event.event_id===d.id},h=a.filter(p).map((function(e){var r=n.fromElasticDTO(e,{url:t},l);return r.syncedAt=u,r})),m=h.reduce((function(t,r){var n;return e.__assign(e.__assign({},t),((n={})[r.id]=r,n))}),((o={})[d.id]=d,o));return s.filter(p).map((function(e){var n=r.fromElasticDTO(e,t,l);return n.syncedAt=u,[n,e.event.event_id]})).forEach((function(e){var t=e[0],r=e[1];r!==parseInt(d.id,10)?m[r]?m[r].occurrences.push(t):console.log("Can't attach occ to missing ".concat(r," sample")):d.occurrences.push(t)})),(c=d.samples).push.apply(c,h),d.syncedAt=u,d}catch(e){return console.warn(JSON.stringify(i)),console.error(e),null}}}(f,this.Occurrence,this.Model,E,j)).filter(w),S=function(e){return!x.cidMap.has(e.cid)},T=A.filter(S),(q=this.data).push.apply(q,T),[2,T]}}))}))},n.prototype.removeAllSynced=function(){var e=[];return this.data.forEach((function(t){t.syncedAt&&e.push(t.destroy())})),Promise.all(e)},n.prototype.reset=function(){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return t=this.data.map((function(e){return e.destroy()})),[4,Promise.all(t)];case 1:return e.sent(),[2]}}))}))},Object.defineProperty(n.prototype,"isSynchronising",{get:function(){return this.remote.synchronising},enumerable:!1,configurable:!0}),n}(n.default);exports.default=u;
@@ -18,7 +18,6 @@ export interface RemoteConfig {
18
18
  [key: string]: string | number | null;
19
19
  } | ((value: any, submission: any, model: any) => any);
20
20
  }
21
- export declare const boolToWarehouseValue: (val?: boolean | "t" | "f" | null) => "t" | "f";
22
21
  export type Keys = (() => {
23
22
  [key: string]: RemoteConfig;
24
23
  }) | {
@@ -34,6 +33,7 @@ interface RemoteAttr {
34
33
  id: string;
35
34
  }
36
35
  type AttrConfig = any;
36
+ export declare const getCamelCaseObj: (dto: any) => import("lodash").Dictionary<any>;
37
37
  export declare const parseRemoteAttrs: (config: {
38
38
  [key: string]: AttrConfig;
39
39
  }, remoteAttrs: RemoteAttr[]) => any;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e,t){for(var r=atob(e.split(",")[1]),n=[],s=0;s<r.length;s++)n.push(r.charCodeAt(s));return new Blob([new Uint8Array(n)],{type:t})}function r(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.boolToWarehouseValue=function(e){return!0===e||"t"===e?"t":"f"},exports.dataURItoBlob=t,exports.getBlobFromURL=function(e,n){if(r(e)){var s=t(e,n);return Promise.resolve(s)}return new Promise((function(t){var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.onload=function(){var e=r.response;t(e)},r.send()}))},exports.getErrorMessageFromObject=function(e){return Object.entries(e).reduce((function(e,t){return"".concat(e).concat(t[0]," ").concat(t[1],"\n")}),"")},exports.isDataURL=r,exports.parseRemoteAttrs=function(e,t){e=e||{};var r=Object.entries(e);return t.reduce((function(e,t){var n=r.find((function(e){var r;return(null===(r=e[1].remote)||void 0===r?void 0:r.id)===parseInt(t.id,10)}));if(!n)return e;var s=n[0],o=isNaN(t.value)?t.value:parseFloat(t.value);return e[s]=o,e}),{})},exports.validateRemoteModel=function(){var t=this.getSurvey(),r=t.verify&&t.verify(this.data,this),n={};if(r){var s=r&&"issues"in r;!("ValidationError"===(null==r?void 0:r.name)||"ValidationError"===(null==r?void 0:r.type))&&!s?n.errors=[r.message]:s?n.errors=r.issues.map((function(e){return e.message})):n=e.__assign({},r)}var o=function(e,t){var r=t.validateRemote();return r&&(e[t.cid]=r,e[t.cid].model=t),e},a=(this.samples||[]).reduce(o,{}),i=(this.occurrences||[]).reduce(o,{}),u=(this.media||[]).reduce(o,{});return Object.keys(n).length||Object.keys(a).length||Object.keys(i).length||Object.keys(u).length?{attributes:n,model:this,models:e.__assign(e.__assign(e.__assign({},a),i),u)}:null};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("lodash");function t(e,r){for(var t=atob(e.split(",")[1]),n=[],s=0;s<t.length;s++)n.push(t.charCodeAt(s));return new Blob([new Uint8Array(n)],{type:r})}function n(e){if(!e)return!1;return!!e.toString().match(/^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i)}exports.dataURItoBlob=t,exports.getBlobFromURL=function(e,r){if(n(e)){var s=t(e,r);return Promise.resolve(s)}return new Promise((function(r){var t=new XMLHttpRequest;t.open("GET",e,!0),t.responseType="blob",t.onload=function(){var e=t.response;r(e)},t.send()}))},exports.getCamelCaseObj=function(e){return r.mapKeys(e,(function(e,t){return r.camelCase(t)}))},exports.getErrorMessageFromObject=function(e){return Object.entries(e).reduce((function(e,r){return"".concat(e).concat(r[0]," ").concat(r[1],"\n")}),"")},exports.isDataURL=n,exports.parseRemoteAttrs=function(e,r){e=e||{};var t=Object.entries(e);return r.reduce((function(e,r){var n=t.find((function(e){var t;return(null===(t=e[1].remote)||void 0===t?void 0:t.id)===parseInt(r.id,10)}));if(!n)return e;var s=n[0],a=isNaN(r.value)?r.value:parseFloat(r.value);return e[s]=a,e}),{})},exports.validateRemoteModel=function(){var r=this.getSurvey(),t=r.verify&&r.verify(this.data,this),n={};if(t){var s=t&&"issues"in t;!("ValidationError"===(null==t?void 0:t.name)||"ValidationError"===(null==t?void 0:t.type))&&!s?n.errors=[t.message]:s?n.errors=t.issues.map((function(e){return e.message})):n=e.__assign({},t)}var a=function(e,r){var t=r.validateRemote();return t&&(e[r.cid]=t,e[r.cid].model=r),e},o=(this.samples||[]).reduce(a,{}),i=(this.occurrences||[]).reduce(a,{}),u=(this.media||[]).reduce(a,{});return Object.keys(n).length||Object.keys(o).length||Object.keys(i).length||Object.keys(u).length?{attributes:n,model:this,models:e.__assign(e.__assign(e.__assign({},o),i),u)}:null};
package/dist/Model.d.ts CHANGED
@@ -84,5 +84,6 @@ export default class Model<T extends Data = Data> {
84
84
  syncedAt: number | null | undefined;
85
85
  data: T;
86
86
  };
87
- resetDefaults(defaultsToSet?: any): Promise<void>;
87
+ reset(defaultsToSet?: any): Promise<void>;
88
+ get isStored(): boolean;
88
89
  }
package/dist/Model.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),s=require("mobx-utils"),r=require("@flumens/utils"),i=function(t){return JSON.parse(JSON.stringify(t))},a={},n=function(){function n(n){var o=n.id,d=void 0===o?"":o,u=n.cid,c=void 0===u?"":u,h=n.createdAt,l=n.updatedAt,v=n.syncedAt,f=n.data,p=void 0===f?{}:f,y=n.attrs,_=void 0===y?{}:y,b=n.store,A=this;this.ready=new r.Deferred,this.debouncedValue=3e3,this._observerPaused=!1,this.id=d,this.cid=c||d||r.UUIDv7();var w,g=Date.now();this.createdAt=h||g,this.updatedAt=l||g,this.syncedAt=v,this.data=i(t.__assign(t.__assign(t.__assign({},a),p),_)),e.makeObservable(this,{createdAt:e.observable,updatedAt:e.observable,syncedAt:e.observable,data:e.observable}),this.store=b;s.deepObserve(this.data,(function(){A._observerPaused||(A.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(w),w=setTimeout((function(){return A.sync.apply(A,t)}),A.debouncedValue)}())}))}return n.prototype.setUpdatedAtTimestamp=function(t){this.updatedAt=t},n.prototype.fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){var s;return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.store.find(this.cid)]:(this.ready.resolve(!1),[2]);case 1:return(s=t.sent())?[3,3]:[4,this.save()];case 2:return t.sent(),this.ready.resolve(!0),[2];case 3:return s.id&&(this.id=s.id),s.cid&&(this.cid=s.cid),this._observerPaused=!0,e.set(this.data,s.data),this._observerPaused=!1,this.createdAt=s.createdAt,this.updatedAt=s.updatedAt,this.syncedAt=s.syncedAt,this.ready.resolve(!0),[2]}}))}))},n.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.store)throw new Error("Trying to save locally without a store");return e=this.toJSON(),[4,this.store.save(e)];case 1:return t.sent(),[2]}}))}))},n.prototype.destroy=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.store)throw new Error("Trying to delete locally without a store");return[4,this.store.delete(this.cid)];case 1:return t.sent(),[2]}}))}))},n.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.save()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},n.prototype.toJSON=function(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,data:e.toJS(this.data)}},n.prototype.resetDefaults=function(s){var r=this;this.id="";var i=JSON.parse(JSON.stringify(t.__assign(t.__assign({},a),s)));e.set(this.data,i);var n=Object.keys(i);return Object.keys(this.data).forEach((function(t){n.includes(t)||(r.data[t]=null,delete r.data[t])})),this.save()},n}();exports.copyObject=i,exports.default=n;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("mobx-utils"),s=require("@flumens/utils"),i=function(t){return JSON.parse(JSON.stringify(t))},a={},n=function(){function n(n){var o=n.id,d=void 0===o?"":o,u=n.cid,c=void 0===u?"":u,h=n.createdAt,l=n.updatedAt,v=n.syncedAt,p=n.data,f=void 0===p?{}:p,y=n.attrs,b=void 0===y?{}:y,_=n.store,A=this;this.ready=new s.Deferred,this.debouncedValue=3e3,this._observerPaused=!1,this.id=d,this.cid=c||d||s.UUIDv7();var w,g=Date.now();this.createdAt=h||g,this.updatedAt=l||g,this.syncedAt=v,this.data=i(t.__assign(t.__assign(t.__assign({},a),f),b)),e.makeObservable(this,{createdAt:e.observable,updatedAt:e.observable,syncedAt:e.observable,data:e.observable}),this.store=_;r.deepObserve(this.data,(function(){A._observerPaused||(A.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(w),w=setTimeout((function(){return A.sync.apply(A,t)}),A.debouncedValue)}())}))}return n.prototype.setUpdatedAtTimestamp=function(t){this.updatedAt=t},n.prototype.fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.store.find(this.cid)]:(this.ready.resolve(!1),[2]);case 1:return(r=t.sent())?[3,3]:[4,this.save()];case 2:return t.sent(),this.ready.resolve(!0),[2];case 3:return r.id&&(this.id=r.id),r.cid&&(this.cid=r.cid),this._observerPaused=!0,e.set(this.data,r.data),this._observerPaused=!1,this.createdAt=r.createdAt,this.updatedAt=r.updatedAt,this.syncedAt=r.syncedAt,this.ready.resolve(!0),[2]}}))}))},n.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.store)throw new Error("Trying to save locally without a store");return e=this.toJSON(),[4,this.store.save(e)];case 1:return t.sent(),[2]}}))}))},n.prototype.destroy=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.store)throw new Error("Trying to delete locally without a store");return[4,this.store.delete(this.cid)];case 1:return t.sent(),[2]}}))}))},n.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.save()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},n.prototype.toJSON=function(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,data:e.toJS(this.data)}},n.prototype.reset=function(r){var s=this;this.id="";var i=JSON.parse(JSON.stringify(t.__assign(t.__assign({},a),r)));e.set(this.data,i);var n=Object.keys(i);return Object.keys(this.data).forEach((function(t){n.includes(t)||(s.data[t]=null,delete s.data[t])})),this.save()},Object.defineProperty(n.prototype,"isStored",{get:function(){return!!this.store},enumerable:!1,configurable:!0}),n}();exports.copyObject=i,exports.default=n;
package/dist/index.d.ts CHANGED
@@ -7,4 +7,8 @@ export { default as ElasticIndiciaOccurrence } from './Indicia/ElasticOccurrence
7
7
  export { default as ElasticIndiciaSample } from './Indicia/ElasticSample';
8
8
  export { default as IndiciaOccurrence } from './Indicia/Occurrence';
9
9
  export { default as IndiciaSample } from './Indicia/Sample';
10
+ export { default as IndiciaGroup, dtoSchema as groupDtoSchema, } from './Indicia/Group';
11
+ export { default as IndiciaLocation, dtoSchema as locationDtoSchema, LocationType, } from './Indicia/Location';
10
12
  export { default as IndiciaSampleCollection } from './Indicia/SampleCollection';
13
+ export { default as IndiciaGroupCollection, byGroupMembershipStatus, } from './Indicia/GroupCollection';
14
+ export { default as IndiciaLocationCollection, byLocationType, } from './Indicia/LocationCollection';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./Drupal/User.js"),r=require("./Stores/SQLiteDatabase.js"),t=require("./Stores/LocalForageStore.js"),a=require("./Stores/SQLiteStore.js"),i=require("./Stores/Store.js"),o=require("./Model.js"),s=require("./Collection.js"),l=require("./Indicia/Media.js"),u=require("./Indicia/Occurrence.js"),d=require("./Indicia/Sample.js"),c=require("./Indicia/SampleCollection.js");exports.DrupalUserModel=e.default,exports.SQLiteDatabase=r.default,exports.LocalForageStore=t.default,exports.SQLiteStore=a.default,exports.IStore=i.default,exports.Model=o.default,exports.Collection=s.default,exports.IndiciaMedia=l.default,exports.IndiciaOccurrence=u.default,exports.IndiciaSample=d.default,exports.IndiciaSampleCollection=c.default;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./Drupal/User.js"),r=require("./Stores/SQLiteDatabase.js"),o=require("./Stores/LocalForageStore.js"),t=require("./Stores/SQLiteStore.js"),i=require("./Stores/Store.js"),a=require("./Model.js"),s=require("./Collection.js"),c=require("./Indicia/Media.js"),u=require("./Indicia/Occurrence.js"),l=require("./Indicia/Sample.js"),p=require("./Indicia/Group.js"),d=require("./Indicia/Location.js"),n=require("./Indicia/SampleCollection.js"),S=require("./Indicia/GroupCollection.js"),x=require("./Indicia/LocationCollection.js");exports.DrupalUserModel=e.default,exports.SQLiteDatabase=r.default,exports.LocalForageStore=o.default,exports.SQLiteStore=t.default,exports.IStore=i.default,exports.Model=a.default,exports.Collection=s.default,exports.IndiciaMedia=c.default,exports.IndiciaOccurrence=u.default,exports.IndiciaSample=l.default,exports.IndiciaGroup=p.default,exports.groupDtoSchema=p.dtoSchema,exports.IndiciaLocation=d.default,Object.defineProperty(exports,"LocationType",{enumerable:!0,get:function(){return d.LocationType}}),exports.locationDtoSchema=d.dtoSchema,exports.IndiciaSampleCollection=n.default,exports.IndiciaGroupCollection=S.default,exports.byGroupMembershipStatus=S.byGroupMembershipStatus,exports.IndiciaLocationCollection=x.default,exports.byLocationType=x.byLocationType;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {