Feature: Mozimo Product Register

This commit is contained in:
2024-08-16 10:23:50 +05:30
parent bd0ee4facd
commit 3b46ac97bc
20 changed files with 1107 additions and 0 deletions

View File

@ -89,6 +89,10 @@ export const routes: Routes = [
path: 'ledger',
loadChildren: () => import('./ledger/ledger.routes').then((mod) => mod.routes),
},
{
path: 'mozimo-product-register',
loadChildren: () => import('./mozimo-product-register/mozimo-product-register.routes').then((mod) => mod.routes),
},
{
path: 'net-transactions',
loadChildren: () => import('./net-transactions/net-transactions.routes').then((mod) => mod.routes),

View File

@ -35,6 +35,7 @@
<a mat-menu-item routerLink="/rate-contracts">Rate Contracts</a>
<a mat-menu-item routerLink="/batch-integrity-report">Batch Integrity</a>
<a mat-menu-item routerLink="/non-contract-purchase">Non Contract Purchases</a>
<a mat-menu-item routerLink="/mozimo-product-register">Mozimo Product Register</a>
</mat-menu>
<button mat-button [matMenuTriggerFor]="productReportMenu">Product Reports</button>

View File

@ -0,0 +1,66 @@
import { DataSource } from '@angular/cdk/collections';
import { EventEmitter } from '@angular/core';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { merge, Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { MozimoProductRegisterItem } from './mozimo-product-register-item';
export class MozimoProductRegisterDataSource extends DataSource<MozimoProductRegisterItem> {
public data: MozimoProductRegisterItem[] = [];
public paginator?: MatPaginator;
constructor(public dataObs: Observable<MozimoProductRegisterItem[]>) {
super();
}
connect(): Observable<MozimoProductRegisterItem[]> {
const dataMutations: EventEmitter<PageEvent>[] = [];
const d = this.dataObs.pipe(
tap((x) => {
this.data = x;
}),
);
if (this.paginator) {
dataMutations.push((this.paginator as MatPaginator).page);
}
return merge(d, ...dataMutations).pipe(
map(() => this.calculate([...this.data])),
tap(() => {
if (this.paginator) {
this.paginator.length = this.data.length;
}
}),
map((x: MozimoProductRegisterItem[]) => this.getPagedData(x)),
);
}
disconnect() {}
private calculate(data: MozimoProductRegisterItem[]): MozimoProductRegisterItem[] {
if (data.length === 0) {
return data;
}
let ob = data[0].opening;
data.forEach((item) => {
item.opening = ob;
if (item.ageing !== null || item.display !== null) {
item.closing = (item.ageing ?? 0) + (item.display ?? 0);
item.variance = item.opening + item.received - item.sale - item.nc - item.closing;
} else {
item.closing = item.opening + item.received - item.sale - item.nc;
item.variance = 0;
}
ob = item.closing;
});
return data;
}
private getPagedData(data: MozimoProductRegisterItem[]) {
if (this.paginator === undefined) {
return data;
}
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
}

View File

@ -0,0 +1,28 @@
export class MozimoProductRegisterItem {
id: string | null;
date: string;
opening: number;
received: number;
sale: number;
nc: number;
display: number | null;
ageing: number | null;
variance: number | null;
closing: number;
lastEditDate: string | null;
public constructor(init?: Partial<MozimoProductRegisterItem>) {
this.id = null;
this.date = '';
this.opening = 0;
this.received = 0;
this.sale = 0;
this.nc = 0;
this.display = null;
this.ageing = null;
this.variance = null;
this.closing = 0;
this.lastEditDate = null;
Object.assign(this, init);
}
}

View File

@ -0,0 +1,17 @@
.right {
display: flex;
justify-content: flex-end;
}
.first {
margin-right: 4px;
}
.middle {
margin-left: 4px;
margin-right: 4px;
}
.last {
margin-left: 4px;
}

View File

@ -0,0 +1,164 @@
<mat-card>
<mat-card-header>
<mat-card-title-group>
<mat-card-title>Mozimo Product Register</mat-card-title>
@if (dataSource.data.length) {
<button mat-icon-button (click)="exportCsv()">
<mat-icon>save_alt</mat-icon>
</button>
}
</mat-card-title-group>
</mat-card-header>
<mat-card-content>
<form [formGroup]="form" class="flex flex-col">
<div class="flex flex-row justify-around content-start items-start sm:max-lg:flex-col">
<mat-form-field class="flex-auto mr-5">
<mat-label>Start Date</mat-label>
<input
matInput
#startDateElement
[matDatepicker]="startDate"
formControlName="startDate"
autocomplete="off"
/>
<mat-datepicker-toggle matSuffix [for]="startDate"></mat-datepicker-toggle>
<mat-datepicker #startDate></mat-datepicker>
</mat-form-field>
<mat-form-field class="flex-auto">
<mat-label>Finish Date</mat-label>
<input matInput [matDatepicker]="finishDate" formControlName="finishDate" autocomplete="off" />
<mat-datepicker-toggle matSuffix [for]="finishDate"></mat-datepicker-toggle>
<mat-datepicker #finishDate></mat-datepicker>
</mat-form-field>
</div>
<div class="flex flex-row justify-around content-start items-start sm:max-lg:flex-col">
<mat-form-field class="flex-auto basis-4/5 mr-5">
<mat-label>Product</mat-label>
<input
type="text"
matInput
#productElement
[matAutocomplete]="auto"
formControlName="product"
autocomplete="off"
/>
<mat-autocomplete
#auto="matAutocomplete"
autoActiveFirstOption
[displayWith]="displayFn"
(optionSelected)="selected($event)"
>
@for (product of products | async; track product) {
<mat-option [value]="product">{{ product.name }}</mat-option>
}
</mat-autocomplete>
</mat-form-field>
<button mat-raised-button class="flex-auto basis-1/5" color="primary" (click)="show()">Show</button>
</div>
<mat-table #table [dataSource]="dataSource" aria-label="Elements" formArrayName="items">
<!-- Date Column -->
<ng-container matColumnDef="date">
<mat-header-cell *matHeaderCellDef class="center first">Date</mat-header-cell>
<mat-cell *matCellDef="let row" class="center first">
<span
matBadge="1"
matBadgeSize="small"
[matBadgeHidden]="!row.lastEditDate"
matTooltip="{{ row.lastEditDate | localTime }}"
[matTooltipDisabled]="!row.lastEditDate"
>{{ row.date }}</span
>
</mat-cell>
</ng-container>
<!-- Opening Column -->
<ng-container matColumnDef="opening">
<mat-header-cell *matHeaderCellDef class="right middle">Opening</mat-header-cell>
<mat-cell *matCellDef="let row" class="right middle">{{ row.opening | number: '0.2-2' }}</mat-cell>
</ng-container>
<!-- Received Column -->
<ng-container matColumnDef="received">
<mat-header-cell *matHeaderCellDef class="middle">Received</mat-header-cell>
<mat-cell *matCellDef="let row; let i = index" [formGroupName]="i" class="middle">
<mat-form-field class="flex-auto">
<mat-label>Received</mat-label>
<input matInput type="number" formControlName="received" (change)="updateReceived($event, row)" />
</mat-form-field>
</mat-cell>
</ng-container>
<!-- Sale Column -->
<ng-container matColumnDef="sale">
<mat-header-cell *matHeaderCellDef class="middle">Sale</mat-header-cell>
<mat-cell *matCellDef="let row; let i = index" [formGroupName]="i" class="middle">
<mat-form-field class="flex-auto">
<mat-label>Sale</mat-label>
<input matInput type="number" formControlName="sale" (change)="updateSale($event, row)" />
</mat-form-field>
</mat-cell>
</ng-container>
<!-- Nc Column -->
<ng-container matColumnDef="nc">
<mat-header-cell *matHeaderCellDef class="middle">Nc</mat-header-cell>
<mat-cell *matCellDef="let row; let i = index" [formGroupName]="i" class="middle">
<mat-form-field class="flex-auto">
<mat-label>Nc</mat-label>
<input matInput type="number" formControlName="nc" (change)="updateNc($event, row)" />
</mat-form-field>
</mat-cell>
</ng-container>
<!-- Display Column -->
<ng-container matColumnDef="display">
<mat-header-cell *matHeaderCellDef class="middle">Display</mat-header-cell>
<mat-cell *matCellDef="let row; let i = index" [formGroupName]="i" class="middle">
<mat-form-field class="flex-auto">
<mat-label>Display</mat-label>
<input matInput type="number" formControlName="display" (change)="updateDisplay($event, row)" />
</mat-form-field>
</mat-cell>
</ng-container>
<!-- Ageing Column -->
<ng-container matColumnDef="ageing">
<mat-header-cell *matHeaderCellDef class="middle">Ageing</mat-header-cell>
<mat-cell *matCellDef="let row; let i = index" [formGroupName]="i" class="middle">
<mat-form-field class="flex-auto">
<mat-label>Ageing</mat-label>
<input matInput type="number" formControlName="ageing" (change)="updateAgeing($event, row)" />
</mat-form-field>
</mat-cell>
</ng-container>
<!-- Variance Column -->
<ng-container matColumnDef="variance">
<mat-header-cell *matHeaderCellDef class="right middle">Variance</mat-header-cell>
<mat-cell *matCellDef="let row" class="right middle">{{ row.variance | number: '0.2-2' }}</mat-cell>
</ng-container>
<!-- Closing Column -->
<ng-container matColumnDef="closing">
<mat-header-cell *matHeaderCellDef class="right last">Closing</mat-header-cell>
<mat-cell *matCellDef="let row" class="right last">{{ row.closing | number: '0.2-2' }}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
<mat-paginator
#paginator
[length]="dataSource.data.length"
[pageIndex]="0"
[pageSize]="50"
[pageSizeOptions]="[25, 50, 100, 250, 300, 5000]"
>
</mat-paginator>
</form>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" (click)="save()" [disabled]="form.pristine">Save</button>
</mat-card-actions>
</mat-card>

View File

@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MozimoProductRegisterComponent } from './mozimo-product-register.component';
describe('MozimoProductRegisterComponent', () => {
let component: MozimoProductRegisterComponent;
let fixture: ComponentFixture<MozimoProductRegisterComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [MozimoProductRegisterComponent],
}).compileComponents();
fixture = TestBed.createComponent(MozimoProductRegisterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,250 @@
import { DecimalPipe, CurrencyPipe, AsyncPipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormArray, FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialog } from '@angular/material/dialog';
import { MatBadgeModule } from '@angular/material/badge';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatPaginator, MatPaginatorModule } from '@angular/material/paginator';
import { MatTableModule } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import moment from 'moment';
import { AuthService } from '../auth/auth.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ToCsvService } from '../shared/to-csv.service';
import { MozimoProductRegister } from './mozimo-product-register';
import { MozimoProductRegisterDataSource } from './mozimo-product-register-datasource';
import { MozimoProductRegisterItem } from './mozimo-product-register-item';
import { MozimoProductRegisterService } from './mozimo-product-register.service';
import { MatAutocompleteModule, MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { Product } from '../core/product';
import { debounceTime, distinctUntilChanged, Observable, switchMap, of as observableOf, BehaviorSubject } from 'rxjs';
import { ProductSku } from '../core/product-sku';
import { ProductService } from '../product/product.service';
import { LocalTimePipe } from '../shared/local-time.pipe';
import { MatTooltipModule } from '@angular/material/tooltip';
@Component({
selector: 'app-mozimo-product-register',
templateUrl: './mozimo-product-register.component.html',
styleUrls: ['./mozimo-product-register.component.css'],
standalone: true,
imports: [
AsyncPipe,
CurrencyPipe,
DecimalPipe,
LocalTimePipe,
MatAutocompleteModule,
MatBadgeModule,
MatButtonModule,
MatCardModule,
MatDatepickerModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatPaginatorModule,
MatTableModule,
MatTooltipModule,
ReactiveFormsModule,
],
})
export class MozimoProductRegisterComponent implements OnInit {
@ViewChild(MatPaginator, { static: true }) paginator!: MatPaginator;
info: MozimoProductRegister = new MozimoProductRegister();
body = new BehaviorSubject<MozimoProductRegisterItem[]>([]);
dataSource: MozimoProductRegisterDataSource = new MozimoProductRegisterDataSource(this.body);
form: FormGroup<{
startDate: FormControl<Date>;
finishDate: FormControl<Date>;
product: FormControl<string | null>;
items: FormArray<
FormGroup<{
received: FormControl<number>;
sale: FormControl<number>;
nc: FormControl<number>;
display: FormControl<number | null>;
ageing: FormControl<number | null>;
}>
>;
}>;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['date', 'opening', 'received', 'sale', 'nc', 'display', 'ageing', 'variance', 'closing'];
products: Observable<ProductSku[]>;
constructor(
private route: ActivatedRoute,
private router: Router,
private toCsv: ToCsvService,
private dialog: MatDialog,
private snackBar: MatSnackBar,
public auth: AuthService,
private ser: MozimoProductRegisterService,
private productSer: ProductService,
) {
this.form = new FormGroup({
startDate: new FormControl(new Date(), { nonNullable: true }),
finishDate: new FormControl(new Date(), { nonNullable: true }),
product: new FormControl<string | null>(null),
items: new FormArray<
FormGroup<{
received: FormControl<number>;
sale: FormControl<number>;
nc: FormControl<number>;
display: FormControl<number | null>;
ageing: FormControl<number | null>;
}>
>([]),
});
this.products = this.form.controls.product.valueChanges.pipe(
debounceTime(150),
distinctUntilChanged(),
switchMap((x) => (x === null ? observableOf([]) : this.productSer.autocompleteSku(x, null))),
);
}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { info: MozimoProductRegister };
this.info = data.info;
this.form.patchValue({
product: this.info.product?.name ?? '',
startDate: moment(this.info.startDate, 'DD-MMM-YYYY').toDate(),
finishDate: moment(this.info.finishDate, 'DD-MMM-YYYY').toDate(),
});
this.form.controls.items.clear();
this.info.body.forEach((x) =>
this.form.controls.items.push(
new FormGroup({
received: new FormControl(x.received, { nonNullable: true, validators: [Validators.min(0)] }),
sale: new FormControl(x.sale, { nonNullable: true, validators: [Validators.min(0)] }),
nc: new FormControl(x.nc, { nonNullable: true, validators: [Validators.min(0)] }),
display: new FormControl(x.display, { nonNullable: false, validators: [Validators.min(0)] }),
ageing: new FormControl(x.ageing, { nonNullable: false, validators: [Validators.min(0)] }),
}),
),
);
if (!this.dataSource.paginator) {
this.dataSource.paginator = this.paginator;
}
this.body.next(this.info.body);
});
}
displayFn(product?: Product | string): string {
return !product ? '' : typeof product === 'string' ? product : product.name;
}
selected(event: MatAutocompleteSelectedEvent): void {
this.info.product = event.option.value;
}
show() {
const info = this.getInfo();
if (info.product) {
this.router.navigate(['mozimo-product-register', info.product.id], {
queryParams: {
startDate: info.startDate,
finishDate: info.finishDate,
},
});
}
}
save() {
this.ser.save(this.getMozimoProductRegister()).subscribe({
next: () => {
this.snackBar.open('', 'Success');
},
error: (error) => {
this.snackBar.open(error, 'Danger');
},
});
}
getMozimoProductRegister(): MozimoProductRegister {
const formModel = this.form.value;
this.info.startDate = moment(formModel.startDate).format('DD-MMM-YYYY');
this.info.finishDate = moment(formModel.finishDate).format('DD-MMM-YYYY');
const array = this.form.controls.items;
this.info.body.forEach((item, index) => {
item.received = +(array.controls[index].value.received ?? 0);
item.sale = +(array.controls[index].value.sale ?? 0);
item.nc = +(array.controls[index].value.nc ?? 0);
const display = array.controls[index].value.display ?? null;
const ageing = array.controls[index].value.ageing ?? null;
item.display = display == null ? null : +display;
item.ageing = ageing == null ? null : +ageing;
});
return this.info;
}
getInfo(): MozimoProductRegister {
const formModel = this.form.value;
return new MozimoProductRegister({
product: this.info.product,
startDate: moment(formModel.startDate).format('DD-MMM-YYYY'),
finishDate: moment(formModel.finishDate).format('DD-MMM-YYYY'),
});
}
exportCsv() {
const headers = {
Date: 'date',
Opening: 'opening',
Received: 'received',
Sale: 'sale',
};
const d = JSON.parse(JSON.stringify(this.dataSource.data)).map((x: MozimoProductRegisterItem) => ({
x,
}));
const csvData = new Blob([this.toCsv.toCsv(headers, d)], {
type: 'text/csv;charset=utf-8;',
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(csvData);
link.setAttribute('download', 'mozimo-product-register.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
updateReceived($event: Event, row: MozimoProductRegisterItem) {
row.received = +($event.target as HTMLInputElement).value;
this.body.next(this.info.body);
}
updateSale($event: Event, row: MozimoProductRegisterItem) {
row.sale = +($event.target as HTMLInputElement).value;
this.body.next(this.info.body);
}
updateNc($event: Event, row: MozimoProductRegisterItem) {
row.nc = +($event.target as HTMLInputElement).value;
this.body.next(this.info.body);
}
updateDisplay($event: Event, row: MozimoProductRegisterItem) {
const val = ($event.target as HTMLInputElement).value;
row.display = val === '' ? null : +val;
this.body.next(this.info.body);
}
updateAgeing($event: Event, row: MozimoProductRegisterItem) {
const val = ($event.target as HTMLInputElement).value;
row.ageing = val === '' ? null : +val;
this.body.next(this.info.body);
}
}

View File

@ -0,0 +1,18 @@
import { TestBed } from '@angular/core/testing';
import { ResolveFn } from '@angular/router';
import { MozimoProductRegister } from './mozimo-product-register';
import { mozimoProductRegisterResolver } from './mozimo-product-register.resolver';
describe('mozimoProductRegisterResolver', () => {
const executeResolver: ResolveFn<MozimoProductRegister> = (...resolverParameters) =>
TestBed.runInInjectionContext(() => mozimoProductRegisterResolver(...resolverParameters));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it('should be created', () => {
expect(executeResolver).toBeTruthy();
});
});

View File

@ -0,0 +1,12 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { MozimoProductRegister } from './mozimo-product-register';
import { MozimoProductRegisterService } from './mozimo-product-register.service';
export const mozimoProductRegisterResolver: ResolveFn<MozimoProductRegister> = (route) => {
const id = route.paramMap.get('id');
const startDate = route.queryParamMap.get('startDate') || null;
const finishDate = route.queryParamMap.get('finishDate') || null;
return inject(MozimoProductRegisterService).list(id, startDate, finishDate);
};

View File

@ -0,0 +1,34 @@
import { Routes } from '@angular/router';
import { authGuard } from '../auth/auth-guard.service';
import { MozimoProductRegisterComponent } from './mozimo-product-register.component';
import { mozimoProductRegisterResolver } from './mozimo-product-register.resolver';
export const routes: Routes = [
{
path: '',
component: MozimoProductRegisterComponent,
canActivate: [authGuard],
data: {
permission: 'Ledger',
},
resolve: {
info: mozimoProductRegisterResolver,
},
runGuardsAndResolvers: 'always',
},
{
path: ':id',
component: MozimoProductRegisterComponent,
canActivate: [authGuard],
data: {
// permission: 'Mozimo Product Register',
permission: 'Ledger',
},
resolve: {
info: mozimoProductRegisterResolver,
},
runGuardsAndResolvers: 'always',
},
];

View File

@ -0,0 +1,17 @@
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { inject, TestBed } from '@angular/core/testing';
import { MozimoProductRegisterService } from './mozimo-product-register.service';
describe('MozimoProductRegisterService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
providers: [MozimoProductRegisterService, provideHttpClient(withInterceptorsFromDi())],
});
});
it('should be created', inject([MozimoProductRegisterService], (service: MozimoProductRegisterService) => {
expect(service).toBeTruthy();
}));
});

