Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ktnishide/part2 #2

Open
wants to merge 3 commits into
base: ktnishide/part1
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,38 @@ To run this server locally, run as follows:
```bash
$ dart run lib/server.dart
```


To run server tests locally, run as follows:

```bash
$ dart test
```

To build docker image, run as follows:

```bash
$ docker build -t <image name> .
```

To run docker image, run as follows:

```bash
$ docker run --publish 8000:8000 bubble
```

Curl call examples:

post order
```bash
$ curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "store_number=1&order_number=1&flavours=brown sugar&toppings=tapioca pearls&amount_of_ice=Full&total_order_price=50.99" http://localhost:8000/order/
```

get report
```bash
$ curl -X GET http://localhost:8000/order/report?monthYear=2021-09
```


Interesting...
![image_size](image_size.png)
6 changes: 6 additions & 0 deletions app/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
include: package:lints/recommended.yaml

# linter:
# rules:
# I'm curious the reason of this rule....
# for map is ok but list not
# avoid_function_literals_in_foreach_calls: false
Binary file added app/image_size.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
33 changes: 28 additions & 5 deletions app/lib/controllers/order_controller.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import 'dart:convert';
import 'dart:developer';

import '../shared/helpers.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';

import '../models/order.dart';
import '../models/orders_report.dart';
import '../repositories/orders_repository.dart';
import '../shared/helpers.dart';

class OrderController {
OrderController(this.orderRepository);
Expand All @@ -20,20 +22,41 @@ class OrderController {
order.validate();
orderRepository.saveOrder(order);
return Response.ok(order.toJson());
} catch (e) {
return Response.internalServerError(body: e.toString());
} catch (e, stack) {
return handleError(e, stack);
}
});

router.get('/', (request) {
try {
return Response.ok(json.encode(orderRepository.getOrders()),
headers: {'Content-Type': 'application/json'});
} catch (e) {
return Response.internalServerError(body: e.toString());
} catch (e, stack) {
return handleError(e, stack);
}
});

router.get('/report<monthYear|.*>', (Request request) async {
try {
final monthYear = request.url.queryParameters['monthYear'] ?? '';
final orders = orderRepository.getOrders();

OrdersReport report = OrdersReport();

return Response.ok(
json.encode(report.generateReport(orders, monthYear).toJson()),
headers: {'Content-Type': 'application/json'});
} catch (e, stack) {
return handleError(e, stack);
}
});

return router;
}

Response handleError(e, stack) {
log(e.toString());
log(stack.toString());
return Response.internalServerError(body: e.toString());
}
}
31 changes: 20 additions & 11 deletions app/lib/models/order.dart
Original file line number Diff line number Diff line change
Expand Up @@ -124,16 +124,7 @@ class Order {
throw 'unnexpected flavour: $flavours';
}

toppings?.forEach((element) {
if (![
'TAPIOCA PEARLS',
'JELLY',
'CREAM TOP',
'OREO',
].contains(element.trim().toUpperCase())) {
throw 'unnexpected toppings: ${toppings.toString()}';
}
});
toppings?.forEach(validateToppings);

if (![
'FULL',
Expand All @@ -149,8 +140,26 @@ class Order {
if (toppings?.length != 1 ||
toppings?[0].trim().toUpperCase() != 'TAPIOCA PEARLS' ||
amountOfIce?.toUpperCase() != 'FULL') {
throw 'Invalid combination for Brown Sugar';
throw '''
Invalid combination for Brown Sugar, expected:
{
"flavours": "Brown Sugar",
"toppings": "tapioca pearls",
"amount_of_ice": "Full"
}
''';
}
}
}

void validateToppings(element) {
if (![
'TAPIOCA PEARLS',
'JELLY',
'CREAM TOP',
'OREO',
].contains(element.trim().toUpperCase())) {
throw 'unnexpected toppings: $element';
}
}
}
89 changes: 89 additions & 0 deletions app/lib/models/orders_report.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import "package:collection/collection.dart";

import 'order.dart';

