Skip to content

Commit

Permalink
Merge pull request #19 from bozzelliandrea/orders
Browse files Browse the repository at this point in the history
Orders
  • Loading branch information
bozzelliandrea authored Jul 10, 2022
2 parents 6f1c6a6 + 7a94d30 commit 501b560
Show file tree
Hide file tree
Showing 9 changed files with 195 additions and 61 deletions.
4 changes: 2 additions & 2 deletions @types/global/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ declare global {

function readOrder(id: string): Promise<Order>;

function deleteOrder(id: string): Promise<Order>;
function deleteOrder(id: string): Promise<boolean>;

function deleteOrders(ids: string[]): Promise<Order[]>;
function deleteOrders(ids: string[]): Promise<boolean>;

function readMenuItems(): Promise<MenuItem[]>;
}
Expand Down
141 changes: 121 additions & 20 deletions api/lib/io.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const fs = require("fs");
const {Notification} = require('electron');
const os = require("os");
const readline = require('readline');
const {uuidv4, removeElement} = require('./commons');
const {uuidv4, removeElement, updateElement} = require('./commons');
const platesFilePath = `${os.homedir()}/Documents/plate-config.txt`;
const ordersFilePath = `${os.homedir()}/Documents/orders.txt`;
const menuItemsFilePath = `${os.homedir()}/Documents/menu-items.txt`;
Expand Down Expand Up @@ -74,8 +74,9 @@ async function deletePlateById(_, id) {
}

