Product updates report.

This commit is contained in:
Amritanshu Agrawal 2020-11-11 12:18:10 +05:30
parent 6f9394dc8d
commit d5b2da4388
19 changed files with 500 additions and 0 deletions

View File

@ -29,6 +29,7 @@ from .routers.reports import (
cashier_report,
discount_report,
product_sale_report,
product_updates_report,
sale_report,
tax_report,
)
@ -65,6 +66,7 @@ app.include_router(product.router, prefix="/api/products", tags=["products"])
app.include_router(device.router, prefix="/api/devices", tags=["devices"])
app.include_router(sale_category.router, prefix="/api/sale-categories", tags=["products"])
app.include_router(header_footer.router, prefix="/api/header-footer", tags=["products"])
app.include_router(product_updates_report.router, prefix="/api/product-updates-report", tags=["products"])
app.include_router(section.router, prefix="/api/sections", tags=["sections"])
app.include_router(section_printer.router, prefix="/api/section-printers", tags=["section-printers"])

View File

@ -174,6 +174,7 @@ def update(
quantity=data.quantity,
valid_from=date_,
valid_till=None,
sort_order=item.sort_order,
)
db.add(product_version)
db.commit()

View File

@ -0,0 +1,83 @@
from datetime import date, timedelta
from typing import List
from fastapi import APIRouter, Depends, Security
from sqlalchemy import and_, or_
from sqlalchemy.orm import Session, contains_eager, joinedload
from ...core.security import get_current_active_user as get_user
from ...db.session import SessionLocal
from ...models import MenuCategory, ProductVersion
from ...schemas.auth import UserToken
from . import report_finish_date, report_start_date
router = APIRouter()
# Dependency
def get_db() -> Session:
try:
db = SessionLocal()
yield db
finally:
db.close()
@router.get("")
def product_updates_report_view(
start_date: date = Depends(report_start_date),
finish_date: date = Depends(report_finish_date),
db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["product-sale-report"]),
):
return {
"startDate": start_date.strftime("%d-%b-%Y"),
"finishDate": finish_date.strftime("%d-%b-%Y"),
"report": product_updates_report(start_date, finish_date, db),
}
def product_updates_report(s: date, f: date, db: Session) -> List[str]:
list_: List[ProductVersion] = (
db.query(ProductVersion)
.join(ProductVersion.menu_category)
.filter(
or_(
and_(
ProductVersion.valid_from >= s,
ProductVersion.valid_from <= f,
),
and_(
ProductVersion.valid_till >= s - timedelta(days=1),
ProductVersion.valid_till <= f,
),
)
)
.order_by(
MenuCategory.sort_order,
MenuCategory.name,
ProductVersion.sort_order,
ProductVersion.name,
ProductVersion.valid_from.nullsfirst(),
)
.options(
joinedload(ProductVersion.menu_category, innerjoin=True),
contains_eager(ProductVersion.menu_category),
)
.all()
)
report = {}
for item in list_:
if item.product_id not in report:
report[item.product_id] = ""
report[item.product_id] += (
"From: "
+ (f"{item.valid_from:%d-%b-%Y}" if item.valid_from is not None else "\u221e")
+ " "
+ "Till: "
+ (f"{item.valid_till:%d-%b-%Y}" if item.valid_till is not None else "\u221e")
+ "\n"
+ f"{item.full_name} @ {item.price: .2f} - {'Happy Hour' if item.has_happy_hour else 'No Happy Hour'}\n"
)
return list(report.values())

View File

