added the edit and delete event offline

This commit is contained in:
Eudes Inácio
2021-10-20 11:06:00 +01:00
parent a77fffe6f8
commit f181bd12d9
7 changed files with 163 additions and 188 deletions
+12 -28
View File
@@ -23,7 +23,7 @@ import { Network } from '@ionic-native/network/ngx';
import { BackgroundService } from 'src/app/services/background.service'; import { BackgroundService } from 'src/app/services/background.service';
import { OfflineManagerService } from 'src/app/services/offline-manager.service'; import { OfflineManagerService } from 'src/app/services/offline-manager.service';
import { Storage } from '@ionic/storage'; import { Storage } from '@ionic/storage';
import { EventsService} from 'src/app/services/events.service'; import { EventsService } from 'src/app/services/events.service';
@Component({ @Component({
@@ -81,11 +81,10 @@ export class HomePage implements OnInit {
private inativityService: InativityService, private inativityService: InativityService,
private storageService: StorageService, private storageService: StorageService,
private webNotificationPopupService: WebNotificationPopupService, private webNotificationPopupService: WebNotificationPopupService,
private network: Network,
private backgroundservice: BackgroundService, private backgroundservice: BackgroundService,
private offlinemanager: OfflineManagerService, private offlinemanager: OfflineManagerService,
private storage: Storage, private storage: Storage,
private eventservice: EventsService ) { private eventservice: EventsService) {
this.webNotificationPopupService.askNotificationPermission() this.webNotificationPopupService.askNotificationPermission()
@@ -118,37 +117,20 @@ export class HomePage implements OnInit {
window.addEventListener('online', () => { window.addEventListener('online', () => {
console.log('Became online') console.log('Became online')
this.backgroundservice.online() this.backgroundservice.online()
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
this.webnotification.webconnection();
this.webnotification.register();
} else {
this.mobilefirstConnect();
this.notificationsService.onReceviNotification();
this.offlinemanager.synchnize()
}
}); });
window.addEventListener('offline', () => { window.addEventListener('offline', () => {
console.log('Became offline') console.log('Became offline')
this.backgroundservice.offline() this.backgroundservice.offline()
}); });
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
this.webnotification.webconnection();
this.webnotification.register();
} else {
window.addEventListener('online', (on) => {
console.log('Became online',on)
this.storage.get('storedreq').then((req) =>{
console.log('STORED REQUEST', req)
req.forEach(element => {
this.eventservice.editEvent(element,2,3).subscribe((res) =>{
console.log('REQUEST RESULT', res)
})
});
})
this.backgroundservice.online()
});
window.addEventListener('offline', (off) => {
console.log('Became offline',off)
this.backgroundservice.offline()
});
this.mobilefirstConnect();
this.notificationsService.onReceviNotification();
}
this.updateList() this.updateList()
var myWorker = new Worker(new URL('./nice.worker.js', import.meta.url)); var myWorker = new Worker(new URL('./nice.worker.js', import.meta.url));
@@ -197,6 +179,8 @@ export class HomePage implements OnInit {
} }
} }
updateList() { updateList() {
this.notificationsService.registerCallback( this.notificationsService.registerCallback(
@@ -209,6 +209,7 @@ export class EditEventPage implements OnInit {
this.toastService.successMessage(); this.toastService.successMessage();
}, error => { }, error => {
if(error.status != 0)
this.toastService.badRequest() this.toastService.badRequest()
}); });
@@ -18,6 +18,7 @@ import { DocumentSetUpMeetingPage } from 'src/app/modals/document-set-up-meeting
import { ExpedientTaskModalPage } from '../../gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page'; import { ExpedientTaskModalPage } from '../../gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page'; import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { BackgroundService } from 'src/app/services/background.service'; import { BackgroundService } from 'src/app/services/background.service';
import { StorageService } from 'src/app/services/storage.service';
@Component({ @Component({
selector: 'app-view-event', selector: 'app-view-event',
@@ -66,7 +67,8 @@ export class ViewEventPage implements OnInit {
private location: Location, private location: Location,
public platform: Platform, public platform: Platform,
private sqliteservice: SqliteService, private sqliteservice: SqliteService,
private backgroundservice: BackgroundService private backgroundservice: BackgroundService,
private storage: StorageService
) { ) {
this.isEventEdited = false; this.isEventEdited = false;
this.loadedEvent = new Event(); this.loadedEvent = new Event();
@@ -100,6 +102,22 @@ export class ViewEventPage implements OnInit {
this.loadEvent(); this.loadEvent();
this.backgroundservice.registerBackService('Online', () => { this.backgroundservice.registerBackService('Online', () => {
this.storage.get('eventEdit').then((req) => {
JSON.parse(req).forEach(element => {
this.eventsService.editEvent(element, 2, 3).subscribe((res) => {
this.storage.remove('eventEdit')
console.log('eventEdit synchnize', res)
})
});
})
this.storage.get('eventDelete').then((req) => {
JSON.parse(req).forEach(element => {
this.eventsService.editEvent(element, 2, 3).subscribe((res) => {
this.storage.remove('eventDelete')
console.log('eventEdit synchnize', res)
})
});
})
this.loadEvent(); this.loadEvent();
}); });
+54 -46
View File
@@ -19,6 +19,7 @@ import { ExpedienteGdStore } from 'src/app/store/expedientegd-store.service';
import { SqliteService } from 'src/app/services/sqlite.service'; import { SqliteService } from 'src/app/services/sqlite.service';
import { NetworkConnectionService } from 'src/app/services/network-connection.service' import { NetworkConnectionService } from 'src/app/services/network-connection.service'
import { BackgroundService } from 'src/app/services/background.service'; import { BackgroundService } from 'src/app/services/background.service';
import { momentG } from 'src/plugin/momentG';
@Component({ @Component({
selector: 'app-events', selector: 'app-events',
@@ -107,14 +108,10 @@ export class EventsPage implements OnInit {
// console.log('Resize event detected'); // console.log('Resize event detected');
}); });
try {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) { this.sqliteservice.databaseConn();
} else { } catch (error) {
try { console.log("Error creating local database: ", error)
this.sqliteservice.databaseConn();
} catch (error) {
console.log("Error creating local database: ", error)
}
} }
} }
@@ -208,18 +205,9 @@ export class EventsPage implements OnInit {
const list = mdOficialEvents.concat(mdPessoalEvents); const list = mdOficialEvents.concat(mdPessoalEvents);
console.log("getAllMdOficialPessoalEvents", list) console.log("getAllMdOficialPessoalEvents", list)
if (this.platform.is('desktop') || this.platform.is('mobileweb')) { this.addEventToDb(list);
} else {
if (list.length > 0) {
list.forEach(element => {
this.sqliteservice.addEvent(element)
});
}
}
this.listToPresent = list this.listToPresent = list
if (list.length > 0) { if (list.length > 0) {
this.currentEvent = list[0].Subject; this.currentEvent = list[0].Subject;
this.currentHoursMinutes = list[0].StartDate; this.currentHoursMinutes = list[0].StartDate;
@@ -236,14 +224,7 @@ export class EventsPage implements OnInit {
const list = prOficialEvents.concat(prPessoalEvents); const list = prOficialEvents.concat(prPessoalEvents);
console.log("getAllPrOficialPessoalEvents", list) console.log("getAllPrOficialPessoalEvents", list)
if (this.platform.is('desktop') || this.platform.is('mobileweb')) { this.addEventToDb(list);
} else {
if (list.length > 0) {
list.forEach(element => {
this.sqliteservice.addEvent(element)
});
}
}
if (list.length > 0) { if (list.length > 0) {
this.currentEvent = list[0].Subject; this.currentEvent = list[0].Subject;
this.currentHoursMinutes = list[0].StartDate; this.currentHoursMinutes = list[0].StartDate;
@@ -326,38 +307,65 @@ export class EventsPage implements OnInit {
} */ } */
} }
addEventToDb(list) {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
} else {
if (list.length > 0) {
list.forEach(element => {
this.sqliteservice.addEvent(element)
});
}
}
}
getEventsFromLocalDb() { getEventsFromLocalDb() {
/* window.addEventListener('online', (on) => { let date = new Date();
this.showGreeting(); date.setMonth(date.getMonth() + 1);
let dateToday = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
this.router.events.forEach((event) => { console.log('dateeeeee', dateToday)
if (event instanceof NavigationEnd && event.url == '/home/events') {
this.RefreshEvents();
setTimeout(() => {
this.LoadList();
}, 1500)
}
});
this.hideSearch();
}); */
// window.addEventListener('offline', (off) => {
if (this.platform.is('desktop') || this.platform.is('mobileweb')) { if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
} else { } else {
this.sqliteservice.getAllEvents().then((event: any[]) => { this.sqliteservice.getAllEvents().then((event: any[]) => {
this.listToPresent = event let todayEvents = new Array()
event.forEach((element) => {
let eventObject = {
AppointmentState: element.AppointmentState,
Attachments: element.Attachments,
Attendees: element.Attendees,
CalendarId: element.CalendarId,
CalendarName: element.CalendarName,
Category: element.Category,
EndDate: element.EndDate,
EventId: element.EventId,
EventRecurrence: element.EventRecurrence,
EventType: element.EventType,
HasAttachments: element.HasAttachments,
HumanDate: element.HumanDate,
IsAllDayEvent: element.IsAllDayEvent,
IsMeeting: element.IsMeeting,
IsRecurring: element.IsRecurring,
Location: element.Location,
Organizer: element.Organizer,
Profile: element.Profile,
StartDate: element.StartDate,
Subject: element.Subject
}
let starteDate = momentG(new Date(element.StartDate), 'yyyy-MM-dd');
console.log('startTOdayyy', starteDate)
if (dateToday == starteDate) {
todayEvents.push(eventObject);
}
})
this.listToPresent = todayEvents
this.totalEvent = this.listToPresent.length this.totalEvent = this.listToPresent.length
this.currentEvent = this.listToPresent[0].Subject this.currentEvent = this.listToPresent[0].Subject
this.currentHoursMinutes = this.listToPresent[0].StartDate this.currentHoursMinutes = this.listToPresent[0].StartDate
console.log("All events from local,", event) console.log("All events from local,", event)
}) })
this.sqliteservice.getAllProcess().then((res) => {
console.log('INICION ALL EVENTs', res)
})
this.sqliteservice.getprocessByworkflow("Expediente").then((process: any[]) => { this.sqliteservice.getprocessByworkflow("Expediente").then((process: any[]) => {
console.log('OFOFOFOOF', process) console.log('OFOFOFOOF', process)
+14 -2
View File
@@ -346,7 +346,7 @@ export class EventsService {
return this.http.put<Event>(`${puturl}`, event, options).pipe( return this.http.put<Event>(`${puturl}`, event, options).pipe(
catchError(err => { catchError(err => {
this.offlinemanager.storeRequest(puturl, 'PUT', arrayReq); this.offlinemanager.storeRequestData('eventEdit', arrayReq);
throw new Error(err); throw new Error(err);
}) })
) )
@@ -432,6 +432,13 @@ export class EventsService {
} }
deleteEvent(eventid: string, eventDeleteType: number, calendarName: string) { deleteEvent(eventid: string, eventDeleteType: number, calendarName: string) {
let arrayReq = [];
let Object = {
eventid: eventid,
eventDeleteType: eventDeleteType,
calendarName: calendarName
}
arrayReq.push(Object)
const puturl = environment.apiURL + 'calendar/DeleteEvent'; const puturl = environment.apiURL + 'calendar/DeleteEvent';
let params = new HttpParams(); let params = new HttpParams();
@@ -472,7 +479,12 @@ export class EventsService {
break; break;
} }
return this.http.delete(`${puturl}`, options) return this.http.delete(`${puturl}`, options).pipe(
catchError(err => {
this.offlinemanager.storeRequestData('eventDelete', arrayReq);
throw new Error(err);
})
)
} }
postExpedientEvent(docId: any, body: any, sharedagenda: string, serialNumber: any, applicationID: any) { postExpedientEvent(docId: any, body: any, sharedagenda: string, serialNumber: any, applicationID: any) {
const geturl = environment.apiURL + 'calendar/' + ((sharedagenda != '') ? sharedagenda : 'CreateEventExpediente') + '/event'; const geturl = environment.apiURL + 'calendar/' + ((sharedagenda != '') ? sharedagenda : 'CreateEventExpediente') + '/event';
+27 -78
View File
@@ -4,91 +4,40 @@ import { Observable, from, of, forkJoin } from 'rxjs';
import { switchMap, finalize } from 'rxjs/operators'; import { switchMap, finalize } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { ToastController } from '@ionic/angular'; import { ToastController } from '@ionic/angular';
const STORAGE_REQ_KEY = 'storedreq'; import { BackgroundService } from 'src/app/services/background.service';
import { EventsService } from 'src/app/services/events.service';
interface StoredRequest {
url: string,
type: string,
data: any,
time: number,
id: string
}
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class OfflineManagerService { export class OfflineManagerService {
/* eventservice: EventsService */
constructor( constructor(
private storage: Storage, private storage: Storage,
private http: HttpClient, /* private backgroundservice: BackgroundService */) { }
private toastController: ToastController) { }
synchnize() {
checkForEvents(): Observable<any> { /* this.backgroundservice.registerBackService('Online', () => {
return from(this.storage.get(STORAGE_REQ_KEY)).pipe( this.storage.get('eventEdit').then((req) => {
switchMap(storedOperations => { JSON.parse(req).forEach(element => {
let storedObj = JSON.parse(storedOperations); this.eventservice.editEvent(element, 2, 3).subscribe((res) => {
if (storedObj && storedObj.length > 0) { this.storage.remove('eventEdit')
return this.sendRequests(storedObj).pipe( console.log('eventEdit synchnize', res)
finalize(() => { })
let toast = this.toastController.create({ });
message: `Local data succesfully synced to API!`,
duration: 3000,
position: 'bottom'
});
toast.then(toast => toast.present());
this.storage.remove(STORAGE_REQ_KEY);
})
);
} else {
console.log('no local events to sync');
return of(false);
}
}) })
) }) */
} }
storeRequest(url, type, data) { storeRequestData(key, data) {
let toast = this.toastController.create({ return this.storage.set(key, JSON.stringify(data));
message: `Your data is stored locally because you seem to be offline.`,
duration: 3000,
position: 'bottom'
});
toast.then(toast => toast.present());
let action: StoredRequest = {
url: url,
type: type,
data: data,
time: new Date().getTime(),
id: Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5)
};
return this.storage.get(STORAGE_REQ_KEY).then(storedOperations => {
let storedObj = JSON.parse(storedOperations);
if (storedObj) {
storedObj.push(action);
} else {
storedObj = [action];
}
// Save old & new local transactions back to Storage
return this.storage.set(STORAGE_REQ_KEY, JSON.stringify(storedObj));
});
} }
sendRequests(operations: StoredRequest[]) { sendRequestData(key) {
let obs = []; return this.storage.get(key)
for (let op of operations) {
console.log('Make one request: ', op);
let oneObs = this.http.request(op.type, op.url, op.data);
obs.push(oneObs);
}
// Send out all local events and return once they are finished
return forkJoin(obs);
} }
} }
+36 -33
View File
@@ -26,13 +26,15 @@ export class SqliteService {
} }
databaseConn() { databaseConn() {
this.platform.ready().then(async () => { if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
await this.sqlite.create({ } else {
name: this.db_name, this.platform.ready().then(async () => {
location: 'default' await this.sqlite.create({
}).then(async (sqLite: SQLiteObject) => { name: this.db_name,
this.dbInstance = sqLite; location: 'default'
await sqLite.executeSql(` }).then(async (sqLite: SQLiteObject) => {
this.dbInstance = sqLite;
await sqLite.executeSql(`
CREATE TABLE IF NOT EXISTS ${this.events} ( CREATE TABLE IF NOT EXISTS ${this.events} (
EventId varchar(255) PRIMARY KEY, EventId varchar(255) PRIMARY KEY,
Subject varchar(255), Subject varchar(255),
@@ -57,12 +59,12 @@ export class SqliteService {
Profile varchar(255), Profile varchar(255),
HumanDate varchar(255) HumanDate varchar(255)
)`, []) )`, [])
.then((res) => { .then((res) => {
console.log("Sucess Events Table created: ", res) console.log("Sucess Events Table created: ", res)
}) })
.catch((error) => console.log(JSON.stringify(error))); .catch((error) => console.log(JSON.stringify(error)));
await sqLite.executeSql(` await sqLite.executeSql(`
CREATE TABLE IF NOT EXISTS ${this.expedientes} ( CREATE TABLE IF NOT EXISTS ${this.expedientes} (
serialNumber varchar(255) PRIMARY KEY, serialNumber varchar(255) PRIMARY KEY,
workflowInstanceFolio varchar(255), workflowInstanceFolio varchar(255),
@@ -79,12 +81,12 @@ export class SqliteService {
workflowInstanceID INTERGER, workflowInstanceID INTERGER,
workflowName varchar(255) workflowName varchar(255)
)`, []) )`, [])
.then((res) => { .then((res) => {
console.log("Sucess Espedientes Table created: ", res) console.log("Sucess Espedientes Table created: ", res)
}) })
.catch((error) => console.log(JSON.stringify(error))); .catch((error) => console.log(JSON.stringify(error)));
await sqLite.executeSql(` await sqLite.executeSql(`
CREATE TABLE IF NOT EXISTS ${this.allprocess} ( CREATE TABLE IF NOT EXISTS ${this.allprocess} (
serialNumber varchar(255) PRIMARY KEY, serialNumber varchar(255) PRIMARY KEY,
workflowInstanceFolio varchar(255), workflowInstanceFolio varchar(255),
@@ -102,12 +104,12 @@ export class SqliteService {
workflowName varchar(255), workflowName varchar(255),
interveners Text interveners Text
)`, []) )`, [])
.then((res) => { .then((res) => {
console.log("Sucess AllProcess Table created: ", res) console.log("Sucess AllProcess Table created: ", res)
}) })
.catch((error) => console.log(JSON.stringify(error))); .catch((error) => console.log(JSON.stringify(error)));
await sqLite.executeSql(` await sqLite.executeSql(`
CREATE TABLE IF NOT EXISTS ${this.actions} ( CREATE TABLE IF NOT EXISTS ${this.actions} (
ProcessId INTERGER PRIMARY KEY, ProcessId INTERGER PRIMARY KEY,
ActionType varchar(255), ActionType varchar(255),
@@ -117,13 +119,14 @@ export class SqliteService {
Description varchar(255), Description varchar(255),
publications Text publications Text
)`, []) )`, [])
.then((res) => { .then((res) => {
console.log("Sucess action Table created: ", res) console.log("Sucess action Table created: ", res)
}) })
.catch((error) => console.log(JSON.stringify(error)));
})
.catch((error) => console.log(JSON.stringify(error))); .catch((error) => console.log(JSON.stringify(error)));
}) });
.catch((error) => console.log(JSON.stringify(error))); }
});
} }
//addactions //addactions
@@ -182,8 +185,8 @@ export class SqliteService {
}); });
} }
//updateevent //updateevent
public updateEvent(data) { public updateEvent(data) {
this.dbInstance.executeSql(` this.dbInstance.executeSql(`
INSERT OR REPLACE INTO ${this.events} (EventId,Subject,HasAttachments,Location,CalendarId,CalendarName,StartDate,EndDate,EventType,Attendees,IsMeeting,IsRecurring,IsAllDayEvent,AppointmentState,TimeZone,Organizer,Category,EventRecurrence,Attachments,Body,Profile,HumanDate ) INSERT OR REPLACE INTO ${this.events} (EventId,Subject,HasAttachments,Location,CalendarId,CalendarName,StartDate,EndDate,EventType,Attendees,IsMeeting,IsRecurring,IsAllDayEvent,AppointmentState,TimeZone,Organizer,Category,EventRecurrence,Attachments,Body,Profile,HumanDate )
VALUES ('${data.EventId}','${data.Subject}','${data.HasAttachments}','${data.Location}','${data.CalendarId}','${data.CalendarName}','${data.StartDate}','${data.EndDate}','${data.EventType}','${data.Attendees}','${data.IsMeeting}','${data.IsRecurring}', VALUES ('${data.EventId}','${data.Subject}','${data.HasAttachments}','${data.Location}','${data.CalendarId}','${data.CalendarName}','${data.StartDate}','${data.EndDate}','${data.EventType}','${data.Attendees}','${data.IsMeeting}','${data.IsRecurring}',
@@ -197,10 +200,10 @@ export class SqliteService {
} }
//updateActions //updateActions
public updateactions(id,data) { public updateactions(id, data) {
console.log("update action data", data ) console.log("update action data", data)
this.dbInstance.executeSql(` this.dbInstance.executeSql(`
UPDATE ${this.actions} SET publications = ? WHERE ProcessId = ${id}`,[data]) UPDATE ${this.actions} SET publications = ? WHERE ProcessId = ${id}`, [data])
.then(() => { .then(() => {
console.log("action update with Success"); console.log("action update with Success");