Customer discount with prefill discount in sales.

This commit is contained in:
2021-04-02 14:34:07 +05:30
parent faf83f9356
commit 73850560aa
35 changed files with 690 additions and 48 deletions

View File

@ -110,6 +110,10 @@ const routes: Routes = [
loadChildren: () =>
import('./section-printers/section-printers.module').then((mod) => mod.SectionPrintersModule),
},
{
path: 'settings',
loadChildren: () => import('./settings/settings.module').then((mod) => mod.SettingsModule),
},
{
path: 'settle-options',
loadChildren: () =>

View File

@ -0,0 +1,12 @@
export class CustomerDiscount {
id: string;
name: string;
discount: number;
public constructor(init?: Partial<CustomerDiscount>) {
this.id = '';
this.name = '';
this.discount = 0;
Object.assign(this, init);
}
}

View File

@ -1,14 +1,18 @@
import { CustomerDiscount } from './customer-discount';
export class Customer {
id: string;
name: string;
phone: string;
address: string;
discounts: CustomerDiscount[];
public constructor(init?: Partial<Customer>) {
this.id = '';
this.name = '';
this.phone = '';
this.address = '';
this.discounts = [];
Object.assign(this, init);
}
}

View File

@ -38,9 +38,28 @@
>
<mat-form-field fxFlex>
<mat-label>Address</mat-label>
<input matInput placeholder="Address" formControlName="address" />
<textarea matInput placeholder="Address" formControlName="address"> </textarea>
</mat-form-field>
</div>
<mat-divider></mat-divider>
<div formArrayName="discounts">
<div
fxLayout="row"
*ngFor="let r of item.discounts; index as i"
[formGroupName]="i"
fxLayout="row"
fxLayoutAlign="space-around start"
fxLayout.lt-md="column"
fxLayoutGap="20px"
fxLayoutGap.lt-md="0px"
>
<mat-form-field fxFlex>
<mat-label>Discount on {{ r.name }}</mat-label>
<input matInput placeholder="Discount" formControlName="discount" />
<span matSuffix>%</span>
</mat-form-field>
</div>
</div>
</form>
</mat-card-content>
<mat-card-actions>

View File

@ -2,6 +2,7 @@ import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angula
import { AbstractControl, FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { round } from 'mathjs';
import { Customer } from '../../core/customer';
import { ToasterService } from '../../core/toaster.service';
@ -33,6 +34,7 @@ export class CustomerDetailComponent implements OnInit, AfterViewInit {
name: '',
phone: '',
address: '',
discounts: this.fb.array([]),
});
}
@ -48,6 +50,16 @@ export class CustomerDetailComponent implements OnInit, AfterViewInit {
(this.form.get('name') as AbstractControl).setValue(item.name);
(this.form.get('phone') as AbstractControl).setValue(item.phone);
(this.form.get('address') as AbstractControl).setValue(item.address);
this.form.setControl(
'discounts',
this.fb.array(
item.discounts.map((x) =>
this.fb.group({
discount: '' + x.discount * 100,
}),
),
),
);
}
ngAfterViewInit() {
@ -100,6 +112,13 @@ export class CustomerDetailComponent implements OnInit, AfterViewInit {
this.item.name = formModel.name;
this.item.phone = formModel.phone;
this.item.address = formModel.address;
const array = this.form.get('discounts') as FormArray;
this.item.discounts.forEach((item, index) => {
item.discount = Math.max(
Math.min(round(array.controls[index].value.discount / 100, 5), 100),
0,
);
});
return this.item;
}
}

View File

@ -0,0 +1,18 @@
import { inject, TestBed } from '@angular/core/testing';
import { CustomerDiscountsService } from './customer-discounts.service';
describe('CustomerDiscountsService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [CustomerDiscountsService],
});
});
it('should be created', inject(
[CustomerDiscountsService],
(service: CustomerDiscountsService) => {
expect(service).toBeTruthy();
},
));
});

View File

@ -0,0 +1,37 @@
import { HttpClient, HttpHeaders } 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 { DiscountItem } from '../sales/discount/discount-item';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
};
const url = '/api/customer-discounts';
const serviceName = 'CustomerService';
@Injectable({
providedIn: 'root',
})
export class CustomerDiscountsService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
list(id: string | undefined): Observable<DiscountItem[]> {
const getUrl: string = id === undefined ? `${url}` : `${url}/${id}`;
return this.http
.get<DiscountItem[]>(getUrl)
.pipe(catchError(this.log.handleError(serviceName, `get id=${id}`))) as Observable<
DiscountItem[]
>;
}
listForDiscount(): Observable<{ name: string; discount: number; discountLimit: number }[]> {
return this.http
.get<{ name: string; discount: number; discountLimit: number }[]>(`${url}/for-discount`)
.pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable<
{ name: string; discount: number; discountLimit: number }[]
>;
}
}

