Browse Source

Set Persons created by client to active

Adds active attribute to api, also ran black
Maarten van den Berg 6 years ago
parent
commit
d7b593036f
2 changed files with 56 additions and 55 deletions
  1. 18 16
      piket_client/model.py
  2. 38 39
      piket_server/__init__.py

+ 18 - 16
piket_client/model.py

30
             return False, ex
30
             return False, ex
31
 
31
 
32
     datetime_format = "%Y-%m-%dT%H:%M:%S.%f"
32
     datetime_format = "%Y-%m-%dT%H:%M:%S.%f"
33
+
33
     @classmethod
34
     @classmethod
34
     def unsettled_consumptions(cls) -> dict:
35
     def unsettled_consumptions(cls) -> dict:
35
-        req = requests.get(urljoin(SERVER_URL, 'status'))
36
+        req = requests.get(urljoin(SERVER_URL, "status"))
36
 
37
 
37
         data = req.json()
38
         data = req.json()
38
 
39
 
39
-        if data['unsettled']['amount']:
40
-            data['unsettled']['first'] = datetime.datetime\
41
-                    .strptime(data['unsettled']['first'],
42
-                            cls.datetime_format)
43
-            data['unsettled']['last'] = datetime.datetime\
44
-                    .strptime(data['unsettled']['last'],
45
-                            cls.datetime_format)
40
+        if data["unsettled"]["amount"]:
41
+            data["unsettled"]["first"] = datetime.datetime.strptime(
42
+                data["unsettled"]["first"], cls.datetime_format
43
+            )
44
+            data["unsettled"]["last"] = datetime.datetime.strptime(
45
+                data["unsettled"]["last"], cls.datetime_format
46
+            )
46
 
47
 
47
         return data
48
         return data
48
 
49
 
49
 
50
 
50
-
51
 class Person(NamedTuple):
51
 class Person(NamedTuple):
52
     """ Represents a Person, as retrieved from the database. """
52
     """ Represents a Person, as retrieved from the database. """
53
 
53
 
87
         """ Create a new Person from the current attributes. As tuples are
87
         """ Create a new Person from the current attributes. As tuples are
88
         immutable, a new Person with the correct id is returned. """
88
         immutable, a new Person with the correct id is returned. """
89
         req = requests.post(
89
         req = requests.post(
90
-            urljoin(SERVER_URL, "people"), json={"person": {"name": self.name}}
90
+            urljoin(SERVER_URL, "people"),
91
+            json={"person": {"name": self.name, "active": True}},
91
         )
92
         )
92
 
93
 
93
         try:
94
         try:
332
             )
333
             )
333
             return False
334
             return False
334
 
335
 
336
+
335
 class Settlement(NamedTuple):
337
 class Settlement(NamedTuple):
336
     """ Represents a stored Settlement. """
338
     """ Represents a stored Settlement. """
339
+
337
     settlement_id: int
340
     settlement_id: int
338
     name: str
341
     name: str
339
     consumption_summary: dict
342
     consumption_summary: dict
341
     @classmethod
344
     @classmethod
342
     def from_dict(cls, data: dict) -> "Settlement":
345
     def from_dict(cls, data: dict) -> "Settlement":
343
         return Settlement(
346
         return Settlement(
344
-            settlement_id=data['settlement_id'],
345
-            name=data['name'],
346
-            consumption_summary=data['consumption_summary']
347
+            settlement_id=data["settlement_id"],
348
+            name=data["name"],
349
+            consumption_summary=data["consumption_summary"],
347
         )
350
         )
348
 
351
 
349
     @classmethod
352
     @classmethod
350
     def create(cls, name: str) -> "Settlement":
353
     def create(cls, name: str) -> "Settlement":
351
         req = requests.post(
354
         req = requests.post(
352
-            urljoin(SERVER_URL, '/settlements'),
353
-            json={'settlement': {'name': name}}
355
+            urljoin(SERVER_URL, "/settlements"), json={"settlement": {"name": name}}
354
         )
356
         )
355
 
357
 
356
-        return cls.from_dict(req.json()['settlement'])
358
+        return cls.from_dict(req.json()["settlement"])

+ 38 - 39
piket_server/__init__.py

69
     @property
69
     @property
70
     def as_dict(self) -> dict:
70
     def as_dict(self) -> dict:
71
         return {
71
         return {
72
-            'settlement_id': self.settlement_id,
73
-            'name': self.name,
74
-            'consumption_summary': self.consumption_summary
72
+            "settlement_id": self.settlement_id,
73
+            "name": self.name,
74
+            "consumption_summary": self.consumption_summary,
75
         }
75
         }
76
 
76
 
77
     @property
77
     @property
78
     def consumption_summary(self) -> dict:
78
     def consumption_summary(self) -> dict:
