Feature: Adding recipe templates to print recipes.

Feautre: Recipe export to xlsx
Chore: Python 11 style type annotations
Chore: Moved to sqlalchemy 2.0
Chore: Minimum python is 3.11
Fix: Fix nullability of a lot of fields in the database.
This commit is contained in:
2023-07-23 08:12:21 +05:30
parent d2d26ab1ae
commit 22cac61761
344 changed files with 3247 additions and 2370 deletions

View File

@ -0,0 +1,41 @@
<div class="flex flex-auto flex-row justify-around content-center items-center lg:max-w-[50%]">
<mat-card class="flex-auto">
<mat-card-header>
<mat-card-title>RecipeTemplate</mat-card-title>
</mat-card-header>
<mat-card-content>
<form [formGroup]="form" class="flex flex-col">
<div class="flex flex-row justify-around content-start items-start">
<mat-form-field class="flex-auto">
<mat-label>Name</mat-label>
<input matInput #nameElement formControlName="name" />
</mat-form-field>
<mat-form-field class="flex-auto">
<mat-label>Date</mat-label>
<input
matInput
[matDatepicker]="date"
formControlName="date"
autocomplete="off"
#dateElement
(focus)="dateElement.select()"
/>
<mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
<mat-datepicker #date></mat-datepicker>
</mat-form-field>
<mat-checkbox formControlName="selected" class="flex-auto">Is Selected?</mat-checkbox>
</div>
<div class="flex flex-row justify-around content-start items-start">
<mat-form-field class="flex-auto">
<mat-label>Text</mat-label>
<textarea matInput matAutosizeMinRows="20" formControlName="text"></textarea>
</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,28 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { MatDialogModule } from '@angular/material/dialog';
import { RouterTestingModule } from '@angular/router/testing';
import { RecipeTemplateDetailComponent } from './recipe-template-detail.component';
describe('RecipeTemplateDetailComponent', () => {
let component: RecipeTemplateDetailComponent;
let fixture: ComponentFixture<RecipeTemplateDetailComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatDialogModule, ReactiveFormsModule, RouterTestingModule],
declarations: [RecipeTemplateDetailComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RecipeTemplateDetailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,114 @@
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { ToasterService } from '../../core/toaster.service';
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
import { RecipeTemplate } from '../recipe-template';
import { RecipeTemplateService } from '../recipe-template.service';
@Component({
selector: 'app-recipe-template-detail',
templateUrl: './recipe-template-detail.component.html',
styleUrls: ['./recipe-template-detail.component.css'],
})
export class RecipeTemplateDetailComponent implements OnInit, AfterViewInit {
@ViewChild('nameElement', { static: true }) nameElement?: ElementRef;
form: FormGroup<{
name: FormControl<string>;
date: FormControl<Date>;
text: FormControl<string>;
selected: FormControl<boolean>;
}>;
item: RecipeTemplate = new RecipeTemplate();
constructor(
private route: ActivatedRoute,
private router: Router,
private dialog: MatDialog,
private toaster: ToasterService,
private ser: RecipeTemplateService,
) {
this.form = new FormGroup({
name: new FormControl<string>('', { nonNullable: true }),
date: new FormControl(new Date(), { nonNullable: true }),
text: new FormControl<string>('', { nonNullable: true }),
selected: new FormControl<boolean>(false, { nonNullable: true }),
});
}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { item: RecipeTemplate };
this.showItem(data.item);
});
}
showItem(item: RecipeTemplate) {
this.item = item;
this.form.setValue({
name: this.item.name,
date: moment(this.item.date, 'DD-MMM-YYYY').toDate(),
text: this.item.text,
selected: this.item.selected,
});
}
ngAfterViewInit() {
setTimeout(() => {
if (this.nameElement) {
this.nameElement.nativeElement.focus();
}
}, 0);
}
save() {
this.ser.saveOrUpdate(this.getItem()).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/recipe-templates');
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
delete() {
this.ser.delete(this.item.id).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/recipe-templates');
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
confirmDelete(): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: { title: 'Delete Recipe Template?', content: 'Are you sure? This cannot be undone.' },
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.delete();
}
});
}
getItem(): RecipeTemplate {
const formModel = this.form.value;
this.item.name = formModel.name ?? '';
this.item.date = moment(formModel.date).format('DD-MMM-YYYY');
this.item.text = formModel.text ?? '';
this.item.selected = formModel.selected ?? false;
return this.item;
}
}

View File

@ -0,0 +1,21 @@
import { HttpClientModule } from '@angular/common/http';
import { inject, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { RecipeTemplateListResolver } from './recipe-template-list-resolver.service';
describe('RecipeTemplateListResolver', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule, RouterTestingModule],
providers: [RecipeTemplateListResolver],
});
});
it('should be created', inject(
[RecipeTemplateListResolver],
(service: RecipeTemplateListResolver) => {
expect(service).toBeTruthy();
},
));
});

View File

@ -0,0 +1,16 @@
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import { RecipeTemplate } from './recipe-template';
import { RecipeTemplateService } from './recipe-template.service';
@Injectable({
providedIn: 'root',
})
export class RecipeTemplateListResolver {
constructor(private ser: RecipeTemplateService) {}
resolve(): Observable<RecipeTemplate[]> {
return this.ser.list();
}
}

View File

@ -0,0 +1,72 @@
import { DataSource } from '@angular/cdk/collections';
import { EventEmitter } from '@angular/core';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatSort, Sort } from '@angular/material/sort';
import { merge, Observable, of as observableOf } from 'rxjs';
import { map } from 'rxjs/operators';
import { RecipeTemplate } from '../recipe-template';
/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
const compare = (a: string | number, b: string | number, isAsc: boolean) =>
(a < b ? -1 : 1) * (isAsc ? 1 : -1);
export class RecipeTemplateListDataSource extends DataSource<RecipeTemplate> {
constructor(
public data: RecipeTemplate[],
private paginator?: MatPaginator,
private sort?: MatSort,
) {
super();
}
connect(): Observable<RecipeTemplate[]> {
const dataMutations: (EventEmitter<PageEvent> | EventEmitter<Sort>)[] = [];
if (this.paginator) {
dataMutations.push((this.paginator as MatPaginator).page);
}
if (this.sort) {
dataMutations.push((this.sort as MatSort).sortChange);
}
// Set the paginators length
if (this.paginator) {
this.paginator.length = this.data.length;
}
return merge(observableOf(this.data), ...dataMutations).pipe(
map(() => this.getPagedData(this.getSortedData([...this.data]))),
);
}
disconnect() {}
private getPagedData(data: RecipeTemplate[]) {
if (this.paginator === undefined) {
return data;
}
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
private getSortedData(data: RecipeTemplate[]) {
if (this.sort === undefined) {
return data;
}
if (!this.sort.active || this.sort.direction === '') {
return data;
}
const sort = this.sort as MatSort;
return data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
case 'name':
return compare(a.name, b.name, isAsc);
case 'id':
return compare(+a.id, +b.id, isAsc);
default:
return 0;
}
});
}
}

View File

@ -0,0 +1,46 @@
<mat-card>
<mat-card-header>
<mat-card-title-group>
<mat-card-title>Recipe Templates</mat-card-title>
<a mat-button [routerLink]="['/recipe-templates', 'new']">
<mat-icon>add_box</mat-icon>
Add
</a>
</mat-card-title-group>
</mat-card-header>
<mat-card-content>
<mat-table #table [dataSource]="dataSource" matSort aria-label="Elements">
<!-- Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef mat-sort-header>Name</mat-header-cell>
<mat-cell *matCellDef="let row"
><a [routerLink]="['/recipe-templates', row.id]">{{ row.name }}</a></mat-cell
>
</ng-container>
<!-- Selected Column -->
<ng-container matColumnDef="selected">
<mat-header-cell *matHeaderCellDef mat-sort-header>Is Selected?</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row.selected }}</mat-cell>
</ng-container>
<!-- Date Column -->
<ng-container matColumnDef="date">
<mat-header-cell *matHeaderCellDef mat-sort-header>Date</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row.date }}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
<mat-paginator
#paginator
[length]="dataSource.data.length"
[pageIndex]="0"
[pageSize]="50"
[pageSizeOptions]="[25, 50, 100, 250]"
>
</mat-paginator>
</mat-card-content>
</mat-card>

View File

@ -0,0 +1,24 @@
import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { RecipeTemplateListComponent } from './recipe-template-list.component';
describe('RecipeTemplateListComponent', () => {
let component: RecipeTemplateListComponent;
let fixture: ComponentFixture<RecipeTemplateListComponent>;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [RecipeTemplateListComponent],
}).compileComponents();
fixture = TestBed.createComponent(RecipeTemplateListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should compile', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,33 @@
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ActivatedRoute } from '@angular/router';
import { RecipeTemplate } from '../recipe-template';
import { RecipeTemplateListDataSource } from './recipe-template-list-datasource';
@Component({
selector: 'app-recipe-template-list',
templateUrl: './recipe-template-list.component.html',
styleUrls: ['./recipe-template-list.component.css'],
})
export class RecipeTemplateListComponent implements OnInit {
@ViewChild(MatPaginator, { static: true }) paginator?: MatPaginator;
@ViewChild(MatSort, { static: true }) sort?: MatSort;
list: RecipeTemplate[] = [];
dataSource: RecipeTemplateListDataSource = new RecipeTemplateListDataSource(this.list);
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['name', 'selected', 'date'];
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { list: RecipeTemplate[] };
this.list = data.list;
});
this.dataSource = new RecipeTemplateListDataSource(this.list, this.paginator, this.sort);
}
}

View File

@ -0,0 +1,18 @@
import { HttpClientModule } from '@angular/common/http';
import { inject, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { RecipeTemplateResolver } from './recipe-template-resolver.service';
describe('RecipeTemplateResolver', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule, RouterTestingModule],
providers: [RecipeTemplateResolver],
});
});
it('should be created', inject([RecipeTemplateResolver], (service: RecipeTemplateResolver) => {
expect(service).toBeTruthy();
}));
});

View File

@ -0,0 +1,18 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/internal/Observable';
import { RecipeTemplate } from './recipe-template';
import { RecipeTemplateService } from './recipe-template.service';
@Injectable({
providedIn: 'root',
})
export class RecipeTemplateResolver {
constructor(private ser: RecipeTemplateService) {}
resolve(route: ActivatedRouteSnapshot): Observable<RecipeTemplate> {
const id = route.paramMap.get('id');
return this.ser.get(id);
}
}

View File

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

View File

@ -0,0 +1,62 @@
import { CommonModule } from '@angular/common';
import { NgModule, inject } from '@angular/core';
import { ActivatedRouteSnapshot, RouterModule, RouterStateSnapshot, Routes } from '@angular/router';
import { AuthGuard } from '../auth/auth-guard.service';
import { RecipeTemplateDetailComponent } from './recipe-template-detail/recipe-template-detail.component';
import { RecipeTemplateListComponent } from './recipe-template-list/recipe-template-list.component';
import { RecipeTemplateListResolver } from './recipe-template-list-resolver.service';
import { RecipeTemplateResolver } from './recipe-template-resolver.service';
const recipeTemplateRoutes: Routes = [
{
path: '',
component: RecipeTemplateListComponent,
canActivate: [
(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) =>
inject(AuthGuard).canActivate(route, state),
],
data: {
permission: 'Recipes',
},
resolve: {
list: () => inject(RecipeTemplateListResolver).resolve(),
},
},
{
path: 'new',
component: RecipeTemplateDetailComponent,
canActivate: [
(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) =>
inject(AuthGuard).canActivate(route, state),
],
data: {
permission: 'Recipes',
},
resolve: {
item: (route: ActivatedRouteSnapshot) => inject(RecipeTemplateResolver).resolve(route),
},
},
{
path: ':id',
component: RecipeTemplateDetailComponent,
canActivate: [
(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) =>
inject(AuthGuard).canActivate(route, state),
],
data: {
permission: 'Recipes',
},
resolve: {
item: (route: ActivatedRouteSnapshot) => inject(RecipeTemplateResolver).resolve(route),
},
},
];
@NgModule({
imports: [CommonModule, RouterModule.forChild(recipeTemplateRoutes)],
exports: [RouterModule],
providers: [RecipeTemplateListResolver, RecipeTemplateResolver],
})
export class RecipeTemplateRoutingModule {}