View File

@ -28,6 +28,18 @@
<mat-cell *matCellDef="let row">{{ row.address }}</mat-cell>
</ng-container>
<!-- Discounts Column -->
<ng-container matColumnDef="discounts">
<mat-header-cell *matHeaderCellDef>Discounts</mat-header-cell>
<mat-cell *matCellDef="let row">
<ul>
<li *ngFor="let discount of row.discounts">
{{ discount.name }} - {{ discount.discount | percent: '1.2-2' }}
</li>
</ul>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

View File

@ -14,7 +14,7 @@ export class CustomerListComponent implements OnInit {
dataSource: CustomerListDatasource = new CustomerListDatasource([]);
list: Customer[] = [];
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['name', 'phone', 'address'];
displayedColumns = ['name', 'phone', 'address', 'discounts'];
constructor(private route: ActivatedRoute) {}

View File

@ -250,6 +250,15 @@
>
<h3 class="item-name">Settle Options</h3>
</mat-card>
<mat-card
fxLayout="column"
class="square-button"
matRipple
*ngIf="auth.allowed('settings')"
[routerLink]="['/', 'settings']"
>
<h3 class="item-name">Settings</h3>
</mat-card>
</div>
<footer class="footer">
<p>Backend: v{{ auth.user?.ver }} / Frontend: v{{ version }} on {{ auth.device.name }}</p>

View File

@ -33,14 +33,6 @@ export class SaleCategoryService {
.pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable<SaleCategory[]>;
}
listForDiscount(): Observable<{ name: string; discount: number; discountLimit: number }[]> {
return this.http
.get<{ name: string; discount: number; discountLimit: number }[]>(`${url}/for-discount`)
.pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable<
{ name: string; discount: number; discountLimit: number }[]
>;
}
save(saleCategory: SaleCategory): Observable<SaleCategory> {
return this.http
.post<SaleCategory>(url, saleCategory, httpOptions)

View File

@ -0,0 +1,16 @@
export class DiscountItem {
id: string;
name: string;
discount: number;
discountLimit: number;
customerDiscount: number;
public constructor(init?: Partial<DiscountItem>) {
this.id = '';
this.name = '';
this.discount = 0;
this.discountLimit = 0;
this.customerDiscount = 0;
Object.assign(this, init);
}
}

View File

@ -12,9 +12,11 @@
<ng-container matColumnDef="discount">
<mat-header-cell *matHeaderCellDef class="center" fxFlex>Discount</mat-header-cell>
<mat-cell *matCellDef="let row; let i = index" class="center" [formGroupName]="i" fxFlex>
<mat-form-field>
<mat-form-field fxFlex="100%">
<input matInput type="number" formControlName="discount" autocomplete="off" />
<mat-hint>Maximum Discount {{ row.discountLimit | percent: '1.2-2' }}</mat-hint>
<span matSuffix>%</span>
<mat-hint>Cust: {{ row.customerDiscount | percent: '1.2-2' }}</mat-hint>
<mat-hint align="end">Max: {{ row.discountLimit | percent: '1.2-2' }}</mat-hint>
</mat-form-field>
</mat-cell>
</ng-container>

View File

@ -5,6 +5,7 @@ import { round } from 'mathjs';
import { Observable } from 'rxjs';
import { DiscountDataSource } from './discount-datasource';
import { DiscountItem } from './discount-item';
@Component({
selector: 'app-modifiers',
@ -12,7 +13,7 @@ import { DiscountDataSource } from './discount-datasource';
styleUrls: ['./discount.component.css'],
})
export class DiscountComponent {
list: { name: string; discount: number; discountLimit: number }[] = [];
list: DiscountItem[] = [];
form: FormGroup;
dataSource: DiscountDataSource = new DiscountDataSource([]);
@ -22,12 +23,12 @@ export class DiscountComponent {
public dialogRef: MatDialogRef<DiscountComponent>,
private fb: FormBuilder,
@Inject(MAT_DIALOG_DATA)
public data: Observable<{ name: string; discount: number; discountLimit: number }[]>,
public data: Observable<DiscountItem[]>,
) {
this.form = this.fb.group({
discounts: '',
});
this.data.subscribe((list: { name: string; discount: number; discountLimit: number }[]) => {
this.data.subscribe((list: DiscountItem[]) => {
this.list = list;
this.form.setControl(
'discounts',
@ -35,12 +36,15 @@ export class DiscountComponent {
this.list.map((x) =>
this.fb.group({
name: [x.name],
discount: ['', [Validators.min(0), Validators.max(x.discountLimit * 100)]],
discount: [
'' + (x.discount !== 0 ? x.discount * 100 : ''),
[Validators.min(0), Validators.max(x.discountLimit * 100)],
],
}),
),
),
);
this.dataSource = new DiscountDataSource(list);
this.dataSource = new DiscountDataSource(this.list);
});
}
@ -49,13 +53,15 @@ export class DiscountComponent {
for (let i = this.list.length - 1; i >= 0; i--) {
const item = this.list[i];
const control = (array.controls[i] as FormGroup).controls.discount as FormControl;
if (control.pristine || control.value === null) {
console.log(item.name, control.value, typeof control.value);
if (
control.value === null ||
control.value === '' ||
(control.pristine && control.value === '0')
) {
this.list.splice(i, 1);
} else {
item.discount = Math.max(
Math.min(round(array.controls[i].value.discount / 100, 5), item.discountLimit),
0,
);
item.discount = Math.max(Math.min(round(control.value / 100, 5), item.discountLimit), 0);
}
}
this.dialogRef.close(this.list);

View File

@ -8,6 +8,7 @@ import { AuthService } from '../../auth/auth.service';
import { ReceivePaymentItem } from '../../core/receive-payment-item';
import { Table } from '../../core/table';
import { ToasterService } from '../../core/toaster.service';
import { CustomerDiscountsService } from '../../customers/customer-discounts.service';
import { SaleCategoryService } from '../../sale-category/sale-category.service';
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
import { TableService } from '../../tables/table.service';
@ -33,8 +34,9 @@ export class SalesHomeComponent {
private dialog: MatDialog,
private auth: AuthService,
private toaster: ToasterService,
private mcSer: SaleCategoryService,
private tSer: TableService,
private saleCategoryService: SaleCategoryService,
private tableService: TableService,
private customerDiscountsService: CustomerDiscountsService,
private bs: BillService,
) {}
@ -78,7 +80,7 @@ export class SalesHomeComponent {
if (this.discountAllowed()) {
const dialogRef = this.dialog.open(DiscountComponent, {
// width: '750px',
data: this.mcSer.listForDiscount(),
data: this.customerDiscountsService.list(this.bs.bill.customer?.id),
});
return dialogRef.afterClosed();
}
@ -338,7 +340,7 @@ export class SalesHomeComponent {
> {
return this.dialog
.open(SplitBillComponent, {
data: this.mcSer
data: this.saleCategoryService
.list()
.pipe(map((x) => x.map((y) => ({ id: y.id, name: y.name, selected: false })))),
})
@ -350,7 +352,7 @@ export class SalesHomeComponent {
.open(TablesDialogComponent, {
// width: '750px',
data: {
list: this.tSer.running(),
list: this.tableService.running(),
canChooseRunning,
},
})

View File

@ -0,0 +1,16 @@
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs/internal/Observable';
import { SettingsService } from './settings.service';
@Injectable({
providedIn: 'root',
})
export class PrefillCustomerDiscountResolver implements Resolve<boolean> {
constructor(private ser: SettingsService) {}
resolve(): Observable<boolean> {
return this.ser.getPrefillCustomerDiscount();
}
}

View File

@ -0,0 +1,29 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from '../auth/auth-guard.service';
import { PrefillCustomerDiscountResolver } from './prefill-customer-discount-resolver.service';
import { SettingsComponent } from './settings.component';
const settingsRoutes: Routes = [
{
path: '',
component: SettingsComponent,
canActivate: [AuthGuard],
data: {
permission: 'Settings',
},
resolve: {
prefillCustomerDiscount: PrefillCustomerDiscountResolver,
},
runGuardsAndResolvers: 'always',
},
];
@NgModule({
imports: [CommonModule, RouterModule.forChild(settingsRoutes)],
exports: [RouterModule],
})
export class SettingsRoutingModule {}

View File

@ -0,0 +1,32 @@
.right {
display: flex;
justify-content: flex-end;
}
.selected {
background: #fff3cd;
}
.unposted {
background: #f8d7da;
}
.center {
display: flex;
justify-content: center;
}
.img-container {
position: relative;
}
.img-container .overlay {
display: none;
}
.img-container:hover > .overlay {
display: inline-block;
position: absolute;
left: 60px;
top: 0;
}

View File

@ -0,0 +1,18 @@
<mat-tab-group>
<mat-tab label="Prefill Customer Discount">
<mat-card>
<mat-card-content>
<mat-slide-toggle
(click)="togglePrefill()"
fxFlex="100"
[checked]="prefillCustomerDiscount"
>
Prefill the customer discount
</mat-slide-toggle>
</mat-card-content>
</mat-card>
</mat-tab>
</mat-tab-group>
<footer class="footer">
<p>Backend: v{{ auth.user?.ver }} / Frontend: v{{ version }}</p>
</footer>

View File

@ -0,0 +1,50 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { environment } from '../../environments/environment';
import { AuthService } from '../auth/auth.service';
import { ToasterService } from '../core/toaster.service';
import { SettingsService } from './settings.service';
@Component({
selector: 'app-settings',
templateUrl: './settings.component.html',
styleUrls: ['./settings.component.css'],
})
export class SettingsComponent implements OnInit {
prefillCustomerDiscount = true;
version: string;
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private dialog: MatDialog,
private toaster: ToasterService,
public auth: AuthService,
private ser: SettingsService,
) {
this.version = environment.version;
}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as {
prefillCustomerDiscount: boolean;
};
this.prefillCustomerDiscount = data.prefillCustomerDiscount;
});
}
togglePrefill() {
this.ser.setPrefillCustomerDiscount(!this.prefillCustomerDiscount).subscribe((x) => {
this.prefillCustomerDiscount = x;
});
}
}

View File

@ -0,0 +1,81 @@
import { A11yModule } from '@angular/cdk/a11y';
import { CdkTableModule } from '@angular/cdk/table';
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FlexLayoutModule } from '@angular/flex-layout';
import { ReactiveFormsModule } from '@angular/forms';
import { MomentDateAdapter } from '@angular/material-moment-adapter';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import {
DateAdapter,
MAT_DATE_FORMATS,
MAT_DATE_LOCALE,
MatNativeDateModule,
} from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatSlideToggle, MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { SharedModule } from '../shared/shared.module';
import { SettingsRoutingModule } from './settings-routing.module';
import { SettingsComponent } from './settings.component';
export const MY_FORMATS = {
parse: {
dateInput: 'DD-MMM-YYYY',
},
display: {
dateInput: 'DD-MMM-YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'DD-MMM-YYYY',
monthYearA11yLabel: 'MMM YYYY',
},
};
@NgModule({
imports: [
A11yModule,
CommonModule,
CdkTableModule,
FlexLayoutModule,
MatAutocompleteModule,
MatButtonModule,
MatCardModule,
MatCheckboxModule,
MatDatepickerModule,
MatDialogModule,
MatSlideToggleModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatSelectModule,
MatSortModule,
MatTableModule,
MatTabsModule,
ReactiveFormsModule,
SharedModule,
SettingsRoutingModule,
],
declarations: [SettingsComponent],
providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
],
})
export class SettingsModule {}

View File

@ -0,0 +1,31 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import { catchError, map } from 'rxjs/operators';
import { ErrorLoggerService } from '../core/error-logger.service';
const serviceName = 'SettingsService';
@Injectable({ providedIn: 'root' })
export class SettingsService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
getPrefillCustomerDiscount(): Observable<boolean> {
const url = '/api/settings/prefill-customer-discount';
return this.http.get<{ value: boolean }>(url).pipe(
map((x) => x.value),
catchError(this.log.handleError(serviceName, 'getPrefillCustomerDiscount')),
) as Observable<boolean>;
}
setPrefillCustomerDiscount(value: boolean): Observable<boolean> {
const url = '/api/settings/prefill-customer-discount';
return this.http
.post<{ value: boolean }>(url, { value: value })
.pipe(
map((x) => x.value),
catchError(this.log.handleError(serviceName, 'setPrefillCustomerDiscount')),
) as Observable<boolean>;
}
}

View File

@ -64,9 +64,7 @@ export class UserDetailComponent implements OnInit, AfterViewInit {
ngAfterViewInit() {
setTimeout(() => {
if (this.nameElement !== undefined) {
if (this.nameElement !== undefined) {
this.nameElement.nativeElement.focus();
}
this.nameElement.nativeElement.focus();
}
}, 0);
}