import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; import { Subject } from 'rxjs'; import { InvoicesService } from '../../../services/invoices.service'; @Component({ selector: 'app-item-sales', templateUrl: './item-sales.component.html', styleUrls: ['./item-sales.component.css'] }) export class ItemSalesComponent implements OnInit { public form: FormGroup; currentDate: string; tableData : any[]; endDateError = false; dtOptions: DataTables.Settings = {}; dtTrigger: Subject = new Subject(); isLoadSalesEnabled: boolean = true; constructor(private fb:FormBuilder, private invoiceService:InvoicesService) {} ngOnInit(): void { this.form = this.fb.group({ transactionType: new FormControl(), startDate: [new Date(), Validators.required], endDate: [new Date(), Validators.required] }); this.loadData(this.getCurrentDate(), this.getCurrentDate()); this.form.get('endDate').valueChanges.subscribe(value => this.changeDate()); this.form.get('startDate').valueChanges.subscribe(value => this.changeDate()); } /* @usage: to get the current date */ getCurrentDate(currDate?: any) { var currentDate = currDate ? currDate : new Date(); var dd = String(currentDate.getDate()).padStart(2, '0'); var mm = String(currentDate.getMonth() + 1).padStart(2, '0'); var yyyy = currentDate.getFullYear(); var date = yyyy + '-' + mm + '-' + dd; return date; } /* @usage: called whenever the new date is selected @purpose: loads the table with date selected. */ changeDate() { let endDate = this.form.get('endDate').value, startDate = this.form.get('startDate').value; if (endDate != null && startDate!= null) { if(this.getCurrentDate(endDate) < this.getCurrentDate(startDate)){ this.isLoadSalesEnabled = false; this.endDateError = true; } else{ this.isLoadSalesEnabled = true; this.endDateError = false; } } } /* @usage: called when a table is loaded @param date : date of the transaction to be fetched. @purpose: loads the table with date selected bydefault current date will be selected. */ loadData(fromDate, toDate) { this.invoiceService.getSalesDetailsByDate(fromDate, toDate).subscribe((data: any) => { this.tableData = data.data; // if(this.tableData && this.tableData.length > 0){ // for ( let index = 0; index < this.tableData.length; index++){ // if(this.tableData[index] && this.tableData[index].variants_info){ // this.tableData[index].item_name = this.tableData[index].item_name + ' - ' + this.tableData[index].variants_info; // } // } // }else{ // this.tableData = []; // } this.dtTrigger.next(); }); this.dtOptions = { order: [[0, 'asc']], scrollX: true } } loadSalesData(){ let endDate = this.form.get('endDate').value, startDate = this.form.get('startDate').value; if(endDate !== null && startDate !== null){ let table = $('#salesTable').DataTable(); table.destroy(); this.loadData(this.getCurrentDate(startDate), this.getCurrentDate(endDate)); } } }