import { Component, OnInit, Renderer2, ElementRef, Input } from '@angular/core'; import { TableModule } from 'primeng/table'; import { JsonrpcService, RpcService } from 'src/app/services/jsonrpc.service'; import { MessageService } from 'primeng/api'; import { Order, Products, Delivery_address, Notification, Refund, } from 'src/app/interface/data'; import { ClientsComponent } from '../clients/clients.component'; import { ToastModule } from 'primeng/toast'; import { ConfirmationService, FilterService, FilterMatchMode, SelectItem, } from 'primeng/api'; import { OrderTypes } from 'src/app/data/data'; import { catchError, map } from 'rxjs'; /*import { SwPush, NewsletterService } from '@angular/service-worker*/ @Component({ selector: 'app-orders', templateUrl: './orders.component.html', styleUrls: ['./orders.component.scss'], providers: [ClientsComponent], }) export class OrdersComponent implements OnInit { public orders: Array = []; public order: Array = []; public view: boolean = true; public chooseName!: string; public lastOrderUpdateTime: string = ''; public choose = this.jsonRpcService.ClientChoose; public notification: Array = []; public map_new = new Map(); public map_new_fin = new Map(); public map_due = new Map(); public myAudioP = new Audio(); public myAudioA = new Audio(); public refund!: Refund; public sumRef: number = 0; public sumRef0: any = 0; public sumRef1: any = 0; public sumRef2: any = 0; public sumRef3: any = 0; public matchModeOptions!: SelectItem[]; public dis: boolean = false; public readonly orderTypes = OrderTypes; public selectedStatus: string = ''; public statuses = [ 'К готовке', 'Готовится', 'Готово', 'Отменен', 'Можно забирать', 'У курьера', 'Доставлен', 'Не подтвержден', 'Требует согласия', 'Требуется оплата', 'Оплата просрочена', 'Новый', 'Выдан', 'Нужен возврат', 'Чек напечатан', ]; constructor( private jsonRpcService: JsonrpcService, private messageService: MessageService, private clientsComponent: ClientsComponent, private confirmationService: ConfirmationService, private filterService: FilterService ) {} async ngOnInit() { if (this.choose) { this.getOrders(); setTimeout(() => this.notif(), 700); setInterval(() => this.getOrders(), 60000); this.chooseName = this.jsonRpcService.ClientChooseName; } const customFilterName = 'custom-contains'; this.filterService.register( customFilterName, (value: any, filter: any): boolean => { if (filter === undefined || filter === null || filter.trim() === '') { return true; } if (value === undefined || value === null) { return false; } let det = value.toString(); let det2 = det.toLowerCase(); return ( det2.includes(filter.toString()) || det.includes(filter.toString()) ); } ); this.matchModeOptions = [ { label: 'Содержит', value: customFilterName }, { label: 'Равно', value: FilterMatchMode.EQUALS }, { label: 'Начинается с', value: FilterMatchMode.STARTS_WITH }, ]; } keysFromObject(object: any) { return Object.keys(object); } notif() { for (let i = 0; i < this.orders.length; i++) { this.map_new.set(this.orders[i].id, true); this.map_new_fin.set(this.orders[i].id, true); } } async getOrders() { this.myAudioP.src = '../../../assets/myAudio12.mp3'; this.myAudioA.src = '../../../assets/myAudio23.mp3'; if (this.view == true) { await this.jsonRpcService .rpc2( { method: 'getOrders', params: { client_id: this.choose, order_status: [ 'readyToStart', 'inProgress', 'complete', 'cancel', 'readyToPickup', 'onWay', 'delivered', 'unconfirmed', 'requiresConsent', 'requiresPayment', 'paymentOverdue', 'newOrder', 'issued', 'needReturnPayment', 'printedCheck', ], }, }, RpcService.authService, false ) .subscribe({ next: (result) => { let data = result.result; this.color(data); this.orders = data; this.lastOrderUpdateTime = Date().toString(); document.getElementsByTagName('thead')[0].style.display = 'table'; document.getElementsByTagName('thead')[0].style.width = '100%'; document.getElementsByTagName('thead')[0].style.tableLayout = 'fixed'; document.getElementsByTagName('tbody')[0].style.display = 'block'; document.getElementsByTagName('tbody')[0].style.maxHeight = 'calc(100vh - 385px)'; document.getElementsByTagName('tbody')[0].style.overflowY = 'scroll'; }, error: (err) => { console.log('ERROR: ', err); this.messageService.add({ severity: 'error', summary: 'Произошла ошибка!', }); }, }); } setTimeout(() => this.notif2(), 700); } saveStatus(orderId: number) { this.jsonRpcService .rpc( { method: 'changeOrderStatusForOperator', params: [this.choose, orderId, this.selectedStatus], }, RpcService.authService, true ) .pipe( map((value) => { return value; }), catchError((err) => { return err; }) ).subscribe({ next: (value) => { this.messageService.add({ severity: 'success', summary: 'Статус изменен!', }); console.log('####: value ', value); }, error: (err) => { console.error(err) this.messageService.add({ severity: 'error', summary: 'Произошла ошибка!', }); }, }); } notif2() { for (let i = 0; i < this.orders.length; i++) { if (this.map_new.has(this.orders[i].id) == false) { this.map_new.set(this.orders[i].id, true); } if ( this.map_new_fin.has(this.orders[i].id) == false && this.map_new.has(this.orders[i].id) == true ) { this.myAudioP.load(); this.myAudioP.play(); this.map_new_fin.set(this.orders[i].id, true); this.messageService.add({ severity: 'info', detail: 'Пришел новый заказ №' + this.orders[i].external_id, summary: 'Новый заказ!', key: 'br', sticky: true, }); } var date1 = new Date(); var date2 = new Date(this.orders[i].due_datetime); if ( date2.getTime() - date1.getTime() < 1000 * 3600 && this.orders[i].status_h == 'К готовке' && this.map_due.has(this.orders[i].id) == false && date2.getTime() - date1.getTime() > 1000 * 3000 ) { this.myAudioA.load(); this.myAudioA.play(); this.map_due.set(this.orders[i].id, true); this.messageService.add({ severity: 'warn', detail: 'По заказу ' + this.orders[i].external_id + ' до прихода покупателя остался 1 час!', summary: 'Не взят в работу!', key: 'br', sticky: true, }); } } } async vievOrder(id: any) { this.dis = false; await this.jsonRpcService .rpc2( { method: 'getOrders', params: { client_id: this.choose, order_id: id }, }, RpcService.authService, false ) .subscribe({ next: (result) => { let data = result.result; this.order = data; }, error: (err) => { console.log('ERROR: ', err); this.messageService.add({ severity: 'error', summary: 'Произошла ошибка!', }); }, }); this.view = false; setTimeout(() => this.getOrderRefunds(this.order[0].external_id), 400); } async getOrderRefunds(id: any) { await this.jsonRpcService .rpc2( { method: 'getOrderRefunds', params: { external_id: id }, }, RpcService.authService, false ) .subscribe({ next: (result) => { let data = result.result; this.refund = data; if (this.refund.admin_return.status == 'COMPLETED') { this.sumRef0 = this.refund.admin_return.amount; } else this.sumRef0 = 0; if (this.refund.difference_return.status == 'COMPLETED') { this.sumRef1 = this.refund.difference_return.amount; } else this.sumRef1 = 0; if (this.refund.full_return.status == 'COMPLETED') { this.sumRef2 = this.refund.full_return.amount; } else this.sumRef2 = 0; this.sumRef3 = this.sumRef0 + this.sumRef1 + this.sumRef2; this.sumRef = parseFloat(this.sumRef3.toFixed(2)); }, error: (err) => { console.log('ERROR: ', err); this.messageService.add({ severity: 'error', summary: 'Произошла ошибка!', }); }, }); } doAdminRefund(id: any, type: any, id_: any) { this.dis = false; let qr_id: string; this.jsonRpcService .rpc2( { method: 'getOrders', params: { client_id: this.choose, order_id: id_ }, }, RpcService.authService, false ) .subscribe({ next: (result) => { let data = result.result; let dat: Order = data[0]; if (dat.payment[0].type == 'QR') { qr_id = dat.payment[0].payload.id; this.jsonRpcService .rpc2( { method: 'doAdminRefund', params: { order_id: id_, qr_id: qr_id }, }, RpcService.authService, false ) .subscribe({ next: (result) => { let data = result.result; this.dis = true; }, error: (err) => { console.log('ERROR: ', err); this.messageService.add({ severity: 'error', summary: `Произошла ошибка! ${err.error.error.message}`, }); }, }); } else { this.jsonRpcService .rpc2( { method: 'doAdminRefund', params: { order_id: id_ }, }, RpcService.authService, false ) .subscribe({ next: (result) => { let data = result.result; this.dis = true; }, error: (err) => { console.log('ERROR: ', err); this.messageService.add({ severity: 'error', summary: 'Произошла ошибка!', }); }, }); } }, error: (err) => { console.log('ERROR: ', err); this.messageService.add({ severity: 'error', summary: 'Произошла ошибка!', }); }, }); //await this.jsonRpcService.rpc2({ // method: 'doAdminRefund', // params: { "external_id": id, "qr_id": qr_id } //}, RpcService.authService, false) // .subscribe({ // next: (result) => { // let data = result.result // }, // error: (err) => { // console.log('ERROR: ', err) // this.messageService.add({ // severity: 'error', // summary: 'Произошла ошибка!', // }) // } // } // ); } listOrders() { this.view = true; this.getOrders(); } color(targetData: any) { for (let i = 0; i < targetData.length; i++) { var item = targetData[i]; var date1 = new Date(); var date2 = new Date(item.due_datetime); if ( date2.getTime() - date1.getTime() < 1000 * 3600 && item.status_h == 'К готовке' && date2.getTime() - date1.getTime() >= 0 ) { item.item_style = 'orange'; } if ( item.status_h == 'К готовке' && date2.getTime() - date1.getTime() < 0 ) { item.item_style = 'red'; } if (item.status_h == 'Готово') { item.item_style = 'green'; } if (item.status_h == 'Отменен' || item.status_h == 'Оплата просрочена') { item.item_style = 'grey'; } if ( date2.getTime() - date1.getTime() >= 1000 * 3600 && item.status_h == 'К готовке' ) { item.item_style = 'yellow'; } if (item.status_h == 'Готовится') { item.item_style = 'blue'; } if (item.status_h == 'Выдан') { item.item_style = 'lilac'; } if (item.status_h == 'Напечатан') { item.item_style = 'pink'; } } } confirm(id: any, type: any, id_: any) { if (type == 'QR') { this.confirmationService.confirm({ message: 'Вы действительно хотите сделать возврат оплаты и отменить заказ?', accept: () => { this.doAdminRefund(id, type, id_); }, }); } else { this.confirmationService.confirm({ message: 'Вы действительно хотите отменить заказ?', accept: () => { this.doAdminRefund(id, type, id_); }, }); } } leadToTypeOrderType(str: any) { return str as keyof typeof this.orderTypes; } }