Digitale bierlijst

export.py 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """
  2. Provides functionality for creating Export files.
  3. """
  4. import csv
  5. import os
  6. import sys
  7. from piket_client.model import Settlement, Export, ConsumptionType, Person
  8. if len(sys.argv) > 1:
  9. eid = int(sys.argv[1])
  10. export = Export.get(eid)
  11. else:
  12. export = Export.create()
  13. filename_base = export.created_at.strftime("Export %Y-%m-%d")
  14. # Determine which consumption types exist
  15. consumption_types = [
  16. ConsumptionType.get(id)
  17. for id in {
  18. type_id
  19. for s in export.settlements
  20. for type_id in s["consumption_summary"].keys()
  21. }
  22. ]
  23. consumption_types.sort(key=lambda x: x.name)
  24. extended_settlements = [
  25. Settlement.get(id) for id in map(lambda x: x["settlement_id"], export.settlements)
  26. ]
  27. extended_settlements.sort(key=lambda x: x.name)
  28. person_ids = set()
  29. for settlement in extended_settlements:
  30. for ctype in settlement.count_info.values():
  31. for person_id in ctype["counts"].keys():
  32. person_ids.add(person_id)
  33. persons = [Person.get(person_id) for person_id in person_ids]
  34. persons.sort(key=lambda p: p.name)
  35. fieldnames = [
  36. "Naam",
  37. *map(lambda x: f"{x.name} ({x.settlement_id})", extended_settlements),
  38. "Totaal",
  39. ]
  40. # Create overview table
  41. with open(f"{filename_base} Overzicht.csv", "w") as outf:
  42. writer = csv.DictWriter(outf, fieldnames)
  43. writer.writeheader()
  44. for consumption_type in consumption_types:
  45. row = {"Naam": consumption_type.name}
  46. total = 0
  47. for settlement in extended_settlements:
  48. strid = str(consumption_type.consumption_type_id)
  49. info = settlement.consumption_summary.get(strid, {})
  50. cell = info.get("count", "")
  51. if cell:
  52. total += cell
  53. row[f"{settlement.name} ({settlement.settlement_id})"] = cell
  54. row["Totaal"] = total
  55. writer.writerow(row)
  56. # Create table per consumption type
  57. for c_type in consumption_types:
  58. strid = str(c_type.consumption_type_id)
  59. with open(f"{filename_base} {c_type.name}.csv", "w") as outf:
  60. writer = csv.DictWriter(outf, fieldnames)
  61. writer.writeheader()
  62. for person in persons:
  63. row = {"Naam": person.name}
  64. total = 0
  65. for settlement in extended_settlements:
  66. info = settlement.count_info.get(strid, {})
  67. countinfo = info.get("counts", {})
  68. pinfo = countinfo.get(str(person.person_id), {})
  69. cell = pinfo.get("count", "")
  70. if cell:
  71. total += cell
  72. row[f"{settlement.name} ({settlement.settlement_id})"] = cell
  73. row["Totaal"] = total
  74. writer.writerow(row)