class OrdersReport {
List<Stores>? stores;

OrdersReport({this.stores});

OrdersReport.fromJson(Map<String, dynamic> json) {
if (json['stores'] != null) {
stores = <Stores>[];
json['stores'].forEach((v) {
stores?.add(Stores.fromJson(v));
});
}
}

Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
if (stores != null) {
data['stores'] = stores!.map((v) => v.toJson()).toList();
}
return data;
}

OrdersReport generateReport(List<Order> orders, String monthYear) {
final storesByMonth = filterByMonth(orders, monthYear);
return groupAndSumByStore(storesByMonth, 'store_number');
}

filterByMonth(List<Order> orders, String monthYear) {
final searchDate = DateTime.tryParse('$monthYear-01');
if (searchDate == null) {
throw 'Invalid period: $monthYear, expected: YYYY-MM';
}
return orders
.where((element) =>
element.orderDatetime?.year == searchDate.year &&
element.orderDatetime?.month == searchDate.month)
.toList();
}

groupAndSumByStore(List<Order> storesByMonth, String key) {
Map groupByStore =
groupBy(storesByMonth.map((e) => e.toMap()), (Map obj) => obj[key]);
var report = OrdersReport(stores: []);

groupByStore.forEach((k, v) {
report.stores!.add(Stores(
storeNumber: k.toString(),
orderPriceSum:
'A\$${(v.fold(0, (prev, element) => prev + element['total_order_price']) as double).toStringAsFixed(2)}',
orderTotal: v.fold(0, (prev, element) => prev + 1),
));
});

return report;
}

@override
String toString() => 'OrdersReport(stores: $stores)';
}

class Stores {
String? storeNumber;
String? orderPriceSum;
int? orderTotal;

Stores({this.storeNumber, this.orderPriceSum, this.orderTotal});

Stores.fromJson(Map<String, dynamic> json) {
storeNumber = json['storeNumber'];
orderPriceSum = json['orderPriceSum'];
orderTotal = json['orderTotal'];
}

Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['storeNumber'] = storeNumber;
data['orderPriceSum'] = orderPriceSum;
data['orderTotal'] = orderTotal;
return data;
}

@override
String toString() =>
'Stores(storeNumber: $storeNumber, orderPriceSum: $orderPriceSum, orderTotal: $orderTotal)';
}
22 changes: 10 additions & 12 deletions app/lib/repositories/orders_repository.dart
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import 'dart:convert';
import 'dart:developer';

import 'dart:io';

import '../models/order.dart';
import 'package:path/path.dart' as path;

import '../models/order.dart';

abstract class IOrdersRepository {
List getOrders();
List<Order> getOrders();
void saveOrder(Order order);
}

Expand All @@ -17,27 +17,25 @@ final ordersFile = File(
class OrdersRepositoryFile extends IOrdersRepository {
var orders = [];
OrdersRepositoryFile() {
// initialize file
if (!ordersFile.existsSync()) {
ordersFile.createSync();
ordersFile.writeAsStringSync('[]');
}
var x = jsonDecode(ordersFile.readAsStringSync()) as List;
x.forEach((element) {
orders.add(Order.fromMapDynamic(element).toJson());
});
log('x');
// load file orders in memory
(jsonDecode(ordersFile.readAsStringSync()) as List).forEach(addOrders);
}

void addOrders(element) => orders.add(Order.fromMapDynamic(element).toJson());

@override
List getOrders() {
return jsonDecode(orders.toString());
}
List<Order> getOrders() =>
[...orders.map((e) => Order.fromMapDynamic(jsonDecode(e)))];

@override
void saveOrder(Order order) {
orders.add(order.toJson());
final content = orders.toString();
log(content);
ordersFile.writeAsStringSync(content);
}
}
10 changes: 10 additions & 0 deletions app/test/test_definitions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -100,5 +100,15 @@ void runTests(
expect(response.statusCode, 404);
expect(response.body, 'Route not found');
});
testServer('report OK', (host) async {
var response =
await get(Uri.parse('$host/order/report?monthYear=2021-09'));
expect(response.statusCode, 200);
});
testServer('report NOK - date', (host) async {
var response =
await get(Uri.parse('$host/order/report?monthYear=2021-xx'));
expect(response.statusCode, 500);
});
});
}