Feature: Sale Analysis is working

Fix: Cashier Checkout multiple entries
This commit is contained in:
Amritanshu
2019-08-20 23:02:17 +05:30
parent c6b907061e
commit 70d31fea5e
35 changed files with 650 additions and 138 deletions

View File

@ -357,6 +357,11 @@ def includeme(config):
config.add_route("v1_checkout_id", "/v1/checkout/{id}")
config.add_route("v1_checkout_blank", "/v1/checkout")
config.add_route("v1_sa_sale", "/v1/sale-analysis/sale")
config.add_route("v1_sa_settlements", "/v1_sale-analysis/settlements")
config.add_route("v1_sa_tax", "/v1_sale-analysis/tax")
config.add_route("v1_sale_analysis", "/v1/sale-analysis")
# Done till here
config.add_route("customer", "/Customer.json")
@ -388,10 +393,6 @@ def includeme(config):
config.add_route("setting_list", "/Settings.json")
config.add_route("setting_id", "/Setting/{id}.json")
config.add_route("sa_sale", "/SaleAnalysis/Sale.json")
config.add_route("sa_settlements", "/SaleAnalysis/Settlements.json")
config.add_route("sa_tax", "/SaleAnalysis/Tax.json")
config.add_route("voucher_reprint", "/ReprintVoucher/{id}.json")
config.add_route("api_lock_info", "/api/LockInfo")

View File

@ -1 +1,17 @@
__author__ = 'tanshu'
from datetime import datetime, timedelta
__author__ = "tanshu"
def get_start_date(s):
if not s:
return datetime.today().replace(hour=7)
else:
return datetime.strptime(s, "%d-%b-%Y").replace(hour=7)
def get_finish_date(f):
if not f:
return datetime.today().replace(hour=7) + timedelta(days=1)
else:
return datetime.strptime(f, "%d-%b-%Y").replace(hour=7) + timedelta(days=1)

View File

@ -5,6 +5,8 @@ from barker.models import Voucher, User, Settlement
from pyramid.view import view_config
from sqlalchemy.orm import joinedload
from barker.views.reports import get_start_date, get_finish_date
__author__ = "tanshu"
@ -12,20 +14,11 @@ __author__ = "tanshu"
request_method="GET",
route_name="v1_active_cashiers",
renderer="json",
permission="Cashier Checkout"
permission="Cashier Checkout",
)
def active_cashiers(request):
start_date = request.GET.get("s", None)
if not start_date:
start_date = datetime.today().replace(hour=7, minute=0)
else:
start_date = datetime.strptime(start_date, "%d-%b-%Y").replace(hour=7, minute=0)
finish_date = request.GET.get("f", None)
if not finish_date:
finish_date = datetime.today().replace(hour=7, minute=0) + timedelta(days=1)
else:
finish_date = datetime.strptime(finish_date, "%d-%b-%Y").replace(hour=7, minute=0) + timedelta(days=1)
start_date = get_start_date(request.GET.get("s", None))
finish_date = get_finish_date(request.GET.get("f", None))
user_ids = (
request.dbsession.query(Voucher.user_id)
@ -47,15 +40,15 @@ def active_cashiers(request):
request_method="GET",
route_name="v1_checkout_blank",
renderer="json",
permission="Cashier Checkout"
permission="Cashier Checkout",
)
def blank_out(request):
return {
"startDate": datetime.today().strftime("%d-%b-%Y"),
"finishDate": datetime.today().strftime("%d-%b-%Y"),
"user": {"id": ''},
"user": {"id": ""},
"amounts": [],
"info": []
"info": [],
}
@ -68,8 +61,8 @@ def blank_out(request):
)
def check_me_out(request):
id_ = uuid.UUID(request.matchdict["id"])
start_date = datetime.strptime(request.GET["s"], "%d-%b-%Y").replace(hour=7, minute=0)
finish_date = datetime.strptime(request.GET["f"], "%d-%b-%Y").replace(hour=7, minute=0) + timedelta(days=1)
start_date = get_start_date(request.GET.get("s", None))
finish_date = get_finish_date(request.GET.get("f", None))
vouchers = (
request.dbsession.query(Voucher)
@ -105,8 +98,9 @@ def check_me_out(request):
)
amounts[so.settle_option.name] += so.amount
return {
"startDate": request.GET["s"],
"finishDate": request.GET["f"],
"startDate": start_date.date().strftime("%d-%b-%Y"),
"finishDate": (finish_date - timedelta(days=1)).date().strftime("%d-%b-%Y"),
"user": {"id": id_},
"amounts": [{'name': key, 'amount': value} for key, value in amounts.items()], "info": info
"amounts": [{"name": key, "amount": value} for key, value in amounts.items()],
"info": info,
}

