Feature: Added the customer module to list / edit customers. This is needed to add the customer discount functionality

This commit is contained in:
Amritanshu Agrawal 2021-04-02 06:34:31 +05:30
parent 214c40fbde
commit 0da16e9548
24 changed files with 560 additions and 7 deletions

View File

@ -93,11 +93,11 @@ def delete(
raise
@router.get("", response_model=schemas.CustomerIn)
@router.get("", response_model=schemas.CustomerBlank)
def show_blank(
db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["customers"]),
) -> schemas.CustomerIn:
) -> schemas.CustomerBlank:
return blank_customer_info()
@ -137,5 +137,5 @@ def customer_info(item: Customer) -> schemas.Customer:
)
def blank_customer_info() -> schemas.CustomerIn:
return schemas.CustomerIn(name="", address="", phone="")
def blank_customer_info() -> schemas.CustomerBlank:
return schemas.CustomerBlank(name="", address="", phone="")

View File

@ -9,11 +9,11 @@ from . import to_camel
class CustomerIn(BaseModel):
name: str = Field(..., min_length=1)
phone: str = Field(..., min_length=1)
# phone: str = Field(..., min_length=1)
phone: str
address: Optional[str]
class Config:
fields = {"id_": "id"}
anystr_strip_whitespace = True
alias_generator = to_camel
@ -33,4 +33,11 @@ class CustomerLink(BaseModel):
class Config:
fields = {"id_": "id"}
class CustomerBlank(CustomerIn):
name: str
class Config:
anystr_strip_whitespace = True
alias_generator = to_camel

View File

@ -23,6 +23,10 @@ const routes: Routes = [
loadChildren: () =>
import('./cashier-report/cashier-report.module').then((mod) => mod.CashierReportModule),
},
{
path: 'customers',
loadChildren: () => import('./customers/customer.module').then((mod) => mod.CustomerModule),
},
{
path: 'devices',
loadChildren: () => import('./devices/devices.module').then((mod) => mod.DevicesModule),

View File

@ -0,0 +1,14 @@
export class Customer {
id: string;
name: string;
phone: string;
address: string;
public constructor(init?: Partial<Customer>) {
this.id = '';
this.name = '';
this.phone = '';
this.address = '';
Object.assign(this, init);
}
}

View File

@ -0,0 +1,3 @@
.example-card {
max-width: 400px;
}

View File

@ -0,0 +1,51 @@
<div fxLayout="row" fxFlex="50%" fxLayoutAlign="space-around center" class="example-card">
<mat-card fxFlex>
<mat-card-title-group>
<mat-card-title>Customer</mat-card-title>
</mat-card-title-group>
<mat-card-content>
<form [formGroup]="form" fxLayout="column">
<div
fxLayout="row"
fxLayoutAlign="space-around start"
fxLayout.lt-md="column"
fxLayoutGap="20px"
fxLayoutGap.lt-md="0px"
>
<mat-form-field fxFlex>
<mat-label>Name</mat-label>
<input matInput #nameElement placeholder="Name" formControlName="name" />
</mat-form-field>
</div>
<div
fxLayout="row"
fxLayoutAlign="space-around start"
fxLayout.lt-md="column"
fxLayoutGap="20px"
fxLayoutGap.lt-md="0px"
>
<mat-form-field fxFlex>
<mat-label>Phone</mat-label>
<input matInput placeholder="Phone" formControlName="phone" />
</mat-form-field>
</div>
<div
fxLayout="row"
fxLayoutAlign="space-around start"
fxLayout.lt-md="column"
fxLayoutGap="20px"
fxLayoutGap.lt-md="0px"
>
<mat-form-field fxFlex>
<mat-label>Address</mat-label>
<input matInput placeholder="Address" formControlName="address" />
</mat-form-field>
</div>
</form>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" (click)="save()">Save</button>
<button mat-raised-button color="warn" (click)="confirmDelete()">Delete</button>
</mat-card-actions>
</mat-card>
</div>

View File

@ -0,0 +1,26 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { CustomerDetailComponent } from './customer-detail.component';
describe('CustomerDetailComponent', () => {
let component: CustomerDetailComponent;
let fixture: ComponentFixture<CustomerDetailComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [CustomerDetailComponent],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(CustomerDetailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,105 @@
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { Customer } from '../../core/customer';
import { ToasterService } from '../../core/toaster.service';
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
import { CustomerService } from '../customer.service';
@Component({
selector: 'app-customer-detail',
templateUrl: './customer-detail.component.html',
styleUrls: ['./customer-detail.component.css'],
})
export class CustomerDetailComponent implements OnInit, AfterViewInit {
@ViewChild('nameElement', { static: true }) nameElement?: ElementRef;
form: FormGroup;
item: Customer = new Customer();
hide: boolean;
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private toaster: ToasterService,
private dialog: MatDialog,
private ser: CustomerService,
) {
this.hide = true;
// Create form
this.form = this.fb.group({
name: '',
phone: '',
address: '',
});
}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { item: Customer };
this.showItem(data.item);
});
}
showItem(item: Customer) {
this.item = item;
(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);
}
ngAfterViewInit() {
setTimeout(() => {
if (this.nameElement !== undefined) {
this.nameElement.nativeElement.focus();
}
}, 0);
}
save() {
this.ser.saveOrUpdate(this.getItem()).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/customers');
},
(error) => {
this.toaster.show('Error', error);
},
);
}
delete() {
this.ser.delete(this.item.id as string).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/customers');
},
(error) => {
this.toaster.show('Error', error);
},
);
}
confirmDelete(): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: { title: 'Delete Customer?', content: 'Are you sure? This cannot be undone.' },
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.delete();
}
});
}
getItem(): Customer {
const formModel = this.form.value;
this.item.name = formModel.name;
this.item.phone = formModel.phone;
this.item.address = formModel.address;
return this.item;
}
}

