1 import {Observable} from 'rxjs';
2 import {from} from 'rxjs';
3 import {tap, concatMap} from 'rxjs/operators';
4 import {Injectable} from '@angular/core';
5 import {AuthService} from '@eg/core/auth.service';
6 import {EventService} from '@eg/core/event.service';
7 import {IdlObject, IdlService} from '@eg/core/idl.service';
8 import {NetService} from '@eg/core/net.service';
9 import {OrgService} from '@eg/core/org.service';
10 import {PcrudService} from '@eg/core/pcrud.service';
11 import {DbStoreService} from '@eg/core/db-store.service';
13 /** Service for storing and fetching data related to offline services/interfaces */
15 const OFFLINE_CACHE_TIMEOUT = 86400000; // 1 day
18 export class OfflineService {
23 private auth: AuthService,
24 private evt: EventService,
25 private idl: IdlService,
26 private net: NetService,
27 private org: OrgService,
28 private pcrud: PcrudService,
29 private db: DbStoreService
32 refreshOfflineData(): Promise<any> {
33 return this.cacheNeedsUpdating()
36 return this.clearOfflineCache()
37 .then(_ => this.fetchOfflineData());
42 clearOfflineCache(): Promise<any> {
43 return this.db.request(
44 {schema: 'cache', table: 'Object', action: 'deleteAll'})
46 .then(_ => this.db.request(
47 {schema: 'cache', table: 'StatCat', action: 'deleteAll'})
51 fetchOfflineData(): Promise<any> {
53 // Start with the org unit list which is already loaded.
54 this.addListToCache('aou', this.org.list());
56 return this.net.request(
58 'open-ils.circ.offline.data.retrieve',
61 .pipe(concatMap(data => {
62 if (data.idl_class === 'actsc') {
63 return from(this.addStatCatsToCache(data.data));
65 return from(this.addListToCache(data.idl_class, data.data));
71 cacheNeedsUpdating(): Promise<boolean> {
73 return this.db.request({
76 action: 'selectWhereEqual',
78 value: 'pgt' // most likely to have data
81 if (!row) { return true; }
82 return (new Date().getTime() - row.cachedate.getTime()) > OFFLINE_CACHE_TIMEOUT;
86 addListToCache(idlClass: string, list: IdlObject[]): Promise<any> {
88 const pkey = this.idl.classes[idlClass].pkey;
89 const rows = list.map(item => {
92 id: '' + item[pkey](),
93 object: this.idl.toHash(item)
97 return this.db.request({
103 return this.db.request({
106 action: 'insertOrReplace',
107 rows: [{type: idlClass, cachedate: new Date()}]
112 addStatCatsToCache(statcats: IdlObject[]): Promise<any> {
113 if (!statcats || statcats.length === 0) {
114 return Promise.resolve();
117 const rows = statcats.map(
118 cat => ({id: cat.id(), value: this.idl.toHash(cat)}));
120 return this.db.request({