import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { FormGroup, FormBuilder, Validators, FormArray } from '@angular/forms'; import { AccountService } from '../../../services/account.service'; import { JournalService } from '../../../services/journal.service'; import { VendorService } from '../../../services/vendor.service'; import { ToastrService } from 'ngx-toastr'; import { NGXLogger } from 'ngx-logger'; @Component({ selector: 'app-new-journal', templateUrl: './new-journal.component.html', styleUrls: ['./new-journal.component.css'], encapsulation: ViewEncapsulation.None }) export class NewJournalComponent implements OnInit { newJournalForm: FormGroup; addedItems: FormArray; accountNames: any contactNames: any[] vendorNames: any teamMemberNames: any customerNames: any name: string id: string subTotal: number totalCredits: number = 0; subCredits: string = '0.0'; subDebits: string = '0.0'; totalDebits: number = 0; total: number = 0; customerColumns = ['sso','customer_name']; teamColumnName =['team_member_id','member_name']; vendorColumnName = ['display_name','vendor_id']; constructor(private fb: FormBuilder, private toastr: ToastrService, private accountService: AccountService, private journalService: JournalService, private vendorService: VendorService,private logger: NGXLogger) { } ngOnInit(): void { this.newJournalForm = this.fb.group({ startDate: [new Date(), Validators.required], reference: [''], note: ['', Validators.required], createNewItemFor: [], addedItems: this.fb.array([]), totalAmount: [] }); this.addedItems = this.newJournalForm.get('addedItems') as FormArray; this.addedItems.push(this.createAccountForm()); this.addItemToJournalAccount(); this.accountService.getAllAccountNames().subscribe((result: { status: string, message: string, data }) => { this.accountNames = result.data; }); this.newJournalForm.get('createNewItemFor').setValue('customer'); this.journalService.getAllCustomersByColumn(this.customerColumns).subscribe((result: { status: string, message: string, data }) => { this.contactNames = result.data.map((term) => { return { id: term.sso, name: term.customer_name } }); }); } get startDate() { return this.newJournalForm.get('startDate') } get reference() { return this.newJournalForm.get('reference') } get note() { return this.newJournalForm.get('note') } get createNewItemFor() { return this.newJournalForm.get('createNewItemFor') } /* used to dynamically create a item formGroup in a formArray, This adds an row to items table in UI. */ private createAccountForm(): FormGroup { return this.fb.group({ account: [], contactName: [], debits: [], credits: [], amounts: [], createdBy: [], }); } /* @usage: called when we click on add more items link @purpose: new items added to journal. */ addItemToJournalAccount() { this.logger.debug('Adding items to account table'); this.addedItems.push(this.createAccountForm()); } /* @usage: called whenever there is amount is changed in credit or debit @purpose: based on amount entered in credit or debit total amount gets changes. */ amountChanged(itemIndex, name) { this.totalCredits = 0; this.totalDebits = 0; this.total = 0 if (name === 'debit') { if (Number(this.newJournalForm.value.addedItems[itemIndex].debits) < 0 || !Number(this.newJournalForm.value.addedItems[itemIndex].debits)) { this.newJournalForm.value.addedItems[itemIndex].debits = ''; this.newJournalForm.controls['addedItems'].setValue(this.newJournalForm.value.addedItems); } if(this.newJournalForm.value.addedItems[itemIndex].debits) { this.newJournalForm.value.addedItems[itemIndex].debits = (this.newJournalForm.value.addedItems[itemIndex].debits).toFixed(2) this.newJournalForm.controls['addedItems'].setValue(this.newJournalForm.value.addedItems); } if (this.newJournalForm.value.addedItems[itemIndex].credits && this.newJournalForm.value.addedItems[itemIndex].debits) { this.newJournalForm.value.addedItems[itemIndex].credits = ''; this.newJournalForm.controls['addedItems'].setValue(this.newJournalForm.value.addedItems); } } if (name === 'credit') { if (Number(this.newJournalForm.value.addedItems[itemIndex].credits) < 0 || !Number(this.newJournalForm.value.addedItems[itemIndex].credits)) { this.newJournalForm.value.addedItems[itemIndex].credits = ''; this.newJournalForm.controls['addedItems'].setValue(this.newJournalForm.value.addedItems); } if(this.newJournalForm.value.addedItems[itemIndex].credits) { this.newJournalForm.value.addedItems[itemIndex].credits = (this.newJournalForm.value.addedItems[itemIndex].credits).toFixed(2) this.newJournalForm.controls['addedItems'].setValue(this.newJournalForm.value.addedItems); } if (this.newJournalForm.value.addedItems[itemIndex].credits && this.newJournalForm.value.addedItems[itemIndex].debits) { this.newJournalForm.value.addedItems[itemIndex].debits = ''; this.newJournalForm.controls['addedItems'].setValue(this.newJournalForm.value.addedItems); } } for (var i = 0; i < this.newJournalForm.value.addedItems.length; i++) { this.totalDebits += Number(this.newJournalForm.value.addedItems[i].debits); this.totalCredits += Number(this.newJournalForm.value.addedItems[i].credits); } this.total = this.totalDebits + this.totalCredits; this.subCredits = this.totalCredits.toFixed(2); this.subDebits = this.totalDebits.toFixed(2); } /* @usage: called when a single checkbox is checked @purpose: loads the contact list by the names of type selected. */ toggleCustomerType(name) { this.newJournalForm.get('createNewItemFor').setValue(name); this.addedItems = this.newJournalForm.get('addedItems') as FormArray; this.addedItems.clear(); this.addedItems.push(this.createAccountForm()); this.addItemToJournalAccount(); this.defaultFormValues(); if (name === 'teamMember') { this.journalService.getAllTeamMembersByColumn(this.teamColumnName).subscribe((result: { status: string, message: string, data }) => { this.contactNames = result.data.map((term) => { return { id: term.team_member_id, name: term.member_name + '-'+ term.team_member_id } }); }); } else if (name === 'customer') { this.journalService.getAllCustomersByColumn(this.customerColumns).subscribe((result: { status: string, message: string, data }) => { this.contactNames = result.data.map((term) => { return { id: term.sso, name: term.customer_name } }); }); } else if (name === 'vendor') { this.vendorService.getAllVendors(this.vendorColumnName).subscribe((result: { status: string, message: string, data }) => { this.contactNames = result.data.map((term) => { return { id: term.vendor_id, name: term.display_name } }); }); } } /* @usage: called when a item row needs to be removed dynamically @param removeItemIndex : index of the item to be removed. @purpose: removes item fromgroup to formArray at provided index. */ removeItemFromJournal(removeItemIndex: number) { this.logger.debug('Removing row from account tables by default 2 rows must be present'); if (this.newJournalForm.value.addedItems.length > 2) { this.totalDebits -= Number(this.newJournalForm.value.addedItems[removeItemIndex].debits); this.totalCredits -= Number(this.newJournalForm.value.addedItems[removeItemIndex].credits); this.subCredits = this.totalCredits.toFixed(2); this.subDebits = this.totalDebits.toFixed(2); this.addedItems.removeAt(removeItemIndex); } } /* @usage: called when a save btn is clicked @purpose: submit the data into journals. */ onSubmit() { var flag = true; if (this.newJournalForm.valid) { //By Default 2 rows must be present in table if (this.newJournalForm.value.addedItems.length >= 2) { for (var i = 0; i < this.newJournalForm.value.addedItems.length; i++) { if (!this.newJournalForm.value.addedItems[i].account) { flag = false; this.toastr.error("Cannot create a Journal without account"); } else if ((!this.newJournalForm.value.addedItems[i].debits || this.newJournalForm.value.addedItems[i].debits === 0) && (!this.newJournalForm.value.addedItems[i].credits || this.newJournalForm.value.addedItems[i].credits === 0)) { flag = false; this.toastr.error("Cannot create a Journal without credit or debit"); } } } if (flag) { if (this.totalDebits != this.totalCredits) this.toastr.error("Debits and Credits must be equal"); else { this.newJournalForm.get('totalAmount').setValue(Math.floor(this.totalCredits)); this.journalService.createNewJournal(this.newJournalForm.value).subscribe((CreationResult : {status: string, message: string, data }) => { if ( CreationResult.status === "success" ) { this.toastr.success("Journal Created Successfully") this.newJournalForm.reset(); this.newJournalForm.get('startDate').setValue(new Date()); this.newJournalForm.get('createNewItemFor').setValue('customer'); this.journalService.getAllCustomersByColumn(this.customerColumns).subscribe((result: { status: string, message: string, data }) => { this.contactNames = result.data.map((term) => { return { id: term.sso, name: term.customer_name } }); }); this.addedItems = this.newJournalForm.get('addedItems') as FormArray; this.addedItems.clear(); this.addedItems.push(this.createAccountForm()); this.addItemToJournalAccount(); this.defaultFormValues(); } else { this.toastr.error("Something Went Wrong! Please try to refresh"); } }, (error) => { this.toastr.error("Something Went Wrong! Please try to refresh"); }); } } } else { this.newJournalForm.controls['startDate'].markAllAsTouched(); this.newJournalForm.controls['note'].markAllAsTouched(); } } defaultFormValues() { this.totalCredits = 0; this.totalDebits = 0; this.subCredits = '0.0'; this.subDebits = '0.0'; } }