View File

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

View File

@ -0,0 +1,18 @@
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs/internal/Observable';
import { Customer } from '../core/customer';
import { CustomerService } from './customer.service';
@Injectable({
providedIn: 'root',
})
export class CustomerListResolver implements Resolve<Customer[]> {
constructor(private ser: CustomerService) {}
resolve(): Observable<Customer[]> {
return this.ser.list();
}
}

View File

@ -0,0 +1,16 @@
import { DataSource } from '@angular/cdk/collections';
import { Observable, of as observableOf } from 'rxjs';
import { Customer } from '../../core/customer';
export class CustomerListDatasource extends DataSource<Customer> {
constructor(public data: Customer[]) {
super();
}
connect(): Observable<Customer[]> {
return observableOf(this.data);
}
disconnect() {}
}

View File

@ -0,0 +1,35 @@
<mat-card>
<mat-card-title-group>
<mat-card-title>Customers</mat-card-title>
<a mat-button [routerLink]="['/customers', 'new']">
<mat-icon>add_box</mat-icon>
Add
</a>
</mat-card-title-group>
<mat-card-content>
<mat-table #table [dataSource]="dataSource" aria-label="Elements">
<!-- Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let row"
><a [routerLink]="['/customers', row.id]">{{ row.name }}</a></mat-cell
>
</ng-container>
<!-- Phone Column -->
<ng-container matColumnDef="phone">
<mat-header-cell *matHeaderCellDef>Phone</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row.phone }}</mat-cell>
</ng-container>
<!-- Address Column -->
<ng-container matColumnDef="address">
<mat-header-cell *matHeaderCellDef>Address</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row.address }}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
</mat-card-content>
</mat-card>

View File

@ -0,0 +1,28 @@
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Customer } from '../../core/customer';
import { CustomerListDatasource } from './customer-list-datasource';
@Component({
selector: 'app-customer-list',
templateUrl: './customer-list.component.html',
styleUrls: ['./customer-list.component.css'],
})
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'];
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { list: Customer[] };
this.list = data.list;
});
this.dataSource = new CustomerListDatasource(this.list);
}
}

View File

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

View File

@ -0,0 +1,19 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve } from '@angular/router';
import { Observable } from 'rxjs/internal/Observable';
import { Customer } from '../core/customer';
import { CustomerService } from './customer.service';
@Injectable({
providedIn: 'root',
})
export class CustomerResolver implements Resolve<Customer> {
constructor(private ser: CustomerService) {}
resolve(route: ActivatedRouteSnapshot): Observable<Customer> {
const id = route.paramMap.get('id');
return this.ser.get(id);
}
}

View File

@ -0,0 +1,13 @@
import { CustomerRoutingModule } from './customer-routing.module';
describe('CustomersRoutingModule', () => {
let customerRoutingModule: CustomerRoutingModule;
beforeEach(() => {
customerRoutingModule = new CustomerRoutingModule();
});
it('should create an instance', () => {
expect(customerRoutingModule).toBeTruthy();
});
});