View File

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

View File

@ -0,0 +1,66 @@
import { CdkTableModule } from '@angular/cdk/table';
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import {
DateAdapter,
MAT_DATE_FORMATS,
MAT_DATE_LOCALE,
MatNativeDateModule,
} from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MomentDateAdapter } from '@angular/material-moment-adapter';
import { SharedModule } from '../shared/shared.module';
import { RecipeTemplateDetailComponent } from './recipe-template-detail/recipe-template-detail.component';
import { RecipeTemplateListComponent } from './recipe-template-list/recipe-template-list.component';
import { RecipeTemplateRoutingModule } from './recipe-template-routing.module';
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: [
CommonModule,
CdkTableModule,
MatButtonModule,
MatCardModule,
MatCheckboxModule,
MatDatepickerModule,
MatIconModule,
MatInputModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatSortModule,
MatTableModule,
ReactiveFormsModule,
SharedModule,
RecipeTemplateRoutingModule,
],
declarations: [RecipeTemplateListComponent, RecipeTemplateDetailComponent],
providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
],
})
export class RecipeTemplateModule {}

View File

@ -0,0 +1,17 @@
import { HttpClientModule } from '@angular/common/http';
import { inject, TestBed } from '@angular/core/testing';
import { RecipeTemplateService } from './recipe-template.service';
describe('RecipeTemplateService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule],
providers: [RecipeTemplateService],
});
});
it('should be created', inject([RecipeTemplateService], (service: RecipeTemplateService) => {
expect(service).toBeTruthy();
}));
});

View File

@ -0,0 +1,58 @@
import { HttpClient } 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 { RecipeTemplate } from './recipe-template';
const url = '/api/recipe-templates';
const serviceName = 'RecipeTemplateService';
@Injectable({
providedIn: 'root',
})
export class RecipeTemplateService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
get(id: string | null): Observable<RecipeTemplate> {
const getUrl: string = id === null ? url : `${url}/${id}`;
return this.http
.get<RecipeTemplate>(getUrl)
.pipe(
catchError(this.log.handleError(serviceName, `get id=${id}`)),
) as Observable<RecipeTemplate>;
}
list(): Observable<RecipeTemplate[]> {
return this.http
.get<RecipeTemplate[]>(`${url}/list`)
.pipe(catchError(this.log.handleError(serviceName, 'list'))) as Observable<RecipeTemplate[]>;
}
save(recipeTemplate: RecipeTemplate): Observable<RecipeTemplate> {
return this.http
.post<RecipeTemplate>(`${url}`, recipeTemplate)
.pipe(catchError(this.log.handleError(serviceName, 'save'))) as Observable<RecipeTemplate>;
}
update(recipeTemplate: RecipeTemplate): Observable<RecipeTemplate> {
return this.http
.put<RecipeTemplate>(`${url}/${recipeTemplate.id}`, recipeTemplate)
.pipe(catchError(this.log.handleError(serviceName, 'update'))) as Observable<RecipeTemplate>;
}
saveOrUpdate(recipeTemplate: RecipeTemplate): Observable<RecipeTemplate> {
if (!recipeTemplate.id) {
return this.save(recipeTemplate);
}
return this.update(recipeTemplate);
}
delete(id: string): Observable<RecipeTemplate> {
return this.http
.delete<RecipeTemplate>(`${url}/${id}`)
.pipe(catchError(this.log.handleError(serviceName, 'delete'))) as Observable<RecipeTemplate>;
}
}

View File

@ -0,0 +1,16 @@
export class RecipeTemplate {
id: string;
name: string;
date: string;
text: string;
selected: boolean;
public constructor(init?: Partial<RecipeTemplate>) {
this.id = '';
this.name = '';
this.date = '';
this.text = '';
this.selected = false;
Object.assign(this, init);
}
}