|
1 | 1 | #!/usr/bin/env python |
2 | | -from __future__ import annotations |
3 | | -from typing import Dict |
4 | 2 | import csv |
5 | 3 | import sys |
6 | | -from datetime import datetime |
7 | 4 | from pathlib import Path |
8 | 5 |
|
9 | | -from allocation.domain import model |
10 | | -from allocation.service_layer import services, unit_of_work |
11 | | -from allocation.adapters import repository |
12 | | - |
13 | | - |
14 | | -class CsvRepository(repository.AbstractRepository): |
15 | | - def __init__(self, folder): |
16 | | - self._batches_path = Path(folder) / "batches.csv" |
17 | | - self._allocations_path = Path(folder) / "allocations.csv" |
18 | | - self._batches = {} # type: Dict[str, model.Batch] |
19 | | - self._load() |
20 | | - |
21 | | - def get(self, reference): |
22 | | - return self._batches.get(reference) |
23 | | - |
24 | | - def add(self, batch): |
25 | | - self._batches[batch.reference] = batch |
26 | | - |
27 | | - def _load(self): |
28 | | - with self._batches_path.open() as f: |
29 | | - reader = csv.DictReader(f) |
30 | | - for row in reader: |
31 | | - ref, sku = row["ref"], row["sku"] |
32 | | - qty = int(row["qty"]) |
33 | | - if row["eta"]: |
34 | | - eta = datetime.strptime(row["eta"], "%Y-%m-%d").date() |
35 | | - else: |
36 | | - eta = None |
37 | | - self._batches[ref] = model.Batch(ref=ref, sku=sku, qty=qty, eta=eta) |
38 | | - if self._allocations_path.exists() is False: |
39 | | - return |
40 | | - with self._allocations_path.open() as f: |
41 | | - reader = csv.DictReader(f) |
42 | | - for row in reader: |
43 | | - batchref, orderid, sku = row["batchref"], row["orderid"], row["sku"] |
44 | | - qty = int(row["qty"]) |
45 | | - line = model.OrderLine(orderid, sku, qty) |
46 | | - batch = self._batches[batchref] |
47 | | - batch._allocations.add(line) |
48 | | - |
49 | | - def list(self): |
50 | | - return list(self._batches.values()) |
51 | | - |
52 | | - |
53 | | -class CsvUnitOfWork(unit_of_work.AbstractUnitOfWork): |
54 | | - def __init__(self, folder): |
55 | | - self.batches = CsvRepository(folder) |
56 | | - |
57 | | - def commit(self): |
58 | | - with self.batches._allocations_path.open("w") as f: |
59 | | - writer = csv.writer(f) |
60 | | - writer.writerow(["orderid", "sku", "qty", "batchref"]) |
61 | | - for batch in self.batches.list(): |
62 | | - for line in batch._allocations: |
63 | | - writer.writerow( |
64 | | - [line.orderid, line.sku, line.qty, batch.reference] |
65 | | - ) |
66 | | - |
67 | | - def rollback(self): |
68 | | - pass |
| 6 | +from allocation.service_layer import csv_uow, services |
69 | 7 |
|
70 | 8 |
|
71 | 9 | def main(folder): |
72 | 10 | orders_path = Path(folder) / "orders.csv" |
73 | | - uow = CsvUnitOfWork(folder) |
| 11 | + uow = csv_uow.CsvUnitOfWork(folder) |
74 | 12 | with orders_path.open() as f: |
75 | 13 | reader = csv.DictReader(f) |
76 | 14 | for row in reader: |
|
0 commit comments