Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
- import { FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';
- import { Location } from '@angular/common';
- import { MatSnackBar } from '@angular/material';
- import { Subject, Observable, pipe } from 'rxjs';
- import { takeUntil, take, delay, startWith, map, debounceTime } from 'rxjs/operators';
- import { Router } from '@angular/router';
- import { fuseAnimations } from '@layout/animations';
- import { FuseUtils } from '@layout/utils';
- import { Category } from 'app/main/apps/inventory/category/category.model';
- import { InventoryCategoryService } from 'app/main/apps/inventory/category/category.service';
- import { ImageCroppedEvent } from 'ngx-image-cropper';
- import { MatDialog } from '@angular/material/dialog';
- import { PhotoPickerComponent } from 'app/photo-picker/photo-picker.component';
- import { InvoiceNewService } from './new.service';
- import { Invoice, Client, InvoiceProduct } from './invoice.model';
- import { ClientComponent } from '../client/client.component';
- import { searchProducts } from 'app/db-queries';
- import * as _ from 'lodash';
- import { by } from 'protractor';
- @Component({
- selector : 'new-invoice',
- templateUrl : './new.component.html',
- styleUrls : ['./new.component.scss'],
- encapsulation: ViewEncapsulation.None,
- animations : fuseAnimations
- })
- export class InvoiceNewComponent implements OnInit, OnDestroy
- {
- //todo: dodać pole całość, przy zaliczce wyłączyć pole termin płatności, zmienić label data wykonnaie usługi, na płatność
- invoice: any;
- preinvoice: any;
- searching: boolean;
- searchingProduct: boolean;
- invoiceForm: FormGroup;
- clients: Client[]
- filteredClients: Client[];
- searchedProducts: Client[];
- // orders: any;
- // Private
- private _unsubscribeAll: Subject<any>;
- /**
- * Constructor
- *
- * @param {CategoryService} _categoryService
- * @param {FormBuilder} _formBuilder
- * @param {Location} _location
- * @param {MatSnackBar} _matSnackBar
- */
- constructor(
- private _invoiceNewService: InvoiceNewService,
- private _formBuilder: FormBuilder,
- private _location: Location,
- private _matSnackBar: MatSnackBar,
- public dialog: MatDialog,
- private router: Router
- )
- {
- this.invoice = new Invoice();
- console.log(this.invoice.invoice_type, 'type');
- this.invoice.creation_date = new Date();
- this.searching = false;
- this.searchingProduct = false;
- this.searchedProducts = [];
- console.log('construct');
- // Set the private defaults
- this._unsubscribeAll = new Subject();
- this.filteredClients = [];
- }
- // -----------------------------------------------------------------------------------------------------
- // @ Lifecycle hooks
- // -----------------------------------------------------------------------------------------------------
- /**
- * On init
- */
- ngOnInit(): void
- {
- this.invoiceForm = this.createForm();
- //this.addProduct();
- console.log('init');
- this._invoiceNewService.onPreInvoiceChanged
- .pipe(takeUntil(this._unsubscribeAll))
- .subscribe(invoice => {
- this.preinvoice = invoice;
- this.invoice.reference_invoice = this.preinvoice.id;
- if(this.preinvoice.id){
- this.setAdvanceInvoiceType();
- }
- console.log(invoice, 'preee');
- }
- );
- this._invoiceNewService.onAdvancedPayments
- .pipe(takeUntil(this._unsubscribeAll))
- .subscribe((advancedPayments) => {
- this.invoice.advanced_payments = advancedPayments.filter(payment => payment.id != this.invoice.id);
- console.log(this.invoice.advanced_payments, 'advanced component');
- this.invoiceForm.get('payment_brutto').setValidators([Validators.max(this.calculateOutstandingAmount(this.invoice.total_brutto, 0))]);
- //this.calculateFinalSummaries(this.invoice.total_by_vat, this.invoice.advanced_payments);
- });
- this._invoiceNewService.onSellerChange
- .pipe(takeUntil(this._unsubscribeAll))
- .subscribe((seller) => {
- this.invoice.seller = seller.company_info;
- this.invoice.seller.logo = seller.logo
- console.log(this.invoice.seller, 'seller');
- });
- //todo: zmienić na nasłuchiwanie tylko jednego pola
- this.invoiceForm.valueChanges.
- pipe(
- startWith(''),
- debounceTime(300),
- map((value: any) => {
- console.log(value, 'value filtered');
- console.log(value, 'kekeke');
- return typeof value.client === 'string' ? value.client : value.name
- }),
- map(text => text && text.length >= 2 ? this._searchClients(text) : this.filteredClients = [])
- ).subscribe();
- this.searchProduct.valueChanges
- .pipe(
- startWith(''),
- map(value => value && value.length >= 2 ? this._searchProducts(value): this.searchedProducts = [])
- ).subscribe();
- this.invoiceForm.get("invoice_type").valueChanges.pipe(
- debounceTime(300)
- ).subscribe(()=>{
- if(this.invoiceForm.get('invoice_type').value == 2){
- this.disablePaymentField();
- }
- else {
- this.enablePaymentField();
- }
- this.getInvoiceNumber();
- })
- this.invoiceForm.get("creation_date").valueChanges.subscribe(()=>{
- this.getInvoiceNumber();
- })
- this.invoiceForm.get("payment_brutto").valueChanges.subscribe(()=>{
- this.invoice.outstanding_amount = this.calculateOutstandingAmount(this.invoice.total_brutto, this.invoiceForm.get('payment_brutto').value);
- let payment_brutto = this.invoiceForm.get('payment_brutto').value;
- let payment_by_vat = [];
- if(this.preinvoice.id){
- let total_payment_vat = 0;
- let total_payment_netto = 0
- let total_payment_brutto = 0
- this.preinvoice.total_by_vat.forEach(byVat => {
- //vat /netto /brutto /tax
- console.log(byVat, 'byvat');
- let brutto = (Math.round((byVat.brutto / this.preinvoice.total_brutto * payment_brutto) * 100) / 100);
- let netto = this.calculateTotalNetto(1, brutto, byVat.vat );
- let tax = this.calculateTotalTax(brutto, byVat.vat)
- total_payment_vat += tax;
- total_payment_netto += netto;
- total_payment_brutto += brutto;
- payment_by_vat.push({vat: byVat.vat, brutto: brutto, netto: netto, tax: tax});
- })
- this.invoice.payment_netto = Math.round(total_payment_netto *100)/100;
- this.invoice.payment_tax = Math.round(total_payment_vat *100)/100;
- this.invoice.payment_by_vat = payment_by_vat;
- }
- })
- this.getInvoiceNumber();
- // this.invoiceForm.valueChanges.
- // pipe(
- // startWith(''),
- // debounceTime(300),
- // map((value: any) => {
- // console.log(value, 'value filtered');
- // console.log(value, 'kekeke');
- // return typeof value.products && value.products[0].name === 'string' ? value.products[0].name[0].text : 'cto'
- // }),
- // map(text => text && text.length >= 2 ? this._searchClients(text) : this.filteredClients = [])
- // ).subscribe();
- }
- get searchProduct(): FormControl {
- //return this.productForm.get('name') as FormArray;
- return this.invoiceForm.get('searchProduct') as FormControl
- }
- get products(): FormArray {
- return this.invoiceForm.get('products') as FormArray;
- }
- getInvoiceNumber() {
- let type = parseInt(this.invoiceForm.get('invoice_type').value);
- let date = new Date(this.invoiceForm.get('creation_date').value).getTime();
- console.log(type, date);
- this._invoiceNewService.getInvoiceNumber(date,type).then(data => {
- this.invoiceForm.get('prefix').setValue(data.prefix);
- this.invoiceForm.get('number').setValue(data.number);
- this.invoice.inv_number = data.inv_number;
- })
- }
- disablePaymentField() {
- console.log('disable');
- this.invoiceForm.get('payment_brutto').setValue(0);
- this.invoiceForm.get('payment_brutto').disable();
- }
- enablePaymentField(){
- this.invoiceForm.get('payment_brutto').enable();
- }
- setAdvanceInvoiceType(){
- console.log(this.preinvoice, 'pre');
- this.preinvoice.products.forEach(product => {
- this.addAdvanceProduct(product);
- });
- this.invoiceForm.get('client').setValue(this.preinvoice.client);
- this.invoice.seller = this.preinvoice.seller;
- this.invoiceForm.get('invoice_type').setValue('3');
- this.invoiceForm.get('invoice_type').disable();
- }
- addAdvanceProduct = (product) => {
- this.products.push(this.createInvoiceProduct(product));
- this.calculateSummaries(this.products);
- this.invoiceForm.get('products').disable();
- }
- addProduct = (product = null) => {
- let newInvoiceProduct = {id: new Date().getTime(), name: '', count: 1, brutto: 0, vat: 0, total_netto: 0, total_brutto: 0, total_tax: 0};
- let foundProduct = this.searchProduct.value;
- if (product){
- foundProduct = product;
- }
- if(typeof foundProduct == 'string' ){
- if(foundProduct.length){
- newInvoiceProduct.name = foundProduct;
- }
- }
- if(typeof foundProduct == 'object'){
- newInvoiceProduct.name = this.productNameWithAttribute(foundProduct);
- newInvoiceProduct.vat = foundProduct.vat / 100;
- newInvoiceProduct.brutto = foundProduct.price
- newInvoiceProduct.total_brutto = this.calculateTotalBrutto(newInvoiceProduct.count, newInvoiceProduct.brutto );
- newInvoiceProduct.total_netto = this.calculateTotalNetto(1, newInvoiceProduct.brutto, newInvoiceProduct.vat );
- newInvoiceProduct.total_tax = this.calculateTotalTax(newInvoiceProduct.total_brutto, newInvoiceProduct.vat);
- }
- this.products.push(this.createInvoiceProduct(newInvoiceProduct));
- this.products.controls.forEach((control, index) => {
- control.get('brutto').valueChanges.subscribe((data)=> {
- control.get('total_brutto').setValue(this.calculateTotalBrutto(control.get('count').value, control.get('brutto').value));
- control.get('total_netto').setValue(this.calculateTotalNetto(control.get('count').value, control.get('brutto').value,control.get('vat').value));
- control.get('total_tax').setValue(this.calculateTotalTax(control.get('total_brutto').value,control.get('vat').value))
- this.calculateSummaries(this.products);
- })
- control.get('vat').valueChanges.subscribe((data)=> {
- control.get('total_brutto').setValue(this.calculateTotalBrutto(control.get('count').value, control.get('brutto').value));
- control.get('total_netto').setValue(this.calculateTotalNetto(control.get('count').value, control.get('brutto').value,control.get('vat').value));
- control.get('total_tax').setValue(this.calculateTotalTax(control.get('total_brutto').value,control.get('vat').value));
- this.calculateSummaries(this.products);
- })
- control.get('count').valueChanges.subscribe((data)=> {
- control.get('total_brutto').setValue(this.calculateTotalBrutto(control.get('count').value, control.get('brutto').value));
- control.get('total_netto').setValue(this.calculateTotalNetto(control.get('count').value, control.get('brutto').value,control.get('vat').value));
- control.get('total_tax').setValue(this.calculateTotalTax(control.get('total_brutto').value,control.get('vat').value))
- this.calculateSummaries(this.products);
- })
- })
- this.calculateSummaries(this.products);
- this.cleanProductSearch();
- }
- createInvoiceProduct(product : InvoiceProduct): FormGroup {
- let group = this._formBuilder.group({
- id: product.id || '',
- name: product.name || '',
- count: product.count || 0,
- brutto: product.brutto || 0,
- vat: product.vat || 0,
- total_netto: {value:product.total_netto || 0, disabled: true},
- total_brutto: {value: product.total_brutto || 0,disabled: true },
- total_tax: {value:product.total_tax || 0, disabled: true}
- })
- return group;
- }
- /**
- * On destroy
- */
- ngOnDestroy(): void
- {
- console.log('dESTROOOOOY');
- // Unsubscribe from all subscriptions
- this._unsubscribeAll.next();
- this._unsubscribeAll.complete();
- }
- compareState = (val1: number, val2: number) => {
- return val1 === val2;
- }
- clientDisplayWith(client?: Client): string | undefined {
- return client ? client.name : undefined;
- }
- productDisplayWith(product?): string | undefined {
- const name = product? product.name[0].text : undefined;
- const attr = product? product.attr_name[0].text || undefined : undefined;
- return name? name + (attr? ' ' + attr : '') : undefined;
- }
- openClientDialog() {
- const dialogRef = this.dialog.open(ClientComponent, {
- maxWidth: '80vw',
- });
- dialogRef.afterClosed().subscribe(result => {
- console.log(result);
- if(result){
- this.filteredClients.push(result)
- this.invoiceForm.get('client').setValue(result);
- }
- });
- }
- cleanProductSearch(){
- this.searchProduct.setValue('');
- this.searchedProducts = [];
- }
- removeProduct = (index) => {
- this.products.removeAt(index);
- this.calculateSummaries(this.products);
- }
- private _searchClients(text: string): void {
- console.log('searchiiiiiing');
- this.searching = true;
- const filterValue = text.toLowerCase();
- console.log(filterValue, 'filterValue')
- this._invoiceNewService.getClients(filterValue).then((clients: Client[]) => {
- console.log(clients, 'klients');
- this.searching = false;
- this.filteredClients = clients;
- return clients;
- });
- }
- //todo przenieść getProducts do modelu produktu
- private _searchProducts(text: string): void {
- console.log('searching product', text);
- this.searchingProduct = true;
- const filterValue = text.toLowerCase();
- console.log(filterValue, 'filterValue')
- this._invoiceNewService.getProducts(filterValue).then((products: any) => {
- this.searchingProduct = false;
- this.searchedProducts = products;
- console.log(this.searchedProducts, 'searchedProducts');
- return products;
- });
- }
- /**
- * Create product form
- *
- * @returns {FormGroup}
- */
- createForm(): FormGroup
- {
- let form = this._formBuilder.group({
- invoice_type : [this.invoice.invoice_type.toString()],
- client: [this.invoice.client],
- products: this._formBuilder.array([
- ]),
- creation_date: [this.invoice.creation_date],
- creation_place: [this.invoice.creation_place],
- execution_date: [this.invoice.execution_date],
- payment_type: [this.invoice.payment_type],
- payment_deadline: [this.invoice.payment_deadline],
- payment_brutto: [this.invoice.payment_brutto],
- payment_deadline_days: [this.invoice.payment_deadline_days],
- prefix: [this.invoice.prefix],
- number: [this.invoice.number],
- note: [this.invoice.note],
- searchProduct: [''],
- });
- return form;
- }
- productNameWithAttribute(product) : string | undefined{
- const name = product? product.name[0].text : undefined;
- const attr = product? product.attr_name[0].text || undefined : undefined;
- return name? name + (attr? ' ' + attr : '') : undefined;
- }
- //calculations
- //KP = WARTOŚĆ BRUTTO * SP / 100 + SP
- calculateTotalNetto(quantity, brutto, vat){
- const total_brutto = this.calculateTotalBrutto(quantity , brutto);
- const total_vat = this.calculateTotalTax(total_brutto, vat);
- return Math.round((total_brutto - total_vat) * 100) / 100
- }
- calculateTotalTax(total_brutto, vat){
- return Math.round((total_brutto * vat) / (100 + vat) * 100) / 100;
- }
- calculateTotalBrutto(quantity, brutto){
- return quantity * brutto;
- }
- calculateSummaryBrutto(products){
- return parseFloat(products.map(a => a.total_brutto).reduce((a,b) => a + b, 0).toFixed(2));
- }
- calculateSummaryNetto(products){
- return parseFloat(products.map(a=> a.total_netto).reduce((a,b) => a + b, 0).toFixed(2));
- }
- calculateSummaryTax(products){
- return parseFloat(products.map(product => product.total_brutto - product.total_netto).reduce((a,b) => a + b, 0).toFixed(2));
- }
- calculateSummaries(products){
- let vatSummaryBrutto = []
- console.log(products, 'wwa');
- products.getRawValue().forEach(product => {
- if(!vatSummaryBrutto.length){
- vatSummaryBrutto.push({vat: product.vat , sum: product.total_brutto});
- } else {
- let index= _.findIndex(vatSummaryBrutto, {'vat': product.vat});
- console.log(index, 'index');
- if (index >=0){
- vatSummaryBrutto[index].sum += product.total_brutto;
- } else {
- vatSummaryBrutto.push({vat: product.vat , sum: product.total_brutto});
- }
- }
- });
- let total_vat = 0;
- let total_netto = 0;
- let total_brutto = 0;
- let total_by_vat = [];
- console.log(total_vat, total_netto, total_brutto);
- vatSummaryBrutto.forEach(prod => {
- let vat = Math.round((prod.sum * prod.vat) / (100 + prod.vat) * 100) / 100;
- let netto = Math.round((prod.sum - vat) * 100) / 100
- console.log(vat, netto, 'vatnetto');
- total_vat += vat;
- total_netto += netto;
- total_brutto += prod.sum;
- total_by_vat.push({vat: prod.vat, netto: netto, brutto: prod.sum, tax: vat });
- });
- this.invoice.total_brutto = Math.round(total_brutto *100)/100;
- this.invoice.total_netto = Math.round(total_netto *100)/100;
- this.invoice.total_tax = Math.round(total_vat * 100)/100;
- this.invoice.total_by_vat = total_by_vat;
- this.invoice.outstanding_amount = this.calculateOutstandingAmount(this.invoice.total_brutto, this.invoiceForm.get('payment_brutto').value);
- }
- calculateOutstandingAmount(total, total_payment){
- let advancedTotal = 0;
- this.invoice.advanced_payments.forEach(advanced => {
- advancedTotal+=advanced.payment_brutto
- });
- console.log(Math.round((total-advancedTotal-total_payment)*100)/100, 'outstanding amount');
- return Math.round((total - advancedTotal - total_payment) * 100) / 100
- }
- /**
- * Add category
- */
- addInvoice(): void {
- let data = this.invoiceForm.getRawValue();
- console.log(data, 'dat ainvoice');
- console.log(this.invoice, 'invoice');
- //const oldValues = parsedClient;
- let newValues = {...this.invoice, ...data};
- newValues.execution_date = new Date(newValues.execution_date ).getTime();
- newValues.creation_date = new Date(newValues.creation_date ).getTime();
- newValues.invoice_type = parseInt(newValues.invoice_type);
- newValues.client.__typename = undefined;
- newValues.client.addressObj.__typename = undefined;
- newValues.seller.__typename = undefined;
- newValues.seller.addressObj.__typename = undefined;
- if(newValues.invoice_type == 3){
- newValues.payment_deadline = null;
- } else {
- newValues.payment_deadline = new Date(newValues.payment_deadline ).getTime();
- }
- console.log(newValues, 'new invoice');
- this._invoiceNewService.addInvoice(newValues)
- .then((d) => {
- // Trigger the subscription with new data
- this._invoiceNewService.onInvoiceChanged.next(d.data.createInvoice);
- // Show the success message
- this._matSnackBar.open('Faktura zapisana', 'OK', {
- verticalPosition: 'top',
- duration: 2000
- });
- // Change the location with new one
- this._location.go('apps/invoices/details/' + d.data.createInvoice.id);
- this.router.navigate(['/invoices/details/' + d.data.createInvoice.id]);
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement