/* eslint-disable max-len */ import { Component, OnInit, OnDestroy, ViewChild, AfterViewInit } from '@angular/core'; import { DecimalPipe } from '@angular/common'; import { Subject } from 'rxjs'; import { take, takeUntil } from 'rxjs/operators'; import { Store } from '@ngrx/store'; import { faHistory } from '@fortawesome/free-solid-svg-icons'; import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import * as pdfMake from 'pdfmake/build/pdfmake'; import * as pdfFonts from 'pdfmake/build/vfs_fonts'; import { PAGE_SIZE, PAGE_SIZE_OPTIONS, getPaginatorLabel, ScreenSizeEnum, APICallStatusEnum, AlertTypeEnum, SortOrderEnum, CLN_DEFAULT_PAGE_SETTINGS, CLN_PAGE_DEFS } from '../../../../shared/services/consts-enums-functions'; import { ApiCallStatusPayload } from '../../../../shared/models/apiCallsPayload'; import { SelNodeChild } from '../../../../shared/models/RTLconfig'; import { GetInfo, Offer, OfferRequest } from '../../../../shared/models/clnModels'; import { DataService } from '../../../../shared/services/data.service'; import { LoggerService } from '../../../../shared/services/logger.service'; import { CommonService } from '../../../../shared/services/common.service'; import { CLNCreateOfferComponent } from '../create-offer-modal/create-offer.component'; import { CLNOfferInformationComponent } from '../offer-information-modal/offer-information.component'; import { RTLEffects } from '../../../../store/rtl.effects'; import { RTLState } from '../../../../store/rtl.state'; import { openAlert, openConfirmation } from '../../../../store/rtl.actions'; import { disableOffer } from '../../../store/cln.actions'; import { clnNodeInformation, clnNodeSettings, clnPageSettings, offers } from '../../../store/cln.selector'; import { ColumnDefinition, PageSettings, TableSetting } from '../../../../shared/models/pageSettings'; import { CamelCaseWithReplacePipe } from '../../../../shared/pipes/app.pipe'; import { MAT_SELECT_CONFIG } from '@angular/material/select'; @Component({ selector: 'rtl-cln-offers-table', templateUrl: './offers-table.component.html', styleUrls: ['./offers-table.component.scss'], providers: [ { provide: MAT_SELECT_CONFIG, useValue: { overlayPanelClass: 'rtl-select-overlay' } }, { provide: MatPaginatorIntl, useValue: getPaginatorLabel('Offers') } ] }) export class CLNOffersTableComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChild(MatSort, { static: false }) sort: MatSort | undefined; @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator | undefined; faHistory = faHistory; public nodePageDefs = CLN_PAGE_DEFS; public selFilterBy = 'all'; public colWidth = '20rem'; public PAGE_ID = 'transactions'; public tableSetting: TableSetting = { tableId: 'offers', recordsPerPage: PAGE_SIZE, sortBy: 'offer_id', sortOrder: SortOrderEnum.DESCENDING }; public selNode: SelNodeChild | null = {}; public newlyAddedOfferMemo = ''; public newlyAddedOfferValue = 0; public description = ''; public expiry: number; public offerValue: number | null = null; public offerValueHint = ''; public displayedColumns: any[] = []; public offerPaymentReq = ''; public offers: any; public offerJSONArr: Offer[] = []; public information: GetInfo = {}; public private = false; public expiryStep = 100; public pageSize = PAGE_SIZE; public pageSizeOptions = PAGE_SIZE_OPTIONS; public screenSize = ''; public screenSizeEnum = ScreenSizeEnum; public errorMessage = ''; public selFilter = ''; public apiCallStatus: ApiCallStatusPayload | null = null; public apiCallStatusEnum = APICallStatusEnum; private unSubs: Array> = [new Subject(), new Subject(), new Subject(), new Subject(), new Subject(), new Subject(), new Subject()]; constructor(private logger: LoggerService, private store: Store, private commonService: CommonService, private rtlEffects: RTLEffects, private dataService: DataService, private decimalPipe: DecimalPipe, private camelCaseWithReplace: CamelCaseWithReplacePipe) { this.screenSize = this.commonService.getScreenSize(); } ngOnInit() { this.store.select(clnNodeSettings).pipe(takeUntil(this.unSubs[0])).subscribe((nodeSettings: SelNodeChild | null) => { this.selNode = nodeSettings; }); this.store.select(clnNodeInformation).pipe(takeUntil(this.unSubs[1])).subscribe((nodeInfo: GetInfo) => { this.information = nodeInfo; }); this.store.select(clnPageSettings).pipe(takeUntil(this.unSubs[2])). subscribe((settings: { pageSettings: PageSettings[], apiCallStatus: ApiCallStatusPayload }) => { this.errorMessage = ''; this.apiCallStatus = settings.apiCallStatus; if (this.apiCallStatus.status === APICallStatusEnum.ERROR) { this.errorMessage = this.apiCallStatus.message || ''; } this.tableSetting = settings.pageSettings.find((page) => page.pageId === this.PAGE_ID)?.tables.find((table) => table.tableId === this.tableSetting.tableId) || CLN_DEFAULT_PAGE_SETTINGS.find((page) => page.pageId === this.PAGE_ID)?.tables.find((table) => table.tableId === this.tableSetting.tableId)!; if (this.screenSize === ScreenSizeEnum.XS || this.screenSize === ScreenSizeEnum.SM) { this.displayedColumns = JSON.parse(JSON.stringify(this.tableSetting.columnSelectionSM)); } else { this.displayedColumns = JSON.parse(JSON.stringify(this.tableSetting.columnSelection)); } this.displayedColumns.unshift('active'); this.displayedColumns.push('actions'); this.pageSize = this.tableSetting.recordsPerPage ? +this.tableSetting.recordsPerPage : PAGE_SIZE; this.colWidth = this.displayedColumns.length ? ((this.commonService.getContainerSize().width / this.displayedColumns.length) / 14) + 'rem' : '20rem'; this.logger.info(this.displayedColumns); }); this.store.select(offers).pipe(takeUntil(this.unSubs[3])). subscribe((offersSeletor: { offers: Offer[], apiCallStatus: ApiCallStatusPayload }) => { this.errorMessage = ''; this.apiCallStatus = offersSeletor.apiCallStatus; if (this.apiCallStatus.status === APICallStatusEnum.ERROR) { this.errorMessage = !this.apiCallStatus.message ? '' : (typeof (this.apiCallStatus.message) === 'object') ? JSON.stringify(this.apiCallStatus.message) : this.apiCallStatus.message; } this.offerJSONArr = offersSeletor.offers || []; if (this.offerJSONArr && this.offerJSONArr.length > 0 && this.sort && this.paginator && this.displayedColumns.length > 0) { this.loadOffersTable(this.offerJSONArr); } this.logger.info(offersSeletor); }); } ngAfterViewInit() { if (this.offerJSONArr && this.offerJSONArr.length > 0 && this.sort && this.paginator && this.displayedColumns.length > 0) { this.loadOffersTable(this.offerJSONArr); } } openCreateOfferModal() { this.store.dispatch(openAlert({ payload: { data: { pageSize: this.pageSize, component: CLNCreateOfferComponent } } })); } onOfferClick(selOffer: Offer) { const reCreatedOffer: Offer = { used: selOffer.used, single_use: selOffer.single_use, active: selOffer.active, offer_id: selOffer.offer_id, bolt12: selOffer.bolt12, created: selOffer.created, label: selOffer.label }; this.store.dispatch(openAlert({ payload: { data: { offer: reCreatedOffer, newlyAdded: false, component: CLNOfferInformationComponent } } })); } onDisableOffer(selOffer: Offer) { this.store.dispatch(openConfirmation({ payload: { data: { type: AlertTypeEnum.CONFIRM, alertTitle: 'Disable Offer', titleMessage: 'Disabling Offer: ' + (selOffer.offer_id || selOffer.bolt12), noBtnText: 'Cancel', yesBtnText: 'Disable' } } })); this.rtlEffects.closeConfirm.pipe(takeUntil(this.unSubs[4])).subscribe((confirmRes) => { if (confirmRes) { this.store.dispatch(disableOffer({ payload: { offer_id: selOffer.offer_id! } })); } }); } onPrintOffer(selOffer: Offer) { this.dataService.decodePayment(selOffer.bolt12!, false). pipe(take(1)).subscribe((offerDecoded: OfferRequest) => { if (offerDecoded.offer_id && !offerDecoded.offer_amount_msat) { offerDecoded.offer_amount_msat = 0; } const documentDefinition = { pageSize: 'A5', pageOrientation: 'portrait', pageMargins: [10, 50, 10, 50], background: { svg: ` `, width: 249, height: 333, absolutePosition: { x: 84, y: 160 } }, header: { text: (offerDecoded.offer_issuer || ''), alignment: 'center', fontSize: 25, color: '#272727', margin: [0, 20, 0, 0] }, content: [ { svg: '', width: 249, height: 40, alignment: 'center' }, { text: offerDecoded.offer_description ? offerDecoded.offer_description.substring(0, 160) : '', alignment: 'center', fontSize: 16, color: '#5C5C5C' }, { qr: selOffer.bolt12, eccLevel: 'M', fit: '227', alignment: 'center', absolutePosition: { x: 7, y: 205 } }, { text: (!offerDecoded?.offer_amount_msat || offerDecoded?.offer_amount_msat === 0 ? 'Open amount' : (this.decimalPipe.transform((offerDecoded.offer_amount_msat || 0) / 1000) + ' SATS')), fontSize: 20, bold: false, color: 'white', alignment: 'center', absolutePosition: { x: 0, y: 430 } }, { text: 'SCAN TO PAY', fontSize: 22, bold: true, color: 'white', alignment: 'center', absolutePosition: { x: 0, y: 455 } } ], footer: { svg: ` `, alignment: 'center' } }; pdfMake.createPdf(documentDefinition, null, null, pdfFonts.pdfMake.vfs).download('Offer-' + (offerDecoded && offerDecoded.offer_description ? offerDecoded.offer_description : selOffer.bolt12)); }); } applyFilter() { this.offers.filter = this.selFilter.trim().toLowerCase(); } getLabel(column: string) { const returnColumn: ColumnDefinition = this.nodePageDefs[this.PAGE_ID][this.tableSetting.tableId].allowedColumns.find((col) => col.column === column); return returnColumn ? returnColumn.label ? returnColumn.label : this.camelCaseWithReplace.transform(returnColumn.column, '_') : this.commonService.titleCase(column); } setFilterPredicate() { this.offers.filterPredicate = (rowData: Offer, fltr: string) => { let rowToFilter = ''; switch (this.selFilterBy) { case 'all': rowToFilter = ((rowData.active) ? ' active' : ' inactive') + ((rowData.used) ? ' yes' : ' no') + ((rowData.single_use) ? ' single' : ' multiple') + JSON.stringify(rowData).toLowerCase(); if (fltr === 'active' || fltr === 'inactive' || fltr === 'single' || fltr === 'multiple') { fltr = ' ' + fltr; } break; case 'active': rowToFilter = rowData?.active ? 'active' : 'inactive'; break; default: rowToFilter = typeof rowData[this.selFilterBy] === 'undefined' ? '' : typeof rowData[this.selFilterBy] === 'string' ? rowData[this.selFilterBy].toLowerCase() : typeof rowData[this.selFilterBy] === 'boolean' ? (rowData[this.selFilterBy] ? 'yes' : 'no') : rowData[this.selFilterBy].toString(); break; } return this.selFilterBy === 'active' ? rowToFilter.indexOf(fltr) === 0 : rowToFilter.includes(fltr); }; } loadOffersTable(offrs: Offer[]) { this.offers = (offrs) ? new MatTableDataSource([...offrs]) : new MatTableDataSource([]); this.offers.sort = this.sort; this.offers.sortingDataAccessor = (data: any, sortHeaderId: string) => ((data[sortHeaderId] && isNaN(data[sortHeaderId])) ? data[sortHeaderId].toLocaleLowerCase() : data[sortHeaderId] ? +data[sortHeaderId] : null); this.offers.paginator = this.paginator; this.setFilterPredicate(); this.applyFilter(); } onDownloadCSV() { if (this.offers.data && this.offers.data.length > 0) { this.commonService.downloadFile(this.offers.data, 'Offers'); } } ngOnDestroy() { this.unSubs.forEach((completeSub) => { completeSub.next(null); completeSub.complete(); }); } }