79
-        q = Consumption.\
80
-                query.\
81
-                filter_by(settlement=self).\
82
-                group_by(Consumption.consumption_type_id).\
83
-                outerjoin(ConsumptionType).\
84
-                with_entities(
85
-                    Consumption.consumption_type_id,
86
-                    ConsumptionType.name,
87
-                    func.count(Consumption.consumption_id),
88
-                ).\
89
-                all()
79
+        q = (
80
+            Consumption.query.filter_by(settlement=self)
81
+            .group_by(Consumption.consumption_type_id)
82
+            .outerjoin(ConsumptionType)
83
+            .with_entities(
84
+                Consumption.consumption_type_id,
85
+                ConsumptionType.name,
86
+                func.count(Consumption.consumption_id),
87
+            )
88
+            .all()
89
+        )
90
 
90
 
91
-        return {r[0]: {'name': r[1], 'count': r[2]} for r in q}
91
+        return {r[0]: {"name": r[1], "count": r[2]} for r in q}
92
 
92
 
93
 
93
 
94
 class ConsumptionType(db.Model):
94
 class ConsumptionType(db.Model):
157
     """ Return a status ping. """
157
     """ Return a status ping. """
158
     return "Pong"
158
     return "Pong"
159
 
159
 
160
+
160
 @app.route("/status")
161
 @app.route("/status")
161
 def status() -> None:
162
 def status() -> None:
162
     """ Return a status dict with info about the database. """
163
     """ Return a status dict with info about the database. """
163
-    unsettled_q = Consumption.query.\
164
-            filter_by(settlement=None).\
165
-            filter_by(reversed=False)
164
+    unsettled_q = Consumption.query.filter_by(settlement=None).filter_by(reversed=False)
166
 
165
 
167
     unsettled = unsettled_q.count()
166
     unsettled = unsettled_q.count()
168
 
167
 
169
     first = None
168
     first = None
170
     last = None
169
     last = None
171
     if unsettled:
170
     if unsettled:
172
-        last = unsettled_q.\
173
-                order_by(Consumption.created_at.desc()).\
174
-                first().\
175
-                created_at.isoformat()
176
-        first = unsettled_q.\
177
-                order_by(Consumption.created_at.asc())\
178
-                .first()\
179
-                .created_at.isoformat()
180
-
181
-    return jsonify({
182
-        'unsettled': {
183
-            'amount': unsettled,
184
-            'first': first,
185
-            'last': last,
186
-        },
187
-    })
171
+        last = (
172
+            unsettled_q.order_by(Consumption.created_at.desc())
173
+            .first()
174
+            .created_at.isoformat()
175
+        )
176
+        first = (
177
+            unsettled_q.order_by(Consumption.created_at.asc())
178
+            .first()
179
+            .created_at.isoformat()
180
+        )
181
+
182
+    return jsonify({"unsettled": {"amount": unsettled, "first": first, "last": last}})
188
 
183
 
189
 
184
 
190
 # Person
185
 # Person
222
         return jsonify({"error": "Could not parse JSON."}), 400
217
         return jsonify({"error": "Could not parse JSON."}), 400
223
 
218
 
224
     data = json.get("person") or {}
219
     data = json.get("person") or {}
225
-    person = Person(name=data.get("name"))
220
+    person = Person(name=data.get("name"), active=data.get("active", False))
221
+
226
     try:
222
     try:
227
         db.session.add(person)
223
         db.session.add(person)
228
         db.session.commit()
224
         db.session.commit()
347
 
343
 
348
     return jsonify(consumption_type=ct.as_dict), 201
344
     return jsonify(consumption_type=ct.as_dict), 201
349
 
345
 
346
+
350
 # Settlement
347
 # Settlement
351
 @app.route("/settlements", methods=["GET"])
348
 @app.route("/settlements", methods=["GET"])
352
 def get_settlements():
349
 def get_settlements():
354
     result = Settlement.query.all()
351
     result = Settlement.query.all()
355
     return jsonify(settlements=[s.as_dict for s in result])
352
     return jsonify(settlements=[s.as_dict for s in result])
356
 
353
 
354
+
357
 @app.route("/settlements", methods=["POST"])
355
 @app.route("/settlements", methods=["POST"])
358
 def add_settlement():
356
 def add_settlement():
359
     """ Create a Settlement, and link all un-settled Consumptions to it. """
357
     """ Create a Settlement, and link all un-settled Consumptions to it. """
362
     if not json:
360
     if not json:
363
         return jsonify({"error": "Could not parse JSON."}), 400
361
         return jsonify({"error": "Could not parse JSON."}), 400
364
 
362
 
365
-    data = json.get('settlement') or {}
366
-    s = Settlement(name=data['name'])
363
+    data = json.get("settlement") or {}
364
+    s = Settlement(name=data["name"])
367
 
365
 
368
     db.session.add(s)
366
     db.session.add(s)
369
     db.session.commit()
367
     db.session.commit()
370
 
368
 
371
-    Consumption.query.filter_by(settlement=None).update({'settlement_id':
372
-        s.settlement_id})
369
+    Consumption.query.filter_by(settlement=None).update(
370
+        {"settlement_id": s.settlement_id}
371
+    )
373
 
372
 
374
     db.session.commit()
373
     db.session.commit()
375
 
374