View File

@ -1,106 +1,195 @@
import datetime
from pyramid.httpexceptions import HTTPForbidden
from datetime import datetime, timedelta
from pyramid.view import view_config
from sqlalchemy import func
from barker.models import Inventory, Kot, Product, MenuCategory, Settlement, SettleOption, Tax, Voucher
import datetime
from pyramid.httpexceptions import HTTPForbidden
from pyramid.view import view_config
from sqlalchemy import func
from barker.models import Inventory, Kot, Product, MenuCategory, Settlement, SettleOption, Tax, Voucher
from barker.models import (
Inventory,
Kot,
Product,
Settlement,
SettleOption,
Tax,
Voucher,
SaleCategory,
VoucherType,
)
from barker.models.validation_exception import ValidationError
from barker.views.reports import get_start_date, get_finish_date
@view_config(request_method='GET', route_name='sa_sale', renderer='json', permission='Sales Analysis',
request_param=('s', 'f'))
def get_sale(request):
start_date = datetime.datetime.strptime(request.GET['s'], '%d-%b-%Y %H:%M')
finish_date = datetime.datetime.strptime(request.GET['f'], '%d-%b-%Y %H:%M')
@view_config(
request_method="GET",
route_name="v1_sale_analysis",
renderer="json",
permission="Sales Analysis",
)
def get_sale_analysis(request):
start_date = get_start_date(request.GET.get("s", None))
finish_date = get_finish_date(request.GET.get("f", None))
if (datetime.date.today() - start_date.date()).days > 5 and 'Accounts Audit' not in request.effective_principals:
raise HTTPForbidden("Accounts Audit")
if (
datetime.today() - start_date.replace(hour=0)
).days > 5 and "Accounts Audit" not in request.effective_principals:
raise ValidationError("Accounts Audit")
amount = func.sum(Inventory.quantity * Inventory.effective_price * (1 - Inventory.discount)).label('Amount')
list = request.dbsession.query(
MenuCategory.group_type, amount
).join(Voucher.kots).join(Kot.inventories).join(Inventory.product).join(Product.menu_category).filter(
return {
"startDate": start_date.date().strftime("%d-%b-%Y"),
"finishDate": (finish_date - timedelta(days=1)).date().strftime("%d-%b-%Y"),
"amounts": (
get_sale(start_date, finish_date, request.dbsession)
+ [{"name": "--", "amount": 0}]
+ get_settlements(start_date, finish_date, request.dbsession)
+ [{"name": "--", "amount": 0}]
+ get_tax(start_date, finish_date, request.dbsession)
),
}
@view_config(
request_method="GET",
route_name="v1_sa_sale",
renderer="json",
permission="Sales Analysis",
)
def get_sale_view(request):
start_date = get_start_date(request.GET.get("s", None))
finish_date = get_finish_date(request.GET.get("f", None))
if (
datetime.today() - start_date.replace(hour=0)
).days > 5 and "Accounts Audit" not in request.effective_principals:
raise ValidationError("Accounts Audit")
return {
"startDate": start_date.date().strftime("%d-%b-%Y"),
"finishDate": (finish_date - timedelta(days=1)).date().strftime("%d-%b-%Y"),
"amounts": get_sale(start_date, finish_date, request.dbsession),
}
def get_sale(start_date, finish_date, dbsession):
list_ = (
dbsession.query(SaleCategory.name, func.sum(Inventory.net))
.join(Inventory.kot)
.join(Kot.voucher)
.join(Inventory.product)
.join(Product.sale_category)
.filter(
Voucher.date >= start_date,
Voucher.date <= finish_date,
Voucher.is_void == False,
Voucher.settlements.any(~Settlement.settled.in_([1, 4, 7, 8, 9, 10]))
).group_by(
MenuCategory.group_type
).order_by(
MenuCategory.group_type
).all()
Voucher.voucher_type == VoucherType.REGULAR_BILL.value,
)
.group_by(SaleCategory.name)
.order_by(SaleCategory.name)
.all()
)
total = 0
info = []
for gt, am in list:
for gt, am in list_:
total += am
info.append({'GroupType': gt, 'Amount': am})
return info + [{'GroupType': 'Total Settled', 'Amount': total}]
info.append({"name": gt, "amount": am})
return info + [{"name": "Total Settled", "amount": total}]
@view_config(request_method='GET', route_name='sa_settlements', renderer='json', permission='Sales Analysis',
request_param=('s', 'f'))
def get_settlements(request):
start_date = datetime.datetime.strptime(request.GET['s'], '%d-%b-%Y %H:%M')
finish_date = datetime.datetime.strptime(request.GET['f'], '%d-%b-%Y %H:%M')
@view_config(
request_method="GET",
route_name="v1_sa_settlements",
renderer="json",
permission="Sales Analysis",
)
def get_settlements_view(request):
start_date = get_start_date(request.GET.get("s", None))
finish_date = get_finish_date(request.GET.get("f", None))
if (datetime.date.today() - start_date.date()).days > 5 and 'Accounts Audit' not in request.effective_principals:
raise HTTPForbidden("Accounts Audit")
if (
datetime.today() - start_date.replace(hour=0)
).days > 5 and "Accounts Audit" not in request.effective_principals:
raise ValidationError("Accounts Audit")
list = request.dbsession.query(
SettleOption.name, func.sum(Settlement.amount)
).join(Voucher.settlements).join(Settlement.settle_option).filter(
Voucher.date >= start_date,
Voucher.date <= finish_date,
Voucher.is_void == False
).group_by(
SettleOption.name
).order_by(
SettleOption.name
).all()
return {
"startDate": start_date.date().strftime("%d-%b-%Y"),
"finishDate": (finish_date - timedelta(days=1)).date().strftime("%d-%b-%Y"),
"amounts": get_settlements(start_date, finish_date, request.dbsession),
}
def get_settlements(start_date, finish_date, dbsession):
list_ = (
dbsession.query(SettleOption.name, func.sum(Settlement.amount))
.join(Voucher.settlements)
.join(Settlement.settle_option)
.filter(Voucher.date >= start_date, Voucher.date <= finish_date)
.group_by(SettleOption.name)
.order_by(SettleOption.name)
.all()
)
total = 0
info = []
for gt, am in list:
for gt, am in list_:
total += am
info.append({'GroupType': gt, 'Amount': am})
return info + [{'GroupType': 'Total', 'Amount': total}]
info.append({"name": gt, "amount": am})
return info + [{"name": "Total", "amount": total}]
@view_config(request_method='GET', route_name='sa_tax', renderer='json', permission=('Tax Analysis', 'Sales Analysis'),
request_param=('s', 'f'))
def get_tax(request):
start_date = datetime.datetime.strptime(request.GET['s'], '%d-%b-%Y %H:%M')
finish_date = datetime.datetime.strptime(request.GET['f'], '%d-%b-%Y %H:%M')
@view_config(
request_method="GET",
route_name="v1_sa_tax",
renderer="json",
permission=("Tax Analysis", "Sales Analysis"),
)
def get_tax_view(request):
start_date = request.GET.get("s", None)
if not start_date:
start_date = datetime.today().replace(hour=7, minute=0)
else:
start_date = datetime.strptime(start_date, "%d-%b-%Y").replace(hour=7, minute=0)
if (datetime.date.today() - start_date.date()).days > 5 and 'Accounts Audit' not in request.effective_principals:
raise HTTPForbidden("Accounts Audit")
finish_date = request.GET.get("f", None)
if not finish_date:
finish_date = datetime.today().replace(hour=7, minute=0) + timedelta(days=1)
else:
finish_date = datetime.strptime(finish_date, "%d-%b-%Y").replace(
hour=7, minute=0
) + timedelta(days=1)
amounts = request.dbsession.query(
if (
datetime.date().today() - start_date.date()
).days > 5 and "Accounts Audit" not in request.effective_principals:
raise ValidationError("Accounts Audit")
return {
"startDate": start_date.date().strftime("%d-%b-%Y"),
"finishDate": (finish_date - timedelta(days=1)).date().strftime("%d-%b-%Y"),
"amounts": get_settlements(start_date, finish_date, request.dbsession),
}
def get_tax(start_date, finish_date, dbsession):
amounts = (
dbsession.query(
Tax.name,
Inventory.tax_rate,
func.coalesce(func.sum(Inventory.net_taxable), 0),
func.coalesce(func.sum(Inventory.tax_amount), 0)
).join(Voucher.kots).join(Kot.inventories).join(Inventory.tax).filter(
func.coalesce(func.sum(Inventory.net), 0),
func.coalesce(func.sum(Inventory.tax_amount), 0),
)
.join(Voucher.kots)
.join(Kot.inventories)
.join(Inventory.tax)
.filter(
Voucher.date >= start_date,
Voucher.date <= finish_date,
Voucher.is_void == False,
Voucher.settlements.any(~Settlement.settled.in_([1, 4, 7, 8, 9, 10]))
).group_by(
Tax.name,
Inventory.tax_rate
).order_by(
Tax.name,
Inventory.tax_rate
).all()
return [{
'Name': "{0} - {1:.2%}".format(i[0], i[1]),
'TaxRate': i[1],
'NetSale': i[2],
'TaxAmount': i[3]
} for i in amounts]
Voucher.voucher_type == VoucherType.REGULAR_BILL.value,
)
.group_by(Tax.name, Inventory.tax_rate)
.order_by(Tax.name, Inventory.tax_rate)
.all()
)
return [
{
"name": "{0} - {1:.2%}".format(i[0], i[1]),
"taxRate": i[1],
"netSale": i[2],
"amount": i[3],
}
for i in amounts
]

