aboutsummaryrefslogtreecommitdiff
path: root/lib/d2/app/adapters/detail.py
blob: 738230b4c238d952f12635d0977dee7339cb1755 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
from d2.app.adapters import BaseAdapter
from datetime import datetime
from d2.db import DetailType
from d2.db import Detail
from d2.db import Forge
from d2.db import Plot
from d2.db import Occupant
from sqlalchemy import or_
from sqlalchemy import func
from d2.config import Config
from d2.app.model.static import StaticData
from collections import namedtuple
from whoosh.fields import Schema, TEXT, ID
from whoosh.index import create_in

class DetailAdapter(BaseAdapter):

    def __init__(self, db, log, static, detail, detail_type, forge, plot,
                 occupant):
        self._db = db
        self._log = log
        self._static = static
        self._detail = detail
        self._detail_type = detail_type
        self._forge = forge
        self._plot = plot
        self._occupant = occupant
        self._search_schema_ = None
        self._search_index_ = None
        self._label_detail_type_ids_ = None
        self._multiple_value_labels_ = None
        self._make = namedtuple('detail', 'name data')

    @classmethod
    def load(cls, config=None, static=None):
        config = config or Config.load()
        static = static or StaticData.load(config.db)()
        return cls(config.db, config.log, static, Detail, DetailType, Forge,
                   Plot, Occupant)

    @property
    def _label_detail_type_ids(self):
        if not self._label_detail_type_ids_:
            self._label_detail_type_ids_ = [
                    self._static.detail_type.first_name,
                    self._static.detail_type.last_name,
                    self._static.detail_type.name,
                    self._static.detail_type.network_id
            ]
        return self._label_detail_type_ids_

    @property
    def _multiple_value_labels(self):
        if not self._multiple_value_labels_:
            self._multiple_value_labels_ = [
                self._static.detail_type.network_jack,
            ]
        return self._multiple_value_labels_

    def fetch_all_occupant_details(self, occupant_id, date_start=None):
        """Fetch all details for the given occupant_id
        """
        return self._fetch_details(None, occupant_id, date_start)

    def fetch_all_plot_details(self, plot_id, date_start=None):
        """Fetch all details for the given plot_id
        """
        return self._fetch_details(plot_id, None, date_start)

    def fetch_occupant_detail(self, occupant_id, detail_type_id,
                              date_start=None):
        """Fetch a single detail for the given occupant_id and
        detail_type_id
        """
        return self._fetch_detail(None, occupant_id, detail_type_id,
                                  date_start)

    def fetch_plot_detail(self, plot_id, detail_type_id, date_start=None):
        """Fetch a single detail for the given plot_id and
        detail_type_id
        """
        return self._fetch_detail(plot_id, None, detail_type_id, date_start)

    def fetch_detail_by_type_data(self, detail_type_id, data, date_start=None):
        """Fetch all detail records given detail_type_id and data
        """
        date_start = self.build_date(date_start)
        obj = self._db.session.query(self._detail
            ).filter(self._detail.detail_type_id==detail_type_id
            ).filter(func.lower(self._detail.data)==data.lower()
            ).filter(self._detail.date_override==None
            ).filter(self._detail.date_start<=date_start
            ).filter(or_(self._detail.date_end>date_start,
                self._detail.date_end==None)
        ).all()
        if not obj:
            return []
        else:
            return obj

    def _fetch_detail(self, plot_id, occupant_id, detail_type_id, date_start):
        date_start = self.build_date(date_start)
        return self._db.session.query(self._detail
            ).filter(self._detail.plot_id==plot_id
            ).filter(self._detail.occupant_id==occupant_id
            ).filter(self._detail.detail_type_id==detail_type_id
            ).filter(self._detail.date_override==None
            ).filter(self._detail.date_start<=date_start
            ).filter(or_(self._detail.date_end>date_start,
                self._detail.date_end==None)
        ).first()

    def _fetch_details(self, plot_id, occupant_id, date_start):
        if not plot_id and not occupant_id:
            return []
        date_start = self.build_date(date_start)
        obj = self._db.session.query(self._detail
            ).filter(self._detail.plot_id==plot_id
            ).filter(self._detail.occupant_id==occupant_id
            ).filter(self._detail.date_override==None
            ).filter(self._detail.date_start<=date_start
            ).filter(or_(self._detail.date_end>date_start,
                self._detail.date_end==None)
        ).all()
        if not obj:
            return []
        else:
            return obj


    def insert_occupant_detail(self, occupant_id, detail_type_id, data,
                                date_start=None, date_end=None):
        """Inserts detail data for an occupant
        """
        return self._insert_detail(None, occupant_id, detail_type_id, data,
                                   date_start, date_end)

    def insert_plot_detail(self, plot_id, detail_type_id, data,
                                date_start=None, date_end=None):
        """Inserts detail data for an occupant
        """
        return self._insert_detail(plot_id, None, detail_type_id, data,
                                   date_start, date_end)

    def _insert_detail(self, plot_id, occupant_id, detail_type_id, data,
                               date_start=None, date_end=None):

        date_start= self.build_date(date_start)
        data = dict(
                plot_id=plot_id,
                occupant_id=occupant_id,
                detail_type_id=detail_type_id,
                data=data,
                date_start=date_start,
                date_end=date_end,
                date_created=datetime.now(),
                date_override=None
                )
        obj = self._detail.from_dict(data)
        self._db.session.add(obj)
        self._db.session.commit()
        return obj

    def _change_detail(self, plot_id, occupant_id, detail_type_id, data,
                       date_start=None, date_end=None):
        """
        TODO: FIXME
        """
        if plot_id:
            previous_record = self.fetch_plot_detail(plot_id, detail_type_id,
                                                     date_start)
        else:
            previous_record = self.fetch_occupant_detail(occupant_id,
                                detail_type_id, date_start)

        if previous_record:
            self._set_override(previous_record)
            self._set_end(previous_record, date_end)
        else:
            raise Exception("Missing previous recored.  Unable to change.")

        date_start= self.build_date(date_start)
        data = dict(
                plot_id=plot_id,
                occupant_id=occupant_id,
                detail_type_id=detail_type_id,
                data=data,
                date_start=date_start,
                date_end=date_end,
                date_created=datetime.now(),
                date_override=None
                )
        obj = self._detail.from_dict(data)
        self._db.session.add(obj)
        self._db.session.commit()
        return obj

    def _set_override(self, detail_obj):
        detail_obj.date_override = datetime.now()
        self._db.session.commit()

    def _set_end(self, detail_obj, date_end=None):
        date_end = self.build_date(date_end)
        data = detail_obj.as_dict()
        if 'id' in data:
            del(data['id'])
        data['date_end'] = date_end
        data['date_created'] = datetime.now()
        data['date_override'] = None
        obj = self._detail.from_dict(data)
        self._db.session.add(obj)
        self._db.session.commit()

    def update_detail(self, detail_obj):
        """Updates the given changed detail_obj
        """
        if self._db.session.is_modified(detail_obj):
            new_data = detail_obj.as_dict()
            if 'id' in new_data:
                del(new_data['id'])
            self._db.session.refresh(detail_obj)
            detail_obj.date_override = datetime.now()
            obj = self._detail.from_dict(new_data)
            self._db.session.add(obj)
            self._db.session.commit()

    def occupant_details(self, occupant_id, date_start=None):
        results = self.fetch_all_occupant_details(occupant_id, date_start)
        return self._details_to_tuple(results)

    def plot_details(self, plot_id, date_start=None):
        results = self.fetch_all_plot_details(plot_id, date_start)
        return self._details_to_tuple(results)

    def occupant_dict(self, occupant_id, date_start=None):
        details = self.fetch_all_occupant_details(occupant_id, date_start)
        return self.details_to_dict(details)

    def plot_dict(self, plot_id, date_start=None):
        details = self.fetch_all_plot_details(plot_id, date_start)
        return self.details_to_dict(details)

    def _label_from_details(self, details):
        if details:
            out = []
            hold = {}
            for detail in details:
                if (detail.detail_type_id in self._label_detail_type_ids
                            and detail.data):
                    hold[detail.detail_type_id] = detail.data
            if self._static.detail_type.first_name in hold:
                out.append(hold[self._static.detail_type.first_name])
                if self._static.detail_type.last_name in hold:
                    out.append(hold[self._static.detail_type.last_name])
            elif self._static.detail_type.last_name in hold:
                out.append(hold[self._static.detail_type.last_name])
            elif self._static.detail_type.name in hold:
                out.append(hold[self._static.detail_type.name])
            elif self._static.detail_type.network_id in hold:
                out.append(hold[self._static.detail_type.network_id])
            else:
                out.append(u'Unknown')
            return u' '.join(out)

    def details_to_dict(self, details):
        out = {}
        if details:
            out[u'label'] = self._label_from_details(details)
            out[u'plot_id'] = details[0].plot_id
            out[u'occupant_id'] = details[0].occupant_id
            for detail in details:
                if (detail.detail_type_id not in self._label_detail_type_ids
                            and detail.data):
                    name = detail.detail_type.name
                    key = name.lower().strip().replace(u' ', u'_')
                    if detail.detail_type_id in self._multiple_value_labels:
                        if key in out:
                            name = out[key][u'name'].strip()
                            if not name.endswith(u's'):
                                name = u"{0}s".format(name)
                                out[key][u'name'] = name
                            data = out[key][u'data']
                            data.append(detail.data)
                            out[key][u'data'] = data
                        else:
                            out[key] = {}
                            out[key][u'name'] = name
                            out[key][u'data'] = [detail.data]
                    else:
                        out[key] = {}
                        out[key][u'name'] = name
                        out[key][u'data'] = detail.data
        return out

    def _details_dict_to_tuple(self, details):
        """Takes a details dictionary and turnes it into a named tuple
        """
        if details:
            keys = [u'label', u'plot_id', u'occupant_id']
            key_hold = []
            vals = []
            for key in details.keys():
                if key not in keys and key not in key_hold:
                    key_hold.append(key)
            key_hold.sort()
            keys = keys + key_hold
            for key in keys:
                val = details[key]
                if isinstance(val, dict):
                    val = self._make(val[u'name'], val[u'data'])
                vals.append(val)
            make = namedtuple('details', keys)
            return make(*vals)

    def _details_to_tuple(self, details):
        if details:
            hold = {}
            keys = []
            vals = []
            hold[u'label'] = self._label_from_details(details)
            if details[0].plot_id:
                hold[u'plot_id'] = details[0].plot_id
                hold[u'occupant_id'] = None
            else:
                hold[u'plot_id'] = None
                hold[u'occupant_id'] = details[0].occupant_id
            for detail in details:
                if (detail.detail_type_id not in self._label_detail_type_ids
                            and detail.data):
                    name = detail.detail_type.name
                    key = name.lower().strip().replace(u' ', u'_')
                    if detail.detail_type_id in self._multiple_value_labels:
                        if key in hold:
                            data = hold[key].data
                            data.append(detail.data)
                            hold[key] = hold[key]._replace(data=data)
                        else:
                            keys.append(key)
                            data = [detail.data]
                            hold[key] = self._make(name, data)
                    else:
                        keys.append(key)
                        hold[key] = self._make(name, detail.data)
            keys.sort()
            keys = [u'label', u'id', u'id_type'] + keys
            for key in keys:
                vals.append(hold[key])
            make = namedtuple('details', keys)
            return make(*vals)

    def details(self, plot_id=None, occupant_id=None):
        """ Returns a named tuple with complete details.
        """
        plot_id, occupant_id = self._validate(plot_id, occupant_id)
        plot = self.details_to_dict(self.fetch_all_plot_details(plot_id))
        occupant = self.details_to_dict(self.fetch_all_occupant_details(
                                occupant_id))

        if plot and occupant:
            occupant[u'plot_id'] = plot[u'plot_id']
            occupant[u'plot'] = {
                u'name': u'Plot',
                u'data': plot['label']
            }
            del plot[u'plot_id']
            del plot[u'occupant_id']
            del plot[u'label']

            for key, val in plot.items():
                occupant[key] = val
            return self._details_dict_to_tuple(occupant)

        if plot:
            return self._details_dict_to_tuple(plot)

        if occupant:
            return self._details_dict_to_tuple(occupant)

    def _validate(self, plot_id, occupant_id, start_date=None):
        """Validates that the given plot_id and occupant_id
        are valid.  Also checks forge
        """
        if not self._is_valid_plot(plot_id):
            plot_id = None
        if not self._is_valid_occupant(occupant_id):
            occupant_id = None
        if plot_id and occupant_id:
            if not self._is_valid_forge(plot_id, occupant_id, start_date):
                plot_id = None
        return plot_id, occupant_id

    def _is_valid_plot(self, plot_id):
        """Validates that the given plot_id actually exists
        """
        if plot_id:
            obj = self._db.session.query(self._plot
                ).filter(self._plot.id==plot_id
            ).first()
            if obj:
                return True
        return False

    def _is_valid_occupant(self, occupant_id):
        """Validates that the given occupant_id actually exists
        """
        if occupant_id:
            obj = self._db.session.query(self._occupant
                ).filter(self._occupant.id==occupant_id
            ).first()
            if obj:
                return True
        return False

    def _is_valid_forge(self, plot_id, occupant_id, date_start=None):
        """Validates that the given plot_id and occupant_id are related
        in the forge table.
        """
        date_start = self.build_date(date_start)
        obj = self._db.session.query(self._forge
            ).filter(self._forge.plot_id==plot_id
            ).filter(self._forge.occupant_id==occupant_id
            ).filter(self._forge.date_override==None
            ).filter(self._forge.date_start<=date_start
            ).filter(or_(self._forge.date_end>date_start,
                self._forge.date_end==None)
        ).first()
        if obj:
            return True
        else:
            return False