if (foundIndex !== undefined) {
removeElement(lines, foundIndex)
fs.writeFile(platesFilePath, lines,
lines.splice(foundIndex, 1);
let linesAsString = lines.join("\r\n");
fs.writeFile(platesFilePath, linesAsString,
function (err, data) {
if (err) {
return Promise.reject("Fail to write config file: " + err);
Expand All @@ -90,8 +91,43 @@ async function deletePlateById(_, id) {
}
}

function updatePlate(_, config) {
// todo
async function updatePlate(_, config) {
try {
let foundIndex = undefined;

await fs.readFile(platesFilePath, 'utf8', function (err, data) {
if (err) {
return Promise.reject(err);
}

let lines = data.split('\r\n');
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (line !== "" && line.includes(`"_id":"${config._id}"`)) {
foundIndex = index;
break;
}
}

if (foundIndex !== undefined) {
lines[foundIndex] = `${JSON.stringify(config)}`;
let linesAsString = lines.join("\r\n");
fs.writeFile(platesFilePath, linesAsString,
function (err, data) {
if (err) {
return Promise.reject("Fail to write config file: " + err);
}

});
} else {
return Promise.resolve("Config not found");
}
});

return Promise.resolve(config);
} catch (e) {
return Promise.reject(e);
}
}

function _getReaderInterface(filePath) {
Expand All @@ -115,8 +151,6 @@ const filesAdded = () => {
async function addOrder(_, order) {
order._id = uuidv4();
const row = `${JSON.stringify(order)}\r\n`;
console.log(row);

await fs.appendFile(ordersFilePath, row, err => {
if (err) {
return Promise.resolve("Error!");
Expand All @@ -136,8 +170,7 @@ async function addOrders(_, orders) {
}

// display notification
// filesAdded();
return Promise.resolve("Saved!");
return Promise.resolve(orders);
}

async function readOrders(_) {
Expand Down Expand Up @@ -190,33 +223,101 @@ async function deleteOrderById(_, id) {
}

if (foundIndex !== undefined) {
removeElement(lines, foundIndex)
fs.writeFile(ordersFilePath, lines,
lines.splice(foundIndex, 1);
let linesAsString = lines.join("\r\n");
fs.writeFile(ordersFilePath, linesAsString,
function (err, data) {
if (err) {
return Promise.reject("Fail to write config file: " + err);
return Promise.reject("Fail to write order file: " + err);
}
});
} else {
return Promise.resolve("Plate configuration not found");
return Promise.resolve("Order not found");
}
});

return Promise.resolve(true);
} catch (e) {
return Promise.reject(e);
}
}

async function deleteOrdersByIds(_, ids) {
for (const idKey in ids) {
const id = ids[idKey];
await deleteOrderById(_, id);
}
try {
await fs.readFile(ordersFilePath, 'utf8', function (err, data) {
if (err) {
return Promise.reject(err);
}
let foundIndex = undefined;
let lines = data.split('\r\n');

for (let j = 0; j < ids.length; j++) {
const id = ids[j];

for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (line !== "" && line.includes(`"_id":"${id}"`)) {
foundIndex = index;
break;
}
}
if (foundIndex !== undefined) {
lines.splice(foundIndex, 1);
}
}

return Promise.resolve("Deleted!");
let linesAsString = lines.join("\r\n");
fs.writeFile(ordersFilePath, linesAsString,
function (err, data) {
if (err) {
return Promise.reject("Fail to write order file: " + err);
}
});
});

return Promise.resolve(true);
} catch (e) {
return Promise.reject(e);
}
}

function updateOrder(_, order) {
// todo
async function updateOrder(_, order) {
try {
let foundIndex = undefined;

await fs.readFile(ordersFilePath, 'utf8', function (err, data) {
if (err) {
return Promise.reject(err);
}

let lines = data.split('\r\n');
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (line !== "" && line.includes(`"_id":"${order._id}"`)) {
foundIndex = index;
break;
}
}

if (foundIndex !== undefined) {
lines[foundIndex] = `${JSON.stringify(order)}`;
let linesAsString = lines.join("\r\n");
fs.writeFile(ordersFilePath, linesAsString,
function (err, data) {
if (err) {
return Promise.reject("Fail to write order file: " + err);
}

});
} else {
return Promise.resolve("Order not found");
}
});

return Promise.resolve(order);
} catch (e) {
return Promise.reject(e);
}
}

async function readMenuItems(_) {
Expand Down
8 changes: 4 additions & 4 deletions src/app/modules/orders/order-new/order-new.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@ <h3>Insertion form</h3>
formControlName="quantity"
></p-inputNumber>
</div>
<div class="flex-row">
<label>Notes</label>
<textarea [rows]="5" [cols]="30" formControlName="notes" pInputTextarea autoResize="autoResize"></textarea>
</div>
<div class="flex-row">
<label>Plate</label>
<p-dropdown [options]="platesOptions" formControlName="plate" optionLabel="name"></p-dropdown>
</div>
<div class="flex-row">
<label>Notes</label>
<textarea [rows]="5" [cols]="30" formControlName="notes" pInputTextarea autoResize="autoResize"></textarea>
</div>
<div class="flex-row">
<button [disabled]="form?.valid ? !form?.valid : true"
[label]="i18n.COMMON.SAVE"
Expand Down
9 changes: 8 additions & 1 deletion src/app/modules/orders/order-new/order-new.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,18 @@ export class OrderNewComponent implements OnInit, OnDestroy {

private menuItemsSub: Subscription = new Subscription();
private platesSub: Subscription = new Subscription();
private readonly statuses: any[] = [];

constructor(private i18nService: I18nService, private ordersService: OrdersService,
private menuItemsService: MenuItemsService, @Inject('ApiConnector') private apiConnector: ApiConnector,
private datePipe: DatePipe, private router: Router) {
this.i18n = i18nService.instance;
this.statuses = [
{label: 'Todo', value: 'todo'},
{label: 'Progress', value: 'progress'},
{label: 'Done', value: 'done'},
{label: 'Cancelled', value: 'cancelled'}
];
}

ngOnInit(): void {
Expand Down Expand Up @@ -68,7 +75,7 @@ export class OrderNewComponent implements OnInit, OnDestroy {
_id: this.ordersService.createId(),
orderId: newOrder.orderId,
menuItem,
status: Status.Todo,
status: this.statuses[0],
notes: newOrder.notes,
date: dateFormatted,
plate: newOrder.plate
Expand Down
6 changes: 5 additions & 1 deletion src/app/modules/orders/orders/orders.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@
</td>
<td>
<span class="p-column-title">Status</span>
<span [class]="'order-badge status-' + order.status">{{order.status}}</span>
<span [class]="'order-badge status-' + order.status">{{order.status?.label}}</span>
</td>
<td>
<span class="p-column-title">Plate</span>
Expand Down Expand Up @@ -169,6 +169,10 @@
<label for="quantity">Quantity</label>
<p-inputNumber id="quantity" [(ngModel)]="currentOrder.quantity"></p-inputNumber>
</div>
<div class="p-field" *ngIf="currentOrder._id">
<label for="status">Status</label>
<p-dropdown id="status" [options]="statuses" [(ngModel)]="currentOrder.status" optionLabel="label"></p-dropdown>
</div>
<div class="p-field">
<label for="plate">Plate</label>
<p-dropdown id="plate" [options]="platesOptions" [(ngModel)]="currentOrder.plate" optionLabel="name"></p-dropdown>
Expand Down
46 changes: 35 additions & 11 deletions src/app/modules/orders/orders/orders.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,12 @@ export class OrdersComponent implements OnInit, OnDestroy {
header: 'Confirm',
icon: 'pi pi-exclamation-triangle',
accept: () => {
this.orders = this.orders.filter(val => !this.selectedOrders.includes(val));
this.selectedOrders = [];
this.messageService.add({severity:'success', summary: 'Successful', detail: 'Orders Deleted', life: 3000});
const ids = this.selectedOrders.map(item => item._id!);
this.apiConnector.removeOrders(ids).subscribe(() => {
this.orders = this.orders.filter(val => !this.selectedOrders.includes(val));
this.selectedOrders = [];
this.messageService.add({severity:'success', summary: 'Successful', detail: 'Orders Deleted', life: 3000});
})
}
});
}
Expand All @@ -111,7 +114,8 @@ export class OrdersComponent implements OnInit, OnDestroy {
category: this.currentOrder.menuItem.parent.data
};
const currentOrderIdx = this.orders.findIndex(order => order._id === this.currentOrder._id);
this.orders[currentOrderIdx] = {

const editOrder = {
... this.orders[currentOrderIdx],
orderId: this.currentOrder.orderId,
menuItem,
Expand All @@ -120,9 +124,19 @@ export class OrdersComponent implements OnInit, OnDestroy {
date: this.currentOrder.date,
plate: this.currentOrder.plate
};
this.apiConnector.updateOrder(editOrder).subscribe(order => {
console.log("order" + order);

// todo call update

this.orders[currentOrderIdx] = {
... this.orders[currentOrderIdx],
orderId: order.orderId,
menuItem,
status: order.status,
notes: order.notes,
date: order.date,
plate: order.plate
};
});
} else {
// new orders
let newOrders: Order[] = [];
Expand All @@ -138,16 +152,16 @@ export class OrdersComponent implements OnInit, OnDestroy {
_id: this.ordersService.createId(),
orderId: this.currentOrder.orderId,
menuItem,
status: Status.Todo,
status: this.statuses[0],
notes: this.currentOrder.notes,
date: dateFormatted,
plate: this.currentOrder.plate
});
}

// todo call save

this.orders = this.orders.concat(newOrders);
this.apiConnector.addOrders(newOrders).subscribe(orders => {
this.orders = this.orders.concat(orders);
})
}

this.orderDialog = false;
Expand Down Expand Up @@ -180,6 +194,16 @@ export class OrdersComponent implements OnInit, OnDestroy {
}

deleteOrder(order: Order) {
// todo
this.confirmationService.confirm({
message: 'Are you sure you want to delete the selected order?',
header: 'Confirm',
icon: 'pi pi-exclamation-triangle',
accept: () => {
this.apiConnector.removeOrder(order._id!).subscribe(() => {
this.orders = this.orders.filter(val => val != order);
this.messageService.add({severity:'success', summary: 'Successful', detail: 'Orders Deleted', life: 3000});
})
}
});
}
}
4 changes: 2 additions & 2 deletions src/app/services/file-system-connector.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ export class FileSystemConnectorService implements ApiConnector {
return fromPromise(fs.readOrders());
}

removeOrder(id: string): Observable<Order | undefined> {
removeOrder(id: string): Observable<boolean> {
return fromPromise(fs.deleteOrder(id));
}

removeOrders(ids: string[]): Observable<Order[] | undefined> {
removeOrders(ids: string[]): Observable<boolean> {
return fromPromise(fs.deleteOrders(ids));
}

Expand Down
Loading

0 comments on commit 501b560

Please sign in to comment.