import { Component, OnInit } from '@angular/core'; import { InvoicesService } from '../../../services/invoices.service'; import { Subject } from 'rxjs'; import { FormGroup, FormBuilder } from '@angular/forms'; import { BsModalRef, BsModalService } from 'ngx-bootstrap'; import { AssignSalesComponent } from '../assign-sales/assign-sales.component'; import { ToastrService } from 'ngx-toastr'; import { WorkflowStateService } from '../../../services/workflowState.service'; import { AlertModalComponent } from '../../common/alert-modal/alert-modal.component'; import { PrintSalesInvoiceModalComponent } from '../../sales/sales-order-print-modal/sales-order-print-modal.component'; import { RefundSalesComponent } from '../refund-sales/refund-sales.component'; import { ExportComponent } from '../../common/export/export.component'; @Component({ selector: 'app-orders', templateUrl: './orders.component.html', styleUrls: ['./orders.component.css'] }) export class OrdersComponent implements OnInit { pageName: string = 'for_order'; allOrderDetails: any; alertConfirm: any; tableData: any[]; originalData: any[]; bsModalRef: BsModalRef; masterSelected: boolean; cancelEnabled: boolean; checkedList: any; isInProgressEnabled = false; isDeliveredEnabled: boolean; isAssignedEnabled: boolean; isPaidEnabled: boolean; isRefundEnabled: boolean; isExportEnabled: boolean; dtOptions: DataTables.Settings = {}; dtTrigger: Subject = new Subject(); workflowStates: { state_id: number; flow_state: string; }[]; orderForm: FormGroup; currentOrderState: number = 2; defaultOrderState: number = 0; isSingleRowSelected: boolean = false; constructor(private invoiceService: InvoicesService, private stateService: WorkflowStateService, private toastr: ToastrService, private fb: FormBuilder, private modalService: BsModalService) { } ngOnInit() { this.stateService.getAllWorkflowStateByPage(this.pageName).subscribe((result: { status: string, message: string, data }) => { this.workflowStates = result.data; this.workflowStates.push({ "state_id": 0, "flow_state": "ALL STATES" }); this.orderForm.controls['orderState'].setValue(this.workflowStates.find((state) => state.flow_state === 'CONFIRMED').state_id) }); this.loadData(this.currentOrderState); this.orderForm = this.fb.group({ orderState: [], startDate: [] }); this.orderForm.get('startDate').valueChanges.subscribe(value => this.changeDate()); } /* @usage: called to load the table with data @purpose: called whenever there is state changed . */ loadData(id) { this.invoiceService.getAllInvoicesByOrderStatus(id).subscribe((result: { status: string, message: string, data }) => { this.tableData = result.data; for (let i = 0; i < this.tableData.length; i++) { this.isExportEnabled = true; this.tableData[i].isSelected = false; if(this.tableData[i].order_workflow_state != null) { this.tableData[i].orderStates = this.tableData[i].order_workflow_state.flow_state; this.tableData[i].order_state = this.tableData[i].order_workflow_state.flow_state; } if(this.tableData[i].invoice_workflow_state != null){ this.tableData[i].invoiceStates = this.tableData[i].invoice_workflow_state.flow_state; this.tableData[i].invoice_state = this.tableData[i].invoice_workflow_state.flow_state; } if(this.tableData[i].address != null){ this.tableData[i].buc = this.tableData[i].address.buc; this.tableData[i].adn = this.tableData[i].address.adn; this.tableData[i].location_name = this.tableData[i].address.location_name; this.tableData[i].centre = this.tableData[i].address.centre; } if(this.tableData[i].team_member != null){ this.tableData[i].member_name = this.tableData[i].team_member.member_name; } this.tableData[i].amount_paid = this.tableData[i].paid_amount; } this.originalData = this.tableData; this.masterSelected = false; this.isInProgressEnabled = false; this.isDeliveredEnabled = false; this.cancelEnabled = false; this.isAssignedEnabled = false; this.isPaidEnabled = false; this.isRefundEnabled = false; this.dtTrigger.next(); }); this.dtOptions = { columnDefs: [{ type: 'date', 'targets': [1] }, { 'orderable': false, 'targets': [0]}], order: [[1, 'desc']], pageLength: 100, scrollX: true } } updateData(searchDate){ let dataLength = this.originalData.length; this.tableData = []; this.checkedList = []; for (let i = 0; i < dataLength; i++) { if(this.originalData[i].invoice_date === searchDate) { this.tableData.push(this.originalData[i]); } } if(this.tableData.length > 0){ this.isExportEnabled = true; }else{ this.isExportEnabled = false; } this.masterSelected = false; this.isInProgressEnabled = false; this.isDeliveredEnabled = false; this.cancelEnabled = false; this.isAssignedEnabled = false; this.isPaidEnabled = false; this.isRefundEnabled = false; this.dtTrigger.next(); this.dtOptions = { columnDefs: [{ type: 'date', 'targets': [1] }], order: [[1, 'desc']], pageLength: 100, scrollX: true } } /* @usage: called whenever the new date is selected @purpose: loads the table with date selected. */ changeDate() { var datechoosed = this.orderForm.get('startDate').value; if (datechoosed != null) { var date = new Date(datechoosed), month = ("0" + (date.getMonth() + 1)).slice(-2), day = ("0" + date.getDate()).slice(-2); var searchDate = [date.getFullYear(), month, day].join("-"); var table = $('#invoiceGrid').DataTable(); table.destroy(); this.updateData(searchDate); } } /* @usage: called whenever there is statechange filter is called @purpose: based on selected state it will load the data. */ orderStateChanged(stateID) { if(this.currentOrderState!==stateID){ this.currentOrderState = stateID; this.orderForm.get('startDate').setValue(null); var table = $('#invoiceGrid').DataTable(); table.destroy(); this.loadData(this.currentOrderState); } } /* @usage: called whenever single checkbox is selected @purpose: update the selected checklist invoices */ rowSelectedUnselected() { let inProgessRecordFound = false, confirmedRecordFound = false, index; this.masterSelected = this.tableData.every(function (item: any) { return item.isSelected == true; }) this.getCheckedItemList(); if (this.checkedList.length > 0) { this.isAssignedEnabled = true; for (index = 0; index < this.checkedList.length; index++) { let orderState = (this.checkedList[index].order_state).toUpperCase(); if (orderState === 'CONFIRMED'){ if(inProgessRecordFound){ this.disableBtns(); break; }else{ confirmedRecordFound = true; this.isInProgressEnabled = true; this.cancelEnabled = true; // this.isPaidEnabled = true; } } else if(orderState === 'IN PROGRESS'){ if(confirmedRecordFound){ this.disableBtns(); break; }else{ inProgessRecordFound = true; this.isDeliveredEnabled = true; } } else { this.disableBtns(); break; } } } else { this.disableBtns(); this.isAssignedEnabled = false; } this.isSingleRowSelected = this.checkedList.length === 1 ? true : false; if (this.isSingleRowSelected ) { if(this.checkedList[0].invoice_state.toUpperCase() === 'PAID') { this.isRefundEnabled = true; }else if ( this.checkedList[0].invoice_state.toUpperCase() === 'CONFIRMED' ||this.checkedList[0].invoice_state.toUpperCase() === 'NOT PAID' ){ this.isRefundEnabled = false; this.isPaidEnabled = true; } else { this.isRefundEnabled = false; this.isPaidEnabled = false; } } else { this.isRefundEnabled = false; this.isPaidEnabled = false; } } disableBtns(){ this.isDeliveredEnabled = false; this.isInProgressEnabled = false; this.cancelEnabled = false; this.isPaidEnabled = false; this.isRefundEnabled = false; } /* @usage: called when selectAll is checked @purpose: To select and unselect all checkbox. */ checkUncheckAll() { let inProgessRecordFound = false, confirmedRecordFound = false, table = $('#invoiceGrid').DataTable(); let pageLength = table.page.len(), sortOrderIndex = table.rows()[0]; let currViewIndices = sortOrderIndex.splice(0, pageLength); this.masterSelected = !this.masterSelected; for (var i = 0; i < currViewIndices.length; i++) { this.tableData[currViewIndices[i]].isSelected = this.masterSelected; } this.checkedList = []; if(this.masterSelected){ this.isAssignedEnabled = true; this.getCheckedItemList(); } if (this.checkedList.length > 0) { for (var i = 0; i < this.checkedList.length; i++) { var invoiceState = (this.checkedList[i].order_state).toUpperCase(); if (invoiceState === 'CONFIRMED' || invoiceState === 'NOT PAID'){ if(inProgessRecordFound){ this.disableBtns(); break; }else{ confirmedRecordFound = true; this.isInProgressEnabled = true; this.cancelEnabled = true; this.isPaidEnabled = true; } } else if(invoiceState === 'IN PROGRESS'){ if(confirmedRecordFound){ this.disableBtns(); break; }else{ inProgessRecordFound = true; this.isDeliveredEnabled = true; } } else { this.disableBtns(); break; } } } else { this.disableBtns(); this.isAssignedEnabled = false; } } /* @purpose: get all the selected invoices. */ getCheckedItemList() { this.checkedList = []; for (var i = 0; i < this.tableData.length; i++) { if (this.tableData[i].isSelected) this.checkedList.push(this.tableData[i]); } } OpenViewModal(salesOrder) { this.invoiceService.getAllInvDetailsOfInvoice(salesOrder.invoice_id).subscribe((defaultsFromDB : {status: string, message: string, data: []}) => { this.allOrderDetails = defaultsFromDB.data; this.bsModalRef = this.modalService.show(PrintSalesInvoiceModalComponent, { class: 'modal-lg', initialState: { customerSSO:Number(salesOrder.customer_id), invoiceState: salesOrder.invoice_state, subTotal: salesOrder.sub_total, totalAmount: salesOrder.total_amount, handlingFee: salesOrder.handling_fee, walletUsed:salesOrder.wallet_value_used, discount: salesOrder.discount_value , addressDetails: salesOrder.address, allOrderDetails: defaultsFromDB.data, } }); }, ( error ) => { this.toastr.error("Something Went Wrong! Please try to refresh"); }); } getCheckedListInvoiceIds(){ let invoiceIds = []; for (let i = 0; i < this.checkedList.length; i++) { invoiceIds.push(this.checkedList[i].invoice_id); } return invoiceIds; } assignTo() { this.bsModalRef = this.modalService.show(AssignSalesComponent); this.bsModalRef.content.event.subscribe(res=>{ let assignedTeamMemberId = res; if (assignedTeamMemberId) { let invoiceIds = this.getCheckedListInvoiceIds(); this.invoiceService.assignOrder({invoices:invoiceIds, team_member_id: assignedTeamMemberId}).subscribe((result: { status: string, message: string, data }) => { if (result.status === 'success') { var table = $('#invoiceGrid').DataTable(); table.destroy(); this.toastr.success('Order assigned successfully.'); this.loadData(this.currentOrderState); } }, (error) => { var table = $('#invoiceGrid').DataTable(); table.destroy(); this.toastr.error('Cannot assign the order.'); this.loadData(this.currentOrderState); }, ); } }); } markAsDelivered(){ let invoiceIds = this.getCheckedListInvoiceIds(); this.invoiceService.updateOrderStatusToDelivered({invoices:invoiceIds}).subscribe((result: { status: string, message: string, data }) => { if (result.status === 'success') { var table = $('#invoiceGrid').DataTable(); table.destroy(); this.toastr.success('Order Status updated to delivered successfully.'); this.loadData(this.currentOrderState); } }, (error) => { var table = $('#invoiceGrid').DataTable(); table.destroy(); this.toastr.error('Cannot Update the order status to delivered.'); this.loadData(this.currentOrderState); }, ); } markAsInProgress(){ let invoiceIds = this.getCheckedListInvoiceIds(); this.invoiceService.updateOrderStatusToInProgress({invoices:invoiceIds}).subscribe((result: { status: string, message: string, data }) => { if (result.status === 'success') { var table = $('#invoiceGrid').DataTable(); table.destroy(); this.toastr.success('Order Status updated to in progress successfully.'); this.loadData(this.currentOrderState); } }, (error) => { var table = $('#invoiceGrid').DataTable(); table.destroy(); this.toastr.error('Cannot Update the order status to in progress.'); this.loadData(this.currentOrderState); }, ); } cancelOrder(){ this.bsModalRef = this.modalService.show(AlertModalComponent, { backdrop: 'static', keyboard: false, animated: true, ignoreBackdropClick: true, initialState: { title: 'Alert', data: 'Do you want to cancel the selected Order?', buttonText: 'No', deleteBtn: 'Yes' } }); this.bsModalRef.content.event.subscribe(res => { this.alertConfirm = res; if (this.alertConfirm) { let invoices = []; for (let i = 0; i < this.checkedList.length; i++) { invoices.push(this.checkedList[i].invoice_id); } this.invoiceService.cancelSalesOrder({invoice_id: invoices.toString()}).subscribe((result: { status: string, message: string, data }) => { if (result.status === 'success') { var table = $('#invoiceGrid').DataTable(); table.destroy(); this.toastr.success('Orders cancelled successfully.'); this.loadData(this.currentOrderState); } }, (error) => { var table = $('#invoiceGrid').DataTable(); table.destroy(); this.toastr.error('Cannot cancel the Order.'); this.loadData(this.currentOrderState); } ); } }); } /* @usage: to mark the selected record as paid */ markAsPaid(){ let invoiceIds = this.getCheckedListInvoiceIds(); this.invoiceService.updateInvoiceStateToPaid({invoices:invoiceIds}).subscribe((result: { status: string, message: string, data }) => { if (result.status === 'success') { var table = $('#invoiceGrid').DataTable(); this.toastr.success('Order updated successfully.'); table.destroy(); this.loadData(this.currentOrderState); } }, (error) => { var table = $('#invoiceGrid').DataTable(); this.toastr.error('Order Cannot be updated.'); table.destroy(); this.loadData(this.currentOrderState); }, ); } /* @usage: to mark selected record as refund */ markAsRefund(){ this.bsModalRef = this.modalService.show(RefundSalesComponent,{ backdrop: 'static', keyboard: false, animated: true, ignoreBackdropClick: true, initialState: { invoiceId: this.checkedList[0].invoice_id, amountPaid: Number(this.checkedList[0].amount_paid), config: "{ backdrop: 'static' }" } }); this.bsModalRef.content.event.subscribe(res=>{ let refundResult = res; if(refundResult){ var table = $('#invoiceGrid').DataTable(); table.destroy(); this.loadData(this.currentOrderState); } }); } /* @usage: to export selected record */ export(){ this.bsModalRef = this.modalService.show(ExportComponent,{ class: 'modal-md', backdrop: 'static', keyboard: false, animated: true, ignoreBackdropClick: true, initialState: { checkedList: (this.checkedList === undefined) || (this.checkedList && this.checkedList.length === 0) ? this.tableData : this.checkedList, fullDataSet: (this.checkedList === undefined) || (this.checkedList && this.checkedList.length === 0) ? true : false, config: "{ backdrop: 'static' }" } }); } }