View File

@ -0,0 +1,50 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from '../auth/auth-guard.service';
import { CustomerDetailComponent } from './customer-detail/customer-detail.component';
import { CustomerListResolver } from './customer-list-resolver.service';
import { CustomerListComponent } from './customer-list/customer-list.component';
import { CustomerResolver } from './customer-resolver.service';
const customersRoutes: Routes = [
{
path: '',
component: CustomerListComponent,
canActivate: [AuthGuard],
data: {
permission: 'Customers',
},
resolve: {
list: CustomerListResolver,
},
},
{
path: 'new',
component: CustomerDetailComponent,
canActivate: [AuthGuard],
data: {
permission: 'Customers',
},
resolve: {
item: CustomerResolver,
},
},
{
path: ':id',
component: CustomerDetailComponent,
canActivate: [AuthGuard],
resolve: {
item: CustomerResolver,
},
},
];
@NgModule({
imports: [CommonModule, RouterModule.forChild(customersRoutes)],
exports: [RouterModule],
providers: [CustomerListResolver, CustomerResolver],
})
export class CustomerRoutingModule {}

View File

@ -0,0 +1,13 @@
import { CustomerModule } from './customer.module';
describe('CustomerModule', () => {
let customerModuleModule: CustomerModule;
beforeEach(() => {
customerModuleModule = new CustomerModule();
});
it('should create an instance', () => {
expect(customerModuleModule).toBeTruthy();
});
});

View File

@ -0,0 +1,40 @@
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 { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTableModule } from '@angular/material/table';
import { SharedModule } from '../shared/shared.module';
import { CustomerDetailComponent } from './customer-detail/customer-detail.component';
import { CustomerListComponent } from './customer-list/customer-list.component';
import { CustomerRoutingModule } from './customer-routing.module';
@NgModule({
imports: [
CommonModule,
CdkTableModule,
FlexLayoutModule,
MatButtonModule,
MatCardModule,
MatCheckboxModule,
MatDividerModule,
MatIconModule,
MatInputModule,
MatProgressSpinnerModule,
MatTableModule,
ReactiveFormsModule,
SharedModule,
CustomerRoutingModule,
],
declarations: [CustomerListComponent, CustomerDetailComponent],
})
export class CustomerModule {}

View File

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

View File

@ -0,0 +1,58 @@
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import { catchError } from 'rxjs/operators';
import { Customer } from '../core/customer';
import { ErrorLoggerService } from '../core/error-logger.service';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
};
const url = '/api/customers';
const serviceName = 'CustomerService';
@Injectable({
providedIn: 'root',
})
export class CustomerService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
get(id: string | null): Observable<Customer> {
const getUrl: string = id === null ? `${url}` : `${url}/${id}`;
return this.http
.get<Customer>(getUrl)
.pipe(catchError(this.log.handleError(serviceName, `get id=${id}`))) as Observable<Customer>;
}
list(): Observable<Customer[]> {
return this.http
.get<Customer[]>(`${url}/list`)
.pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable<Customer[]>;
}
save(customer: Customer): Observable<Customer> {
return this.http
.post<Customer>(`${url}`, customer, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable<Customer>;
}
update(customer: Customer): Observable<Customer> {
return this.http
.put<Customer>(`${url}/${customer.id}`, customer, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable<Customer>;
}
saveOrUpdate(customer: Customer): Observable<Customer> {
if (!customer.id) {
return this.save(customer);
}
return this.update(customer);
}
delete(id: string): Observable<Customer> {
return this.http
.delete<Customer>(`${url}/${id}`, httpOptions)
.pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable<Customer>;
}
}

View File

@ -10,7 +10,6 @@ import { Customer } from '../customer';
import { GuestBook } from '../guest-book';
import { GuestBookService } from '../guest-book.service';
@Component({
selector: 'app-guest-book-detail',
templateUrl: './guest-book-detail.component.html',

View File

@ -17,6 +17,15 @@
>
<h3 class="item-name">Sales</h3>
</mat-card>
<mat-card
fxLayout="column"
class="square-button"
matRipple
*ngIf="auth.allowed('customers')"
[routerLink]="['/', 'customers']"
>
<h3 class="item-name">Customers</h3>
</mat-card>
</div>
<div fxLayout="row wrap" fxLayoutGap="grid 20px">
<mat-card