Update Product Prices built

This commit is contained in:
2020-11-12 12:32:16 +05:30
parent d5b2da4388
commit 5e180f48d5
33 changed files with 750 additions and 22 deletions
+2
View File
@@ -21,6 +21,7 @@ from .routers import (
section_printer,
table,
tax,
update_product_prices,
)
from .routers.auth import role, user
from .routers.reports import (
@@ -67,6 +68,7 @@ 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(update_product_prices.router, prefix="/api/update-product-prices", 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"])
+1 -1
View File
@@ -91,7 +91,7 @@ def design_bill(
<= (voucher.date - timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)).date(),
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till
>= (voucher.date - timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)).date(),
),
+2 -2
View File
@@ -44,7 +44,7 @@ def design_kot(voucher: Voucher, kot: Kot, items: List[Inventory], copy_number:
<= (voucher.date - timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)).date(),
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till
>= (voucher.date - timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)).date(),
),
@@ -76,7 +76,7 @@ def print_kot(voucher_id: uuid.UUID, db: Session):
<= (voucher.date - timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)).date(),
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till
>= (voucher.date - timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)).date(),
),
+5
View File
@@ -0,0 +1,5 @@
from datetime import date, datetime
def query_date(d: str = None) -> date:
return date.today() if d is None else datetime.strptime(d, "%d-%b-%Y").date()
+2 -2
View File
@@ -139,7 +139,7 @@ def show_list(
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
@@ -223,7 +223,7 @@ def modifier_category_info(item: Optional[ModifierCategory], date_: date, db: Se
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
+6 -6
View File
@@ -60,7 +60,7 @@ def sort_order(
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
@@ -136,7 +136,7 @@ def update(
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
@@ -209,7 +209,7 @@ def delete(
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
@@ -269,7 +269,7 @@ def product_list(date_: date, db: Session) -> List[schemas.Product]:
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
@@ -308,7 +308,7 @@ async def show_term(
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
@@ -347,7 +347,7 @@ def show_id(
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
@@ -53,7 +53,7 @@ def beer_consumption(
ProductVersion.valid_from <= day,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= day,
),
Voucher.voucher_type.in_(
@@ -69,7 +69,7 @@ def get_discount_report(s: date, f: date, db: Session) -> List[DiscountReportIte
ProductVersion.valid_from <= day,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= day,
),
Voucher.voucher_type.in_([VoucherType.REGULAR_BILL.value, VoucherType.KOT.value]),
@@ -79,7 +79,7 @@ def product_sale_report(s: date, f: date, db: Session):
ProductVersion.valid_from <= day,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= day,
),
)
+1 -1
View File
@@ -86,7 +86,7 @@ def get_sale(s: date, f: date, db: Session) -> List[SaleReportItem]:
ProductVersion.valid_from <= day,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= day,
),
)
@@ -0,0 +1,171 @@
import uuid
from datetime import date, timedelta
from decimal import Decimal
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Security, status
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 ..schemas.update_product_prices import UpdateProductPrices, UpdateProductPricesItem
from . import query_date
router = APIRouter()
# Dependency
def get_db() -> Session:
try:
db = SessionLocal()
yield db
finally:
db.close()
@router.get("", response_model=UpdateProductPrices)
def get_update_product_prices(
date_: date = Depends(query_date),
db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["products"]),
) -> UpdateProductPrices:
return UpdateProductPrices(
date=date_,
items=update_product_prices_list(None, date_, db),
)
@router.get("/{id_}", response_model=UpdateProductPrices)
def get_update_product_prices_id(
id_: uuid.UUID,
date_: date = Depends(query_date),
db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["products"]),
) -> UpdateProductPrices:
return UpdateProductPrices(
date=date_,
menuCategoryId=id_,
items=update_product_prices_list(id_, date_, db),
)
def update_product_prices_list(
menu_category_id: Optional[uuid.UUID], date_: date, db: Session
) -> List[UpdateProductPricesItem]:
list_: List[ProductVersion] = (
db.query(ProductVersion)
.join(ProductVersion.menu_category)
.filter(
and_(
or_(
ProductVersion.valid_from == None, # noqa: E711
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
)
)
if menu_category_id is not None:
list_ = list_.filter(ProductVersion.menu_category_id == menu_category_id)
list_.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()
return [
UpdateProductPricesItem(id=item.product_id, name=item.full_name, oldPrice=item.price, newPrice=item.price)
for item in list_
]
@router.post("", response_model=UpdateProductPrices)
def save_update_product_prices(
data: UpdateProductPrices,
db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["products"]),
) -> UpdateProductPrices:
for item in data.items:
update_product(item.id, item.new_price, data.date_, db)
db.commit()
return UpdateProductPrices(
date=data.date_,
items=update_product_prices_list(None, data.date_, db),
)
@router.post("/{id_}", response_model=UpdateProductPrices)
def save_update_product_prices_id(
id_: uuid.UUID,
data: UpdateProductPrices,
db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["products"]),
) -> UpdateProductPrices:
for item in data.items:
update_product(item.id, item.new_price, data.date_, db)
db.commit()
return UpdateProductPrices(
date=data.date_,
menuCategoryId=id_,
items=update_product_prices_list(id_, data.date_, db),
)
def update_product(id_: uuid.UUID, price: Decimal, date_: date, db: Session):
item: ProductVersion = (
db.query(ProductVersion)
.join(ProductVersion.menu_category)
.filter(
and_(
ProductVersion.product_id == id_,
or_(
ProductVersion.valid_from == None, # noqa: E711
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
)
.first()
)
if item.valid_till is not None:
# Allow adding a product here splitting the valid from and to, but not implemented right now
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Product has been invalidated",
)
if item.valid_from == date_: # Update the product as valid from the the same
item.price = price
db.commit()
else: # Create a new version of the product from the new details
item.valid_till = date_ - timedelta(days=1)
product_version = ProductVersion(
product_id=item.product_id,
name=item.name,
units=item.units,
menu_category_id=item.menu_category_id,
sale_category_id=item.sale_category_id,
price=price,
has_happy_hour=item.has_happy_hour,
is_not_available=item.is_not_available,
quantity=item.quantity,
valid_from=date_,
valid_till=None,
sort_order=item.sort_order,
)
db.add(product_version)
+1 -1
View File
@@ -126,7 +126,7 @@ def do_save(
ProductVersion.valid_from <= product_date,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= product_date,
),
)
+1 -1
View File
@@ -114,7 +114,7 @@ def voucher_product(product_id: uuid.UUID, date_: date, db: Session):
ProductVersion.valid_from <= date_,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= date_,
),
)
+1 -1
View File
@@ -106,7 +106,7 @@ def update(
ProductVersion.valid_from <= product_date,
),
or_(
ProductVersion.valid_till == None, # noqa: FE711
ProductVersion.valid_till == None, # noqa: E711
ProductVersion.valid_till >= product_date,
),
)
@@ -0,0 +1,35 @@
import uuid
from datetime import date, datetime
from decimal import Decimal
from typing import List, Optional
from pydantic import BaseModel, validator
from . import to_camel
class UpdateProductPricesItem(BaseModel):
id: uuid.UUID
name: str
old_price: Decimal
new_price: Decimal
class Config:
alias_generator = to_camel
class UpdateProductPrices(BaseModel):
date_: date
menu_category_id: Optional[uuid.UUID]
items: List[UpdateProductPricesItem]
class Config:
alias_generator = to_camel
json_encoders = {date: lambda v: v.strftime("%d-%b-%Y")}
@validator("date_", pre=True)
def parse_date(cls, value):
if isinstance(value, date):
return value
return datetime.strptime(value, "%d-%b-%Y").date()
+9 -1
View File
@@ -40,7 +40,8 @@ const routes: Routes = [
},
{
path: 'header-footer',
loadChildren: () => import('./header-footer/header-footer.module').then((mod) => mod.HeaderFooterModule),
loadChildren: () =>
import('./header-footer/header-footer.module').then((mod) => mod.HeaderFooterModule),
},
{
path: 'modifiers',
@@ -119,6 +120,13 @@ const routes: Routes = [
path: 'tax-report',
loadChildren: () => import('./tax-report/tax-report.module').then((mod) => mod.TaxReportModule),
},
{
path: 'update-product-prices',
loadChildren: () =>
import('./update-product-prices/update-product-prices.module').then(
(mod) => mod.UpdateProductPricesModule,
),
},
{
path: 'users',
loadChildren: () => import('./users/users.module').then((mod) => mod.UsersModule),
+9
View File
@@ -215,6 +215,15 @@
>
<h3 class="item-name">Product Updates Report</h3>
</mat-card>
<mat-card
fxLayout="column"
class="square-button"
matRipple
*ngIf="auth.user && auth.user.perms.indexOf('products') !== -1"
[routerLink]="['/', 'update-product-prices']"
>
<h3 class="item-name">Update Product Prices</h3>
</mat-card>
</div>
<footer class="footer">
<p>Backend: v{{ auth.user?.ver }} / Frontend: v{{ version }} on {{ auth.device.name }}</p>
@@ -4,8 +4,8 @@
<button mat-button (click)="updateSortOrder()" [disabled]="!(filter | async)">
Update Order
</button>
<!-- This should check filtered data and not data-->
<button mat-button mat-icon-button (click)="exportCsv()" [disabled]="!((data | async).length)">
<!-- This should check filtered data and not data-->
<button mat-button mat-icon-button (click)="exportCsv()" [disabled]="!(data | async).length">
<mat-icon>save_alt</mat-icon>
</button>
<a mat-button [routerLink]="['/products', 'new']">
@@ -95,7 +95,9 @@
<!-- Yield Column -->
<ng-container matColumnDef="quantity">
<mat-header-cell *matHeaderCellDef class="right">Quantity</mat-header-cell>
<mat-cell *matCellDef="let row" class="right">{{ row.quantity | number: '1.2-2' }}</mat-cell>
<mat-cell *matCellDef="let row" class="right">{{
row.quantity | number: '1.2-2'
}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
@@ -0,0 +1,16 @@
import { DataSource } from '@angular/cdk/collections';
import { Observable, of as observableOf } from 'rxjs';
import { UpdateProductPricesItem } from './update-product-prices-item';
export class UpdateProductPricesDataSource extends DataSource<UpdateProductPricesItem> {
constructor(public data: UpdateProductPricesItem[]) {
super();
}
connect(): Observable<UpdateProductPricesItem[]> {
return observableOf(this.data);
}
disconnect() {}
}
@@ -0,0 +1,6 @@
export class UpdateProductPricesItem {
id: string;
name: string;
oldPrice: number;
newPrice: number;
}
@@ -0,0 +1,18 @@
import { inject, TestBed } from '@angular/core/testing';
import { UpdateProductPricesResolver } from './update-product-prices-resolver.service';
describe('UpdateProductPricesResolver', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [UpdateProductPricesResolver],
});
});
it('should be created', inject(
[UpdateProductPricesResolver],
(service: UpdateProductPricesResolver) => {
expect(service).toBeTruthy();
},
));
});
@@ -0,0 +1,20 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve } from '@angular/router';
import { Observable } from 'rxjs/internal/Observable';
import { UpdateProductPrices } from './update-product-prices';
import { UpdateProductPricesService } from './update-product-prices.service';
@Injectable({
providedIn: 'root',
})
export class UpdateProductPricesResolver implements Resolve<UpdateProductPrices> {
constructor(private ser: UpdateProductPricesService) {}
resolve(route: ActivatedRouteSnapshot): Observable<UpdateProductPrices> {
const startDate = route.queryParamMap.get('startDate') || null;
const finishDate = route.queryParamMap.get('finishDate') || null;
const id = route.paramMap.get('id');
return this.ser.get(id, startDate, finishDate);
}
}
@@ -0,0 +1,13 @@
import { UpdateProductPricesRoutingModule } from './update-product-prices-routing.module';
describe('UpdateProductPricesRoutingModule', () => {
let pupdateProductPricesRoutingModule: UpdateProductPricesRoutingModule;
beforeEach(() => {
pupdateProductPricesRoutingModule = new UpdateProductPricesRoutingModule();
});
it('should create an instance', () => {
expect(pupdateProductPricesRoutingModule).toBeTruthy();
});
});
@@ -0,0 +1,45 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from '../auth/auth-guard.service';
import { MenuCategoryListResolver } from '../menu-category/menu-category-list-resolver.service';
import { UpdateProductPricesResolver } from './update-product-prices-resolver.service';
import { UpdateProductPricesComponent } from './update-product-prices.component';
const pupdateProductPricesRoutes: Routes = [
{
path: '',
component: UpdateProductPricesComponent,
canActivate: [AuthGuard],
data: {
permission: 'Products',
},
resolve: {
menuCategories: MenuCategoryListResolver,
info: UpdateProductPricesResolver,
},
runGuardsAndResolvers: 'always',
},
{
path: ':id',
component: UpdateProductPricesComponent,
canActivate: [AuthGuard],
data: {
permission: 'Products',
},
resolve: {
menuCategories: MenuCategoryListResolver,
info: UpdateProductPricesResolver,
},
runGuardsAndResolvers: 'always',
},
];
@NgModule({
imports: [CommonModule, RouterModule.forChild(pupdateProductPricesRoutes)],
exports: [RouterModule],
providers: [UpdateProductPricesResolver],
})
export class UpdateProductPricesRoutingModule {}
@@ -0,0 +1,9 @@
.right {
display: flex;
justify-content: flex-end;
margin-right: 1em;
margin-left: 1em;
}
.multi_lines_text {
white-space: pre-line;
}
@@ -0,0 +1,70 @@
<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]="date"
(focus)="date.open()"
placeholder="Date"
formControlName="date"
autocomplete="off"
/>
<mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
<mat-datepicker #date></mat-datepicker>
</mat-form-field>
<mat-form-field fxFlex>
<mat-label>Section</mat-label>
<mat-select placeholder="Section" formControlName="menuCategory">
<mat-option *ngFor="let s of menuCategories" [value]="s.id">
{{ s.name }}
</mat-option>
</mat-select>
</mat-form-field>
<button fxFlex="20" mat-raised-button color="primary" (click)="show()">Show</button>
</div>
<mat-table #table [dataSource]="dataSource" aria-label="Elements" formArrayName="prices">
<!-- Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row.name }}</mat-cell>
</ng-container>
<!-- Old Price Column -->
<ng-container matColumnDef="oldPrice">
<mat-header-cell *matHeaderCellDef class="right">Old Price</mat-header-cell>
<mat-cell *matCellDef="let row" class="right">{{
row.oldPrice | currency: 'INR'
}}</mat-cell>
</ng-container>
<!-- New Price Column -->
<ng-container matColumnDef="newPrice">
<mat-header-cell *matHeaderCellDef class="right">New Price</mat-header-cell>
<mat-cell *matCellDef="let row; let i = index" [formGroupName]="i" fxFlex class="right">
&#x20B9; <input matInput type="number" placeholder="Price" formControlName="newPrice" />
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
</form>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" (click)="save()">Save</button>
</mat-card-actions>
</mat-card>
@@ -0,0 +1,24 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { UpdateProductPricesComponent } from './update-product-prices.component';
describe('UpdateProductPricesComponent', () => {
let component: UpdateProductPricesComponent;
let fixture: ComponentFixture<UpdateProductPricesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [UpdateProductPricesComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UpdateProductPricesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,126 @@
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { MenuCategory } from '../core/menu-category';
import { ToasterService } from '../core/toaster.service';
import { ToCsvService } from '../shared/to-csv.service';
import { UpdateProductPrices } from './update-product-prices';
import { UpdateProductPricesDataSource } from './update-product-prices-datasource';
import { UpdateProductPricesService } from './update-product-prices.service';
@Component({
selector: 'app-update-product-prices',
templateUrl: './update-product-prices.component.html',
styleUrls: ['./update-product-prices.component.css'],
})
export class UpdateProductPricesComponent implements OnInit {
dataSource: UpdateProductPricesDataSource;
form: FormGroup;
menuCategories: MenuCategory[];
info: UpdateProductPrices;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['name', 'oldPrice', 'newPrice'];
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private toCsv: ToCsvService,
private toaster: ToasterService,
private ser: UpdateProductPricesService,
) {
this.createForm();
}
ngOnInit() {
this.route.data.subscribe(
(data: { menuCategories: MenuCategory[]; info: UpdateProductPrices }) => {
this.menuCategories = data.menuCategories;
this.loadData(data.info);
},
);
}
loadData(info: UpdateProductPrices) {
this.info = info;
this.form.get('date').setValue(moment(this.info.date, 'DD-MMM-YYYY').toDate());
this.form
.get('menuCategory')
.setValue(this.info.menuCategoryId !== undefined ? this.info.menuCategoryId : '');
this.form.setControl(
'prices',
this.fb.array(
this.info.items.map((x) =>
this.fb.group({
newPrice: x.newPrice,
}),
),
),
);
this.dataSource = new UpdateProductPricesDataSource(this.info.items);
}
show() {
const info = this.getInfo();
const route = ['update-product-prices'];
if (info.menuCategoryId !== undefined) route.push(info.menuCategoryId);
this.router.navigate(route, {
queryParams: {
date: info.date,
},
});
}
createForm() {
this.form = this.fb.group({
date: '',
menuCategory: '',
prices: this.fb.array([]),
});
}
getInfo(): UpdateProductPrices {
const formModel = this.form.value;
const array = this.form.get('prices') as FormArray;
this.info.items.forEach((item, index) => {
item.newPrice = array.controls[index].value.newPrice;
});
return {
date: moment(formModel.date).format('DD-MMM-YYYY'),
menuCategoryId: formModel.menuCategory,
items: [...this.info.items],
};
}
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', 'update-product-prices.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
save() {
this.ser.save(this.getInfo()).subscribe(
(result: UpdateProductPrices) => {
this.toaster.show('Success', '');
this.loadData(result);
},
(error) => {
this.toaster.show('Danger', error.error);
},
);
}
}
@@ -0,0 +1,13 @@
import { UpdateProductPricesModule } from './update-product-prices.module';
describe('UpdateProductPricesModule', () => {
let pupdateProductPricesModule: UpdateProductPricesModule;
beforeEach(() => {
pupdateProductPricesModule = new UpdateProductPricesModule();
});
it('should create an instance', () => {
expect(pupdateProductPricesModule).toBeTruthy();
});
});
@@ -0,0 +1,67 @@
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 { MatSelectModule } from '@angular/material/select';
import { MatTableModule } from '@angular/material/table';
import { SharedModule } from '../shared/shared.module';
import { UpdateProductPricesRoutingModule } from './update-product-prices-routing.module';
import { UpdateProductPricesComponent } from './update-product-prices.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,
UpdateProductPricesRoutingModule,
MatSelectModule,
],
declarations: [UpdateProductPricesComponent],
providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
],
})
export class UpdateProductPricesModule {}
@@ -0,0 +1,18 @@
import { inject, TestBed } from '@angular/core/testing';
import { UpdateProductPricesService } from './update-product-prices.service';
describe('UpdateProductPricesService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [UpdateProductPricesService],
});
});
it('should be created', inject(
[UpdateProductPricesService],
(service: UpdateProductPricesService) => {
expect(service).toBeTruthy();
},
));
});
@@ -0,0 +1,44 @@
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 { Product } from '../core/product';
import { UpdateProductPrices } from './update-product-prices';
const url = '/api/update-product-prices';
const serviceName = 'UpdateProductPricesService';
@Injectable({
providedIn: 'root',
})
export class UpdateProductPricesService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
get(id: string, startDate: string, finishDate): Observable<UpdateProductPrices> {
const getUrl: string = 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 <Observable<UpdateProductPrices>>(
this.http
.get<UpdateProductPrices>(getUrl, options)
.pipe(catchError(this.log.handleError(serviceName, 'get')))
);
}
save(item: UpdateProductPrices): Observable<UpdateProductPrices> {
const saveUrl: string = item.menuCategoryId === null ? url : `${url}/${item.menuCategoryId}`;
return <Observable<UpdateProductPrices>>(
this.http
.post<Product[]>(saveUrl, item)
.pipe(catchError(this.log.handleError(serviceName, 'save')))
);
}
}
@@ -0,0 +1,7 @@
import { UpdateProductPricesItem } from './update-product-prices-item';
export class UpdateProductPrices {
date: string;
menuCategoryId?: string;
items: UpdateProductPricesItem[];
}