View File

@ -0,0 +1,55 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import { catchError } from 'rxjs/operators';
import { ErrorLoggerService } from '../core/error-logger.service';
import { MozimoProductRegister } from './mozimo-product-register';
const url = '/api/mozimo-product-register';
const serviceName = 'MozimoProductRegisterService';
@Injectable({
providedIn: 'root',
})
export class MozimoProductRegisterService {
constructor(
private http: HttpClient,
private log: ErrorLoggerService,
) {}
list(id: string | null, startDate: string | null, finishDate: string | null): Observable<MozimoProductRegister> {
const listUrl = id === null ? url : `${url}/${id}`;
const options = { params: new HttpParams() };
if (startDate !== null) {
options.params = options.params.set('s', startDate);
}
if (finishDate !== null) {
options.params = options.params.set('f', finishDate);
}
return this.http
.get<MozimoProductRegister>(listUrl, options)
.pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable<MozimoProductRegister>;
}
save(mozimoProductRegister: MozimoProductRegister): Observable<MozimoProductRegister> {
return this.http
.post<MozimoProductRegister>(url, mozimoProductRegister)
.pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable<MozimoProductRegister>;
}
post(date: string, costCentre: string): Observable<MozimoProductRegister> {
const options = { params: new HttpParams().set('d', costCentre) };
return this.http
.post<MozimoProductRegister>(`${url}/${date}`, {}, options)
.pipe(catchError(this.log.handleError(serviceName, 'Post Voucher'))) as Observable<MozimoProductRegister>;
}
delete(date: string, costCentre: string): Observable<MozimoProductRegister> {
const options = { params: new HttpParams().set('d', costCentre) };
return this.http
.delete<MozimoProductRegister>(`${url}/${date}`, options)
.pipe(catchError(this.log.handleError(serviceName, 'Delete Voucher'))) as Observable<MozimoProductRegister>;
}
}

View File

@ -0,0 +1,18 @@
import { Product } from '../core/product';
import { MozimoProductRegisterItem } from './mozimo-product-register-item';
export class MozimoProductRegister {
startDate: string;
finishDate: string;
product: Product;
body: MozimoProductRegisterItem[];
public constructor(init?: Partial<MozimoProductRegister>) {
this.startDate = '';
this.finishDate = '';
this.product = new Product();
this.body = [];
Object.assign(this, init);
}
}