View File

@ -45,6 +45,10 @@ const routes: Routes = [
path: 'sales',
loadChildren: () => import('./sales/sales.module').then(mod => mod.SalesModule)
},
{
path: 'sale-analysis',
loadChildren: () => import('./sale-analysis/sale-analysis.module').then(mod => mod.SaleAnalysisModule)
},
{
path: 'sale-categories',
loadChildren: () => import('./sale-category/sale-categories.module').then(mod => mod.SaleCategoriesModule)

View File

@ -1,7 +1,7 @@
import { BrowserModule } from '@angular/platform-browser';
import { LOCALE_ID, NgModule } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import { HttpClientModule } from "@angular/common/http";
import { HttpClientModule } from '@angular/common/http';
import enIN from '@angular/common/locales/en-IN';
import { AppRoutingModule } from './app-routing.module';

View File

@ -2,7 +2,7 @@ import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/internal/Observable';
import { CashierCheckoutService } from './cashier-checkout.service';
import { User } from "../core/user";
import { User } from '../core/user';
@Injectable({
providedIn: 'root'

View File

@ -1,13 +1,13 @@
import {CashierCheckoutRoutingModule} from './cashier-checkout-routing.module';
describe('CashierCheckoutRoutingModule', () => {
let CashierCheckoutRoutingModule: CashierCheckoutRoutingModule;
let cashierCheckoutRoutingModule: CashierCheckoutRoutingModule;
beforeEach(() => {
CashierCheckoutRoutingModule = new CashierCheckoutRoutingModule();
cashierCheckoutRoutingModule = new CashierCheckoutRoutingModule();
});
it('should create an instance', () => {
expect(CashierCheckoutRoutingModule).toBeTruthy();
expect(cashierCheckoutRoutingModule).toBeTruthy();
});
});

View File

@ -4,7 +4,7 @@ import { RouterModule, Routes } from '@angular/router';
import { CashierCheckoutResolver } from './cashier-checkout-resolver.service';
import { AuthGuard } from '../auth/auth-guard.service';
import { CashierCheckoutComponent } from './cashier-checkout.component';
import { ActiveCashiersResolver } from "./active-cashiers-resolver.service";
import { ActiveCashiersResolver } from './active-cashiers-resolver.service';
const CashierCheckoutRoutes: Routes = [
{

View File

@ -41,7 +41,7 @@
<!-- Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let row"><a [href]="row.url">{{row.name}}</a></mat-cell>
<mat-cell *matCellDef="let row">{{row.name}}</mat-cell>
</ng-container>
<!-- Amount Column -->

View File

@ -5,7 +5,7 @@ import * as moment from 'moment';
import { CashierCheckoutDataSource } from './cashier-checkout-datasource';
import { CashierCheckout } from './cashier-checkout';
import { ToCsvService } from '../shared/to-csv.service';
import { User } from "../core/user";
import { User } from '../core/user';
@Component({
selector: 'app-cashier-checkout',
@ -48,7 +48,11 @@ export class CashierCheckoutComponent implements OnInit {
show() {
const info = this.getInfo();
this.router.navigate(['checkout', this.form.value.cashier], {
const url = ['checkout'];
if (!!info.user.id) {
url.push(info.user.id);
}
this.router.navigate(url, {
queryParams: {
startDate: info.startDate,
finishDate: info.finishDate
@ -68,7 +72,7 @@ export class CashierCheckoutComponent implements OnInit {
const formModel = this.form.value;
return {
user: formModel.cashier,
user: new User({id: formModel.cashier}),
startDate: moment(formModel.startDate).format('DD-MMM-YYYY'),
finishDate: moment(formModel.finishDate).format('DD-MMM-YYYY')
};

View File

@ -1,13 +1,13 @@
import {CashierCheckoutModule} from './cashier-checkout.module';
describe('CashierCheckoutModule', () => {
let CashierCheckoutModule: CashierCheckoutModule;
let cashierCheckoutModule: CashierCheckoutModule;
beforeEach(() => {
CashierCheckoutModule = new CashierCheckoutModule();
cashierCheckoutModule = new CashierCheckoutModule();
});
it('should create an instance', () => {
expect(CashierCheckoutModule).toBeTruthy();
expect(cashierCheckoutModule).toBeTruthy();
});
});

View File

@ -21,7 +21,7 @@ import { CashierCheckoutComponent } from './cashier-checkout.component';
import { MomentDateAdapter } from '@angular/material-moment-adapter';
import { A11yModule } from '@angular/cdk/a11y';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MatSelectModule } from "@angular/material";
import { MatSelectModule } from '@angular/material';
export const MY_FORMATS = {
parse: {

View File

@ -4,7 +4,7 @@ import { Observable } from 'rxjs/internal/Observable';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { CashierCheckout } from './cashier-checkout';
import { ErrorLoggerService } from '../core/error-logger.service';
import {User} from "../core/user";
import { User } from '../core/user';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})

View File

@ -1,4 +1,4 @@
import {User} from "../core/user";
import { User } from '../core/user';
export class CashierCheckoutPrintItem {
date: string;

View File

@ -14,6 +14,9 @@
<mat-card fxLayout="column" class="square-button" matRipple [routerLink]="['/', 'checkout']">
<h3 class="item-name">Cashier Checkout</h3>
</mat-card>
<mat-card fxLayout="column" class="square-button" matRipple [routerLink]="['/', 'sale-analysis']">
<h3 class="item-name">Sale Analysis</h3>
</mat-card>
<mat-card fxLayout="column" class="square-button" matRipple [routerLink]="['/', 'tables']">
<h3 class="item-name">Tables</h3>
</mat-card>

View File

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

View File

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

View File

@ -0,0 +1,20 @@
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/internal/Observable';
import {SaleAnalysis} from './sale-analysis';
import {SaleAnalysisService} from './sale-analysis.service';
@Injectable({
providedIn: 'root'
})
export class SaleAnalysisResolver implements Resolve<SaleAnalysis> {
constructor(private ser: SaleAnalysisService) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<SaleAnalysis> {
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 {SaleAnalysisRoutingModule} from './sale-analysis-routing.module';
describe('SaleAnalysisRoutingModule', () => {
let saleAnalysisRoutingModule: SaleAnalysisRoutingModule;
beforeEach(() => {
saleAnalysisRoutingModule = new SaleAnalysisRoutingModule();
});
it('should create an instance', () => {
expect(saleAnalysisRoutingModule).toBeTruthy();
});
});

View File

@ -0,0 +1,37 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { SaleAnalysisResolver } from './sale-analysis-resolver.service';
import { AuthGuard } from '../auth/auth-guard.service';
import { SaleAnalysisComponent } from './sale-analysis.component';
const SaleAnalysisRoutes: Routes = [
{
path: '',
component: SaleAnalysisComponent,
canActivate: [AuthGuard],
data: {
permission: 'Sales Analysis'
},
resolve: {
info: SaleAnalysisResolver
},
runGuardsAndResolvers: 'always'
}
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(SaleAnalysisRoutes)
],
exports: [
RouterModule
],
providers: [
SaleAnalysisResolver
]
})
export class SaleAnalysisRoutingModule {
}

View File

@ -0,0 +1,4 @@
.right {
display: flex;
justify-content: flex-end;
}

View File

@ -0,0 +1,44 @@
<mat-card>
<mat-card-title-group>
<mat-card-title>Sale Analysis</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">
<!-- 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>
<!-- Amount Column -->
<ng-container matColumnDef="amount">
<mat-header-cell *matHeaderCellDef class="right">Amount</mat-header-cell>
<mat-cell *matCellDef="let row" class="right">{{row.amount | currency:'INR'}}</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,25 @@
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {SaleAnalysisComponent} from './sale-analysis.component';
describe('SaleAnalysisComponent', () => {
let component: SaleAnalysisComponent;
let fixture: ComponentFixture<SaleAnalysisComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SaleAnalysisComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SaleAnalysisComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,90 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { SaleAnalysisDataSource } from './sale-analysis-datasource';
import { SaleAnalysis } from './sale-analysis';
import { ToCsvService } from '../shared/to-csv.service';
@Component({
selector: 'app-sale-analysis',
templateUrl: './sale-analysis.component.html',
styleUrls: ['./sale-analysis.component.css']
})
export class SaleAnalysisComponent implements OnInit {
dataSource: SaleAnalysisDataSource;
form: FormGroup;
info: SaleAnalysis;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['name', 'amount'];
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private toCsv: ToCsvService
) {
this.createForm();
}
ngOnInit() {
this.route.data
.subscribe((data: { info: SaleAnalysis }) => {
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 SaleAnalysisDataSource(this.info.amounts);
});
}
show() {
const info = this.getInfo();
this.router.navigate(['sale-analysis'], {
queryParams: {
startDate: info.startDate,
finishDate: info.finishDate
}
});
}
createForm() {
this.form = this.fb.group({
startDate: '',
finishDate: ''
});
}
getInfo(): SaleAnalysis {
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 = {
Date: 'date',
Name: 'name',
Type: 'type',
Narration: 'narration',
Debit: 'debit',
Credit: 'credit',
Running: 'running',
Posted: 'posted'
};
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', 'sale-analysis.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}

View File

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

View File

@ -0,0 +1,61 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
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 { ReactiveFormsModule } from '@angular/forms';
import { CdkTableModule } from '@angular/cdk/table';
import { SaleAnalysisRoutingModule } from './sale-analysis-routing.module';
import { SaleAnalysisComponent } from './sale-analysis.component';
import { MomentDateAdapter } from '@angular/material-moment-adapter';
import { A11yModule } from '@angular/cdk/a11y';
import { FlexLayoutModule } from '@angular/flex-layout';
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,
SaleAnalysisRoutingModule
],
declarations: [
SaleAnalysisComponent
],
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
]
})
export class SaleAnalysisModule {
}

View File

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

View File

@ -0,0 +1,36 @@
import { Injectable } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { Observable } from 'rxjs/internal/Observable';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { SaleAnalysis } from './sale-analysis';
import { ErrorLoggerService } from '../core/error-logger.service';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
const url = '/v1/sale-analysis';
const serviceName = 'SaleAnalysisService';
@Injectable({
providedIn: 'root'
})
export class SaleAnalysisService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {
}
get(startDate: string, finishDate): Observable<SaleAnalysis> {
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<SaleAnalysis>>this.http.get<SaleAnalysis>(url, options)
.pipe(
catchError(this.log.handleError(serviceName, 'list'))
);
}
}

View File

@ -0,0 +1,10 @@
export class SaleAnalysisItem {
name: string;
amount: number;
}
export class SaleAnalysis {
startDate: string;
finishDate: string;
amounts?: SaleAnalysisItem[];
}

View File

@ -11,7 +11,7 @@ import { Bill, Inventory, Kot, PrintType } from './bills/bill';
import { VoucherService } from './bills/voucher.service';
import { ToasterService } from '../core/toaster.service';
import { Table } from '../core/table';
import { SelectionModel } from "@angular/cdk/collections";
import { SelectionModel } from '@angular/cdk/collections';
@Injectable()
export class BillService {
@ -184,7 +184,7 @@ export class BillService {
printKot(guest_book_id: string): Observable<boolean> {
const item = JSON.parse(JSON.stringify(this.bill));
const newKot = this.getKot();
if (newKot.inventories.length == 0) {
if (newKot.inventories.length === 0) {
this.toaster.show('Error', 'Cannot print a blank KOT\nPlease add some products!');
}
item.kots.push(newKot);
@ -262,7 +262,7 @@ export class BillService {
}
splitBill(table: Table): Observable<boolean> {
const inventoriesToMove: string[] = this.selection.selected.map((x:any)=> x.id)
const inventoriesToMove: string[] = this.selection.selected.map((x: any) => x.id);
return this.ser.splitBill(this.bill.id, inventoriesToMove, table);
}
}

View File

@ -12,8 +12,8 @@ import { map, switchMap } from 'rxjs/operators';
import { TablesDialogComponent } from '../tables-dialog/tables-dialog.component';
import { TableService } from '../../tables/table.service';
import { ToasterService } from '../../core/toaster.service';
import { AuthService } from "../../auth/auth.service";
import { SelectionModel } from "@angular/cdk/collections";
import { AuthService } from '../../auth/auth.service';
import { SelectionModel } from '@angular/cdk/collections';
@Component({
selector: 'app-bills',
@ -56,8 +56,8 @@ export class BillsComponent implements OnInit {
}
isAnySelected(kot: Kot) {
let total: number = 0,
found: number = 0;
let total = 0,
found = 0;
this.bs.data.filter(
x => x.kotId === kot.id
).forEach((c: any) => {
@ -118,7 +118,7 @@ export class BillsComponent implements OnInit {
}
moveKot(kot: Kot) {
const canMergeTables = this.auth.hasPermission("Merge Tables");
const canMergeTables = this.auth.hasPermission('Merge Tables');
this.dialog.open(TablesDialogComponent, {
// width: '750px',
data: {

View File

@ -160,7 +160,7 @@ export class SalesHomeComponent implements OnInit {
}
moveTable() {
const canMergeTables = this.auth.hasPermission("Merge Tables");
const canMergeTables = this.auth.hasPermission('Merge Tables');
this.dialog.open(TablesDialogComponent, {
// width: '750px',
data: {
@ -296,7 +296,7 @@ export class SalesHomeComponent implements OnInit {
return false;
}
if (this.bs.bill.voucherType === PrintType.Kot) {
return false
return false;
}
if (this.bs.bill.isVoid) {
return false;

View File

@ -91,7 +91,7 @@ export class ReceivePaymentComponent {
(z, i) => array.controls[i].valueChanges.pipe(
distinctUntilChanged()
).subscribe(x => {
this.choices[this.type].find(s => s.name == x.name).amount = (x.amount === '' ? 0 : parseInt(x.amount, 10));
this.choices[this.type].find(s => s.name === x.name).amount = (x.amount === '' ? 0 : parseInt(x.amount, 10));
this.balance = this.amount - this.choices[this.type].reduce((a, c) => a + c.amount, 0);
})
);

View File

@ -19,7 +19,7 @@ requires = [
]
setup(name='barker',
version='1.0.0-alpha.3',
version='1.0.0-alpha.4',
description='barker',
long_description=README + '\n\n' + CHANGES,
classifiers=[