Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 | 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 323x 1071x 916x 155x 103x 91x 103x 3x 100x 100x 14x 4x 4x 4x 4x 4x 494x 494x 494x 494x 467x 494x 110x 9x 101x 24x 77x 13x 13x 13x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 8x 6x 6x 6x 4x 4x 1x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x 1x 2x 1x 1x 1x 1x 8x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 3x 3x 3x 3x 14x 1x 13x 13x 9x 9x 9x 13x 8x 29x 29x 29x 29x 29x 29x 29x 29x 3x 3x 29x 29x 29x 29x 29x 29x 29x 29x 72x 19x 72x 29x 4x 3x 4x 29x 8x 4x 8x 29x 29x 29x 29x 29x 29x 29x 12x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 29x 29x 29x 16x 8x 8x 5x 5x 5x 5x 5x 5x 4x 4x 4x 1x 1x 1x 1x 1x 5x 4x 4x 4x 1x 1x 1x 8x 8x 29x 29x 29x 10x 6x 6x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 6x 3x 4x 4x 4x 3x 3x 4x 2x 6x 29x 29x 29x 9x 6x 6x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 6x 29x 1x 29x 8x 29x 23x 12x 12x 12x 7x 7x 7x 7x 7x 7x 7x 6x 7x 2x 10x 10x 10x 10x 9x 9x 9x 9x 8x 8x 8x 8x 8x 1x 9x | import { Injectable, Injector, OnDestroy } from '@angular/core';
import { BaseObject, CommitChange } from './model/base';
import { Observable, Subject, Subscription, firstValueFrom } from 'rxjs';
import { take } from 'rxjs/operators';
import { GenericUtils } from '@unpispas/upp-defs';
import { UserMode } from '@unpispas/upp-base';
import { adhocService } from '@unpispas/upp-base';
import { stateService } from '@unpispas/upp-base';
import { clockService } from '@unpispas/upp-base';
import { languageService } from '@unpispas/upp-base';
import { viewService} from '@unpispas/upp-base';
import { logsService } from '@unpispas/upp-base';
import { syncService } from './sync';
import { eventsNotifier, LogActions } from './events';
import { DataObject, ViewObject } from './model/base';
import { Session } from './model/objects/session';
import { QrCode } from './model/objects/qrcode';
import { User } from './model/objects/user';
import { Place } from './model/objects/place';
import { Address } from './model/objects/address';
import { ObjectFactory } from './model/factory';
import { ObjectRegistry } from './model/model';
import { UserView } from './model/views/user';
/************************************/
/* DATA MODEL REGISTRATION */
/************************************/
ObjectRegistry();
/************************************/
/* DATA STORAGE */
/************************************/
/**
* Represents the structure of the internal storage for objects.
*/
type StorageMap = {
[table: string]: Map<string, BaseObject>;
};
/**
* A utility class for managing objects in a two-tiered storage system.
* Objects are stored either in a "resolved" state, meaning they have a valid `objid`,
* or in an "awaiting" state, meaning they lack a valid identifier.
*/
export class dataStorage {
/**
* Internal storage divided into `resolved` and `awaiting` categories.
* - `resolved`: Objects with valid `objid`.
* - `awaiting`: Objects awaiting resolution (e.g., no valid `objid`).
*/
private _objects:{
resolved: StorageMap;
awaiting: StorageMap;
} = {
resolved: {},
awaiting: {},
};
/********************************/
/* PRIVATE METHODS */
/********************************/
/**
* Retrieves an object by table and reference (`objref`) from a specific storage target.
*
* @param table - The table name where the object is stored.
* @param objref - The unique reference of the object (can be `objid` or `_uuid`).
* @param _target - The target storage to search (`resolved` or `awaiting`).
* @returns The object if found; otherwise, `null`.
*/
private _GetObject(table: string, objref: string, _target: any): BaseObject | null {
if (!(table in _target)){
return null; // table not found
}
return _target[table].get(objref) || null;
}
/**
* Adds an object to a specific storage target.
*
* @param dataobject - The object to add.
* @param _target - The target storage (`resolved` or `awaiting`).
* @returns `true` if the object was added successfully; otherwise, `false`.
*/
private _AddObject(dataobject: BaseObject, _target: any) : boolean{
if (!(dataobject.table in _target)){
_target[dataobject.table] = new Map <string, BaseObject>();
}
if (this._GetObject(dataobject.table, dataobject.objref, _target)){
return false; // already exists
}
_target[dataobject.table].set(dataobject.objref, dataobject);
return true;
}
/**
* Deletes an object from a specific storage target.
*
* @param dataobject - The object to delete.
* @param _target - The target storage (`resolved` or `awaiting`).
*/
private _DelObject(dataobject: BaseObject, _target: any){
Iif (dataobject.table in _target) {
_target[dataobject.table].delete(dataobject.objref)
}
}
/********************************/
/* PUBLIC METHODS */
/********************************/
/**
* Retrieves an object by table, `objid`, or `_uuid` from the storage.
*
* @param table - The table name where the object is stored.
* @param objid - The object identifier (`objid`).
* @param _uuid - The unique identifier (`_uuid`).
* @returns The object if found; otherwise, `null`.
*/
GetByRef(table: string, objid: string | null, _uuid: string | null): BaseObject | null {
let _object = null;
if (!_object && _uuid){
_object = this._GetObject(table, _uuid, this._objects.awaiting);
}
Iif (!_object && objid){
_object = this._GetObject(table, objid, this._objects.resolved);
}
return _object;
}
/**
* Retrieves an object by its reference from either `resolved` or `awaiting` storage.
*
* @param dataobject - The object to retrieve.
* @returns The object if found; otherwise, `null`.
*/
GetObject(dataobject: BaseObject): BaseObject | null {
let _object = null;
if (!_object){
_object = this._GetObject(dataobject.table, dataobject.objref, this._objects.awaiting);
}
if (!_object){
_object = this._GetObject(dataobject.table, dataobject.objref, this._objects.resolved);
}
return _object;
}
/**
* Adds an object to the appropriate storage (`resolved` or `awaiting`).
*
* @param dataobject - The object to add.
* @returns `true` if the object was added successfully; otherwise, `false`.
*/
AddObject(dataobject: BaseObject): boolean {
if (dataobject.CopyOf || !dataobject.ToStorage(this)){
return true; // not suitable for storage
}
if (dataobject.objid && !isNaN(Number(dataobject.objid))){
return this._AddObject(dataobject, this._objects.resolved);
}
else {
return this._AddObject(dataobject, this._objects.awaiting);
}
}
/**
* Deletes an object from the storage.
*
* @param dataobject - The object to delete.
*/
DelObject(dataobject: BaseObject) {
Iif (dataobject.objid && !isNaN(Number(dataobject.objid))){
return this._DelObject(dataobject, this._objects.resolved);
}
else {
return this._DelObject(dataobject, this._objects.awaiting);
}
}
/**
* Updates an object in the storage by deleting and re-adding it.
*
* @param dataobject - The object to update.
*/
SetObject(dataobject: BaseObject | null) {
if (dataobject){
this.DelObject(dataobject);
this.AddObject(dataobject);
}
}
/**
* Resolves an object from the `awaiting` storage and moves it to `resolved`.
*
* @param dataobject - The object to resolve.
*/
Resolve(dataobject: BaseObject){
Iif (dataobject.objid){
return; // this object is already resolved
}
this._DelObject(dataobject, this._objects.awaiting);
dataobject.objid = dataobject.Info['objid'] ? dataobject.Info['objid'].toString() : null;
const _to_delete: BaseObject | null = this._GetObject(dataobject.table, dataobject.objref, this._objects.resolved);
const _to_insert: BaseObject | null = dataobject;
Iif (_to_delete){
this._DelObject(_to_delete, this._objects.resolved);
}
if (dataobject.objid){ // object resolution
this._AddObject(_to_insert, this._objects.resolved);
}
else E{ // object replacement
this._AddObject(_to_insert, this._objects.awaiting);
}
Iif (_to_delete){
_to_delete.OnResolve(); // resolve references for the deleted object
}
}
/**
* Replaces an object in the `resolved` storage with a new version.
*
* @param dataobject - The updated object.
* @param uuid - The UUID of the object to replace.
*/
Replace(dataobject: BaseObject, uuid: string){
const _to_update = this._GetObject(dataobject.table, uuid, this._objects.awaiting);
const _to_delete: BaseObject | null = this._GetObject(dataobject.table, dataobject.objref, this._objects.resolved);
const _to_insert: BaseObject | null = dataobject;
Iif (_to_update){
this._DelObject(_to_update, this._objects.awaiting);
}
Iif (_to_delete){
this._DelObject(_to_delete, this._objects.resolved);
}
this._AddObject(_to_insert, this._objects.resolved)
Iif (_to_update){
_to_update.OnResolve(); // resolve references for the updated object
}
}
/**
* Clears all objects from the storage.
*/
Clear(){
this._objects.resolved = {};
this._objects.awaiting = {};
}
}
/**
* Represents a transaction for committing data changes.
*/
export class dataTransaction {
private _trstatus: 'OPEN' | 'CLOSED' = 'OPEN';
private _tocommit = new Map <string, CommitChange> ();
constructor(private data: dataService){
// nothing to do
}
/**
* Adds an item to the transaction.
*
* @param item - The object to add.
* @returns A promise resolving to `true` if successful.
* @throws If transaction state is invalid or dependencies are unmet.
*/
async push(item: BaseObject, force = false) : Promise<boolean> {
if (this._trstatus != 'OPEN'){
throw new Error("[TRANSACTION]: invalid transaction state: '" + this._trstatus + "'")
}
Iif (force){
item.ForceUpdate();
}
const _changes: CommitChange[] = await Promise.all(item.Commit);
for(let _idx = _changes.length-1; _idx >= 0; _idx--){
const _change = _changes[_idx];
Iif (_change.entrynfo == null){
_changes.slice(_idx, 1); // already resolved in this transaction
}
else {
this._tocommit.set(_change.relation.table + '@' + (_change.relation.objid || _change.relation._uuid), _change)
}
}
// determine if the item is safe to be commited
for (const _change of _changes){
// check if the change is suitable for the transaction
for (const _key in _change.requires){
const _require = _change.requires[_key];
let _issafe = ('objid' in _require.relation) && (_require.relation.objid !== null);
if (!_issafe){ // check if the new item is included in this transaction's commit
_issafe = this._tocommit.has(_require.relation.table + '@' + _require.relation._uuid);
}
if (!_issafe){ // check if the new item is included in the list of items to be commited
_issafe = this.data.ToCommit.has(_require.relation.table + '@' + _require.relation._uuid);
}
if (!_issafe){ // check if the new item has been sent to server (awaiting response)
const _stored = this.data.store.GetByRef(_require.relation.table, null, _require.relation._uuid);
if (_stored){
_issafe = _stored.InCommit;
}
}
if (!_issafe){
throw new Error("[TRANSACTION]: invalid item in transaction (dependencies don't met)");
}
}
}
return true;
}
/**
* Commits all items in the transaction.
*
* @param force - If `true`, forces the commit process.
* @returns A promise resolving to `true` when complete.
*/
async flush(force = false): Promise <boolean> {
Iif (this._trstatus != 'OPEN'){
throw new Error("[TRANSACTION]: invalid transaction state: '" + this._trstatus + "'")
}
// add the computed changes in transacion to the data commit
for(const _change of this._tocommit.values()){
this.data.ToCommit.set(_change.relation.table + '@' + (_change.relation.objid || _change.relation._uuid), _change);
}
return await this.data.Flush(force);
}
}
/**
* Manages weak references to `ViewObject<DataObject>` instances, ensuring that
* objects remain in memory only while actively used. When the last reference
* is lost, the object is automatically garbage collected.
*
* This class uses `WeakMap` and `WeakRef` to store objects without preventing
* their garbage collection, avoiding memory leaks.
*/
export class aliveItems {
// WeakMap stores objects with weak references
private _alivemap = new WeakMap<DataObject, WeakRef<ViewObject<DataObject>>>();
// Debug information
private _register_count = 0;
private _released_count = 0;
get itemssize(): number {
return this._register_count - this._released_count;
}
logstatus(): void {
console.group('[ALIVE] Cache state');
console.info(`Total register: ${this._register_count}`);
console.info(`Total released: ${this._released_count}`);
console.groupEnd();
}
// Registry to clean up references when objects are garbage collected
private finalizationRegistry = new FinalizationRegistry <DataObject> (
(object) => {
Iif (GenericUtils.VerboseLogging(3)){
console.info("-- [ALIVE] " + object.table + "@" + object._uuid + " released (current size: " + this.itemssize + ")");
}
this._released_count++;
this._alivemap.delete(object);
});
/**
* Creates and stores a weak reference to a ViewObject if it does not exist.
* The ViewObject remains in memory only if there are active references.
*
* @param object The DataObject instance to store.
* @returns The ViewObject instance, or null if not found.
*/
private set(object: DataObject): ViewObject<DataObject> | null {
const _view = object.View;
if (_view){
if (GenericUtils.VerboseLogging(3)){
console.info("++ [ALIVE] " + object.table + "@" + object._uuid + " included (current size: " + this.itemssize + ")");
}
this._register_count++;
this._alivemap.set(object, new WeakRef(_view));
this.finalizationRegistry.register(_view, object);
}
return _view;
}
/**
* Checks if the DataObject has an associated ViewObject in the weak storage.
*
* @param object The DataObject instance.
* @returns True if the ViewObject is still in memory, false otherwise.
*/
has (object: DataObject): boolean {
const _hasrf = this._alivemap.has(object);
const _alive = this._alivemap.get(object)?.deref() !== undefined;
Iif (_hasrf && !_alive) {
console.info("[ALIVE] " + object.table + "@" + object._uuid + " reference exists but object is gone");
}
return _hasrf && _alive;
}
/**
* Retrieves the ViewObject associated with a DataObject.
* If it does not exist, it is created and stored with a weak reference.
*
* @param object The DataObject instance.
* @returns The ViewObject instance, or null if the object is null.
*/
get(object: DataObject | null) : ViewObject<DataObject> | null {
if (!object){
return null;
}
let _view = this._alivemap.get(object)?.deref() || null;
if (_view == null){
_view = this.set(object);
if (_view){ // perform the registration just after creation
_view.doRegister();
}
}
return _view;
}
}
/**
* Service to manage data synchronization, transactions, and session-related operations.
*/
@Injectable({
providedIn: 'root'
})
export class dataService implements OnDestroy {
private _user_subscription: Subscription | null = null;
private _expired_subscription: Subscription | null = null;
private _onchange_subscription: Subscription | null = null;
private _onreload_subscription: Subscription | null = null;
/**
* Constructor for the dataService.
*
* @param injector - The angular dependencies injector
* @param clock - Service to manage time-related operations.
* @param lang - Service to manage language-related operations.
* @param adhoc - Ad-hoc request handling service.
* @param logs - Service to manage logs and logging operations.
* @param events - Service to manage application-wide events.
* @param state - Service to manage application state.
* @param view - Service to manage the application's view layer.
* @param sync - Service to manage synchronization with the backend server.
*/
constructor(public injector: Injector, public clock: clockService, private lang: languageService, private adhoc: adhocService, private logs: logsService, private state: stateService, private view: viewService, private sync: syncService){
this._expired_subscription = this.sync.OnExpired.subscribe(
() => {
this.Stop(true);
});
this._onchange_subscription = this.sync.OnChange.subscribe(
(change) => {
const _uuid = (change['table'] == 'SESSION') ? change['id'] : change['_uuid'];
let _update = this.store.GetByRef(change['table'], change['objid'], _uuid);
Iif (!_update){ // include the object into the data model (if it doesn't exist)
_update = ObjectFactory.object(change['table'], change['objid'], this);
Iif (_update){
this.store.AddObject(_update);
}
}
if (_update){ // call to the update method of the target object
_update.OnChange(change);
}
else {
console.error("[DATA] Discarded change (could not create object)", change);
}
});
}
/**
* Cleanup logic when the service is destroyed.
*/
ngOnDestroy(): void {
if (this._user_subscription){
this._user_subscription.unsubscribe();
this._user_subscription = null;
}
if (this._expired_subscription){
this._expired_subscription.unsubscribe();
this._expired_subscription = null;
}
if (this._onchange_subscription){
this._onchange_subscription.unsubscribe();
this._onchange_subscription = null;
}
Iif (this._onreload_subscription){
this._onreload_subscription.unsubscribe();
this._onreload_subscription = null;
}
}
/************************************/
/* STORAGE ACCESS */
/************************************/
private _storage: dataStorage | null = null;
/**
* Lazy getter for the data storage instance.
* Initializes a new `dataStorage` instance if it doesn't already exist.
*/
get store(): dataStorage {
if (!this._storage){
this._storage = new dataStorage();
}
return this._storage;
}
/************************************/
/* EVENTS ACCESS */
/************************************/
private _events: eventsNotifier | null = null;
/**
* Lazy getter for the event factory instance.
* Initializes a new `events` instance if it doesn't already exist.
*/
get events(): eventsNotifier {
if (!this._events){
this._events = new eventsNotifier(this);
}
return this._events;
}
/************************************/
/* ALIVE ITEMS MAP */
/************************************/
/**
* Lazy getter for the alive items repository
* Initializes a new `aliveItems` instance if it doesn't already exist.
*/
private _alives: aliveItems | null = null;
get alives(): aliveItems {
if (!this._alives){
this._alives = new aliveItems();
}
return this._alives;
}
/************************************/
/* TRANSACTIONS */
/************************************/
get transaction(): dataTransaction {
return new dataTransaction(this);
}
/************************************/
/* INITIALIZATION / FINALIZATION */
/************************************/
private _reloadRequested = new Subject<void> ();
private _onSessionReleased = new Subject<boolean>();
private _onSessionChanged = new Subject<Session>();
/** Observable triggered when a reload is requested. */
public OnReloadRequested = this._reloadRequested.asObservable();
/** Observable triggered when the session is released. */
public OnSessionReleased = this._onSessionReleased.asObservable();
/** Observable triggered when the session changes. */
public OnSessionChanged = this._onSessionChanged.asObservable();
private _session: Session | null = null;
/**
* Retrieves the current session.
*/
get session(): Session | null {
return this._session;
}
/**
* Retrieves the current serial number.
*/
get serial(): string {
Iif (this.place){
return GenericUtils.CRC32(this.place.objid + '_' + this.state.device).toString(16);
}
throw new Error("[DATA] Service not ready to provide a serial number!");
}
/**
* Waits until the syncronization service is ready
*/
async Ready(): Promise<void> {
await firstValueFrom(this.sync.IsReady);
}
/**
* Starts a session and initializes the necessary components.
*
* @param session - The session identifier.
* @param access - The access mode for the session (`LOGIN` or `GUEST`).
* @returns A promise resolving to `true` if the session starts successfully, otherwise `false`.
*/
async Start(session: string, access: UserMode): Promise <boolean> {
if (this.session && this.session.id == session){
return false; // already started
}
this._session = new Session(null, this, null, session);
if (this.session && this.store.AddObject(this.session)){
this.sync.Start(session).then(
() => {
this.state.Access = access;
if (this.session){
this._onSessionChanged.next(this.session);
}
});
}
else E{
throw new Error("[DATA] Could not start session!")
}
await firstValueFrom(this._session.OnUpdated);
/** session has been updated from server data */
await new Promise<void>((resolve) => {
setTimeout(async () => {
if (this.session){
if (access == 'LOGIN'){
const _user = this.session.user as User;
await this.SetUser(_user);
Iif (this.user){
this.view.View = 'USER';
}
}
Iif (access == 'GUEST'){
const _qrcd = this.session.qrcode as QrCode;
await this.SetQrCode(_qrcd);
Iif (this.qrcode){
this.view.View = 'PLACE';
}
}
}
resolve();
}, 0);
});
return true;;
}
/**
* Stops the current session and resets all session-related data.
*
* @returns A promise resolving to `true` after successful session termination.
*/
async Stop(expired: boolean): Promise <boolean>{
if (this._session){
this._session.DoUpdate();
}
this._session = null;
this.sync.OnReleased.pipe(take(1)).subscribe(
() => {
this._onSessionReleased.next(expired);
setTimeout(() => {
window.location.reload();
}, 0);
});
await this.sync.Stop();
await this.SetPlace(null);
await this.SetUser(null);
await this.SetQrCode(null);
this.logs.Stop();
this.store.Clear();
return true;
}
/********************************/
/* SESSION USER */
/********************************/
private _onUserChanged = new Subject<User | null>();
/**
* Observable triggered when the user changes.
*/
OnUserChanged = this._onUserChanged.asObservable();
private _user: User | null = null;
/**
* Retrieves the current user.
*/
get user(): User | null {
return this._user;
}
/**
* Updates the current user and notifies related services.
*
* @param user - The new user to set.
* @returns A promise resolving to `true` after successful update.
*/
async SetUser(user: User | null): Promise <boolean>{
await user?.WaitLoaded();
if (this._user != user){
this.store.SetObject(user);
await this.sync.ResetStage();
this._user = user;
this.sync.SetUser(user).then(
() => {
this._onUserChanged.next(user);
});
if (user){
await this.lang.SetLanguage(user.lang || 'ES');
// notify user online status to other clients
const _user = this.alives.get(user || this._user) as UserView;
if (_user.employees.length > 0){
const _transaction = new dataTransaction(this);
if (_transaction){
for(const employee of _user.employees){
await _transaction.push(employee.object, true);
}
_transaction.flush(true);
}
}
}
if (this.user){
Iif (this.user.objid){
console.info("[USER] " + (this.user.fullname || this.user.email) + " (language: " + this.user.lang + ")");
}
else {
console.info("[USER] (guest user)")
}
this._user_subscription = this.user.OnRefresh.subscribe(
() => {
Iif (this.user?.lang){
this.lang.SetLanguage(this.user.lang);
}
})
}
else {
if (this._user_subscription){
this._user_subscription.unsubscribe();
this._user_subscription = null;
}
}
}
this._reloadRequested.next();
return true;
}
/********************************/
/* SESSION PLACE */
/********************************/
private _onPlaceChanged = new Subject<Place | null>();
/**
* Observable triggered when the place changes.
*/
OnPlaceChanged = this._onPlaceChanged.asObservable();
private _place: Place | null = null;
get place(): Place | null {
return this._place;
}
/**
* Updates the current place and notifies related services.
*
* @param place - The new place to set.
* @returns A promise resolving to `true` after successful update.
*/
async SetPlace(place: Place | null): Promise <boolean>{
await place?.WaitLoaded();
if (this.place != place){
this.store.SetObject(place);
let _notifylogin = true;
if ((place && place.ToInsert) || (!place && this.place && this.place.ToInsert)){
_notifylogin = false; // these are a place creation attempts
}
// add the login event to the registry
Iif (_notifylogin){
this.events.LogAction(LogActions.LOGIN, {
place: place ? place : this.place,
login: place ? true : false
})
}
await this.sync.ResetStage();
this._place = place;
// preload the place language strings
if (place){
let _placelang = 'ES'; // defaults to 'ES'
const _placectcd = (place.address as Address)?.country;
Iif (this.lang.GetLanguages().some((_lang) => _lang.lang == _placectcd)){
_placelang = _placectcd || 'ES';
}
this.lang.SetLanguage(_placelang, false);
}
this.sync.SetPlace(place).then(
() => {
this._onPlaceChanged.next(place);
if (place != null){
place.Initialize();
this.view.View = 'PLACE';
}
});
this._reloadRequested.next();
}
else { // update the state place to be considered in doRequest
Iif (place){
this.state.place = place.objid;
}
}
return true;
}
/********************************/
/* SESSION QRCODE */
/********************************/
private _onQrCodeChanged = new Subject<QrCode | null>();
/**
* Observable triggered when the table changes.
*/
OnQrCodeChanged = this._onQrCodeChanged.asObservable();
private _qrcode: QrCode | null = null;
/**
* Retrieves the current table.
*/
get qrcode(): QrCode | null {
return this._qrcode;
}
/**
* Updates the current table and notifies related services.
*
* @param qrcode - The new table to set.
* @returns A promise resolving to `true` after successful update.
*/
async SetQrCode(qrcode: QrCode | null): Promise <boolean>{
await qrcode?.WaitLoaded();
if (this.qrcode != qrcode){
this.store.SetObject(qrcode);
// add the login event to the registry
this.events.LogAction(LogActions.GUEST, {
table: qrcode ? qrcode : this.qrcode,
login: qrcode ? true : false
})
await this.sync.ResetStage();
this._qrcode = qrcode;
this.sync.SetQrCode(qrcode).then(
() => {
this._onQrCodeChanged.next(qrcode);
});
// notify table online status to other clients
const _qrcode = qrcode || this._qrcode;
if (_qrcode){
_qrcode.ForceCommit();
}
this._reloadRequested.next();
}
return true;
}
/************************************/
/* SERVER REQUESTS */
/************************************/
private _doFetchhUrl = 'sync/objidrequest';
/**
* Observable triggered when the load percentage changes.
*/
get OnRefreshPercent(): Observable <number> {
return this.sync.synchonizer.pending.OnRefreshPercent;
}
/**
* Observable triggered when a refresh operation is completed.
*/
get OnRefreshCompleted(): Observable <void> {
return this.sync.synchonizer.OnRefreshCompleted;
}
/**
* Observable triggered when a commit operation is completed.
*/
get OnCommitCompleted(): Observable <void> {
return this.sync.synchonizer.OnCommitCompleted;
}
/**
* Fetches an object by its `objid` from the backend server.
*
* @param table - The table name where the object resides.
* @param objid - The `objid` of the object to fetch.
* @returns A promise resolving with the fetched object data.
*/
FetchByObjid(table: string, objid: string) : Promise <any> {
return this.adhoc.DoRequest(this._doFetchhUrl, { table: table, objid: objid }, null, false);
}
/************************************/
/* PROCESS SERVER UPDATES */
/************************************/
private _logchanges = false; // enable verbose logging additional detail
/**
* Logs detailed information about changes made during a commit operation.
*
* @param _change - The change to log.
*/
private _LogChange(_change: CommitChange) {
Iif (this._logchanges){
const _entrynfo = _change.entrynfo;
const _newentry = !(('objid' in _entrynfo) && _entrynfo['objid']);
if (_newentry){
console.info("[COMMIT] INSERT - '" + _entrynfo['table'] + "'");
}
else {
console.info("[COMMIT] UPDATE - '" + _entrynfo['table'] + " (with objid [" + _entrynfo['objid'] + "]'");
}
for (const _field in _entrynfo){
Iif (['table', 'objid'].includes(_field)){
continue;
}
console.info(" - " + _field + ": " + _entrynfo[_field]);
}
}
}
private _tocommit = new Map <string, CommitChange> ();
/**
* Retrieves the list of objects pending commit.
*/
get ToCommit(): Map <string, CommitChange> {
return this._tocommit;
}
/**
* Adds an list of changes to the commit queue.
*
* @param item - The object to commit.
* @throws If the object has unresolved dependencies.
*/
async Commit(commits: Promise <CommitChange> []): Promise <boolean> {
const _changes: CommitChange[] = await Promise.all(commits);
for (const _change of _changes){
// check if the change is suitable to be commited
for (const _key in _change.requires){
const _require = _change.requires[_key];
let _issafe = ('objid' in _require.relation) && (_require.relation.objid);
if (!_issafe){ // check if the new item is included in the list of items to be commited
_issafe = this.ToCommit.has(_require.relation.table + '@' + _require.relation._uuid);
}
if (!_issafe){ // check if the new item has been sent to server (awaiting response)
const _stored = this.store.GetByRef(_require.relation.table, null, _require.relation._uuid);
if (_stored){
_issafe = _stored.InCommit;
}
}
if (!_issafe){
throw new Error("[DATA]: invalid item to be commited (dependencies doesn't met)")
}
}
const _index = _change.relation.objid || _change.relation._uuid;
Iif (!_index){
throw new Error("[DATA]: invalid item to be commited (unique index not provided)")
}
this._tocommit.set(_change.relation.table + '@' + _index, _change);
}
return true;
}
/**
* Commits all changes in the queue to the backend server.
*
* @param force - If `true`, forces the commit process.
* @returns A promise resolving to `true` after successful synchronization.
*/
async Flush(force = false): Promise <boolean>{
let _flushed = false;
const _changes: CommitChange[] = [...this.ToCommit.values()];
if (_changes.length > 0){
if (GenericUtils.VerboseLogging(2)){
for (const _change of _changes){
this._LogChange(_change);
}
}
_flushed = await this.sync.Flush(_changes, force);
this._tocommit.clear();
}
else {
console.warn("[DATA] Could not commit (nothing to be commited)");
}
return _flushed;
}
} |