@ -68,6 +68,13 @@ const routes: Routes = [
(mod) => mod.ProductSaleReportModule,
),
},
{
path: 'product-updates-report',
loadChildren: () =>
import('./product-updates-report/product-updates-report.module').then(
(mod) => mod.ProductUpdatesReportModule,
),
},
{
path: 'menu-categories',
loadChildren: () =>

View File

@ -206,6 +206,15 @@
>
<h3 class="item-name">Header / Footer</h3>
</mat-card>
<mat-card
fxLayout="column"
class="square-button"
matRipple
*ngIf="auth.user && auth.user.perms.indexOf('products') !== -1"
[routerLink]="['/', 'product-updates-report']"
>
<h3 class="item-name">Product Updates Report</h3>
</mat-card>
</div>
<footer class="footer">
<p>Backend: v{{ auth.user?.ver }} / Frontend: v{{ version }} on {{ auth.device.name }}</p>

View File

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

View File

@ -0,0 +1,18 @@
import { inject, TestBed } from '@angular/core/testing';
import { ProductUpdatesReportResolver } from './product-updates-report-resolver.service';
describe('ProductUpdatesReportResolver', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ProductUpdatesReportResolver],
});
});
it('should be created', inject(
[ProductUpdatesReportResolver],
(service: ProductUpdatesReportResolver) => {
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 { ProductUpdatesReport } from './product-updates-report';
import { ProductUpdatesReportService } from './product-updates-report.service';
@Injectable({
providedIn: 'root',
})
export class ProductUpdatesReportResolver implements Resolve<ProductUpdatesReport> {
constructor(private ser: ProductUpdatesReportService) {}
resolve(route: ActivatedRouteSnapshot): Observable<ProductUpdatesReport> {
const startDate = route.queryParamMap.get('startDate') || null;
const finishDate = route.queryParamMap.get('finishDate') || null;
return this.ser.get(startDate, finishDate);
}
}

View File

@ -0,0 +1,13 @@
import { ProductUpdatesReportRoutingModule } from './product-updates-report-routing.module';
describe('ProductUpdatesReportRoutingModule', () => {
let productUpdatesReportRoutingModule: ProductUpdatesReportRoutingModule;
beforeEach(() => {
productUpdatesReportRoutingModule = new ProductUpdatesReportRoutingModule();
});
it('should create an instance', () => {
expect(productUpdatesReportRoutingModule).toBeTruthy();
});
});

View File

@ -0,0 +1,30 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from '../auth/auth-guard.service';
import { ProductUpdatesReportResolver } from './product-updates-report-resolver.service';
import { ProductUpdatesReportComponent } from './product-updates-report.component';
const productUpdatesReportRoutes: Routes = [
{
path: '',
component: ProductUpdatesReportComponent,
canActivate: [AuthGuard],
data: {
permission: 'Products',
},
resolve: {
info: ProductUpdatesReportResolver,
},
runGuardsAndResolvers: 'always',
},
];
@NgModule({
imports: [CommonModule, RouterModule.forChild(productUpdatesReportRoutes)],
exports: [RouterModule],
providers: [ProductUpdatesReportResolver],
})
export class ProductUpdatesReportRoutingModule {}

View File

@ -0,0 +1,7 @@
.right {
display: flex;
justify-content: flex-end;
}
.multi_lines_text {
white-space: pre-line;
}

View File

@ -0,0 +1,55 @@
<mat-card>
<mat-card-title-group>
<mat-card-title>Product Update Report</mat-card-title>
<button mat-button mat-icon-button (click)="exportCsv()">
<mat-icon>save_alt</mat-icon>
</button>
</mat-card-title-group>
<mat-card-content>
<form [formGroup]="form" fxLayout="column">
<div
fxLayout="row"
fxLayout.lt-md="column"
fxLayoutGap="20px"
fxLayoutGap.lt-md="0px"
fxLayoutAlign="space-around start"
>
<mat-form-field fxFlex="40">
<input
matInput
[matDatepicker]="startDate"
(focus)="startDate.open()"
placeholder="Start Date"
formControlName="startDate"
autocomplete="off"
/>
<mat-datepicker-toggle matSuffix [for]="startDate"></mat-datepicker-toggle>
<mat-datepicker #startDate></mat-datepicker>
</mat-form-field>
<mat-form-field fxFlex="40">
<input
matInput
[matDatepicker]="finishDate"
(focus)="finishDate.open()"
placeholder="Finish Date"
formControlName="finishDate"
autocomplete="off"
/>
<mat-datepicker-toggle matSuffix [for]="finishDate"></mat-datepicker-toggle>
<mat-datepicker #finishDate></mat-datepicker>
</mat-form-field>
<button fxFlex="20" mat-raised-button color="primary" (click)="show()">Show</button>
</div>
</form>
<mat-table #table [dataSource]="dataSource" aria-label="Elements">
<!-- Details Column -->
<ng-container matColumnDef="details">
<mat-header-cell *matHeaderCellDef>Details</mat-header-cell>
<mat-cell class="multi_lines_text" *matCellDef="let row">{{ row }}</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,24 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ProductUpdatesReportComponent } from './product-updates-report.component';
describe('ProductUpdatesReportComponent', () => {
let component: ProductUpdatesReportComponent;
let fixture: ComponentFixture<ProductUpdatesReportComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ProductUpdatesReportComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProductUpdatesReportComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,84 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { ToCsvService } from '../shared/to-csv.service';
import { ProductUpdatesReport } from './product-updates-report';
import { ProductUpdatesReportDataSource } from './product-updates-report-datasource';
@Component({
selector: 'app-product-updates-report',
templateUrl: './product-updates-report.component.html',
styleUrls: ['./product-updates-report.component.css'],
})
export class ProductUpdatesReportComponent implements OnInit {
dataSource: ProductUpdatesReportDataSource;
form: FormGroup;
info: ProductUpdatesReport;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['details'];
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private toCsv: ToCsvService,
) {
this.createForm();
}
ngOnInit() {
this.route.data.subscribe((data: { info: ProductUpdatesReport }) => {
this.info = data.info;
this.form.setValue({
startDate: moment(this.info.startDate, 'DD-MMM-YYYY').toDate(),
finishDate: moment(this.info.finishDate, 'DD-MMM-YYYY').toDate(),
});
this.dataSource = new ProductUpdatesReportDataSource(this.info.report);
});
}
show() {
const info = this.getInfo();
this.router.navigate(['product-updates-report'], {
queryParams: {
startDate: info.startDate,
finishDate: info.finishDate,
},
});
}
createForm() {
this.form = this.fb.group({
startDate: '',
finishDate: '',
});
}
getInfo(): ProductUpdatesReport {
const formModel = this.form.value;
return {
startDate: moment(formModel.startDate).format('DD-MMM-YYYY'),
finishDate: moment(formModel.finishDate).format('DD-MMM-YYYY'),
};
}
exportCsv() {
const headers = {
Details: 'details',
};
const csvData = new Blob([this.toCsv.toCsv(headers, this.dataSource.data)], {
type: 'text/csv;charset=utf-8;',
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(csvData);
link.setAttribute('download', 'product-updates-report.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}

View File

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

View File

@ -0,0 +1,65 @@
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 {
DateAdapter,
MAT_DATE_FORMATS,
MAT_DATE_LOCALE,
MatNativeDateModule,
} from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatTableModule } from '@angular/material/table';
import { SharedModule } from '../shared/shared.module';
import { ProductUpdatesReportRoutingModule } from './product-updates-report-routing.module';
import { ProductUpdatesReportComponent } from './product-updates-report.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,
MatDatepickerModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatNativeDateModule,
MatTableModule,
ReactiveFormsModule,
SharedModule,
ProductUpdatesReportRoutingModule,
],
declarations: [ProductUpdatesReportComponent],
providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
],
})
export class ProductUpdatesReportModule {}

View File

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

View File

@ -0,0 +1,33 @@
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 { ProductUpdatesReport } from './product-updates-report';
const url = '/api/product-updates-report';
const serviceName = 'ProductUpdatesReportService';
@Injectable({
providedIn: 'root',
})
export class ProductUpdatesReportService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
get(startDate: string, finishDate): Observable<ProductUpdatesReport> {
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 <Observable<ProductUpdatesReport>>(
this.http
.get<ProductUpdatesReport>(url, options)
.pipe(catchError(this.log.handleError(serviceName, 'get')))
);
}
}

View File

@ -0,0 +1,5 @@
export class ProductUpdatesReport {
startDate: string;
finishDate: string;
report?: string[];
}