Use render instead of render_to_response
[htsworkflow.git] / inventory / views.py
1 from __future__ import absolute_import, print_function, unicode_literals
2
3 from django.conf import settings
4 from django.contrib.auth.decorators import login_required
5 from django.core.exceptions import ObjectDoesNotExist
6 from django.http import HttpResponse, HttpResponseRedirect
7 from django.shortcuts import render
8 from django.template import RequestContext, Template
9 from django.template.loader import get_template
10
11 from samples.changelist import HTSChangeList
12 from .models import Item, LongTermStorage, ItemType
13 from .admin import ItemAdmin, ItemTypeAdmin
14 from .bcmagic import item_search
15 from experiments.models import FlowCell
16 from bcmagic.plugin import register_search_plugin
17 from bcmagic.forms import BarcodeMagicForm
18 from bcmagic.utils import print_zpl_socket
19
20 register_search_plugin('Inventory Item', item_search)
21
22 import json
23
24 INVENTORY_CONTEXT_DEFAULTS = {
25     'app_name': 'Inventory Tracker',
26     'bcmagic': BarcodeMagicForm()
27 }
28
29 def __flowcell_rundate_sort(x, y):
30     """
31     Sort by rundate
32     """
33     if x.run_date > y.run_date:
34         return 1
35     elif x.run_date == y.run_date:
36         return 0
37     else:
38         return -1
39
40 def __expand_longtermstorage_context(context, item):
41     """
42     Expand information for LongTermStorage
43     """
44     flowcell_list = []
45     flowcell_id_list = []
46     library_id_list = []
47
48     for lts in item.longtermstorage_set.all():
49         flowcell_list.append(lts.flowcell)
50         flowcell_id_list.append(lts.flowcell.flowcell_id)
51         library_id_list.extend([ lib.id for lib in lts.libraries.all() ])
52
53     flowcell_list.sort(__flowcell_rundate_sort)
54     context['oldest_rundate'] = flowcell_list[0].run_date
55     context['latest_rundate'] = flowcell_list[-1].run_date
56
57     context['flowcell_id_list'] = flowcell_id_list
58     context['library_id_list_1_to_20'] = library_id_list[0:20]
59     context['library_id_list_21_to_40'] = library_id_list[20:40]
60     context['library_id_list_41_to_60'] = library_id_list[40:60]
61     context['library_id_list_61_to_80'] = library_id_list[60:80]
62
63
64 EXPAND_CONTEXT = {
65     'Hard Drive': __expand_longtermstorage_context
66 }
67
68 #INVENTORY_ITEM_PRINT_DEFAULTS = {
69 #    'Hard Drive': 'inventory/hard_drive_shell.zpl',
70 #    'default': 'inventory/default.zpl',
71 #    'host': settings.BCPRINTER_PRINTER1_HOST
72 #}
73
74 def getPrinterTemplateByType(item_type):
75     """
76     returns template to use given item_type
77     """
78     assert item_type.printertemplate_set.count() < 2
79
80     # Get the template for item_type
81     if item_type.printertemplate_set.count() > 0:
82         printer_template = item_type.printertemplate_set.all()[0]
83         return printer_template
84     # Get default
85     else:
86         try:
87             printer_template = PrinterTemplate.objects.get(default=True)
88         except ObjectDoesNotExist:
89             msg = "No template for item type (%s) and no default template found" % (item_type.name)
90             raise ValueError(msg)
91
92         return printer_template
93
94
95 @login_required
96 def data_items(request):
97     """
98     Returns items in json format
99     """
100     item_list = Item.objects.all()
101     d = { 'results': len(item_list) }
102     rows = []
103
104     for item in item_list:
105         item_d = {}
106         item_d['uuid'] = item.uuid
107         item_d['barcode_id'] = item.barcode_id
108         item_d['model_id'] = item.item_info.model_id
109         item_d['part_number'] = item.item_info.part_number
110         item_d['lot_number'] = item.item_info.lot_number
111         item_d['vendor'] = item.item_info.vendor.name
112         item_d['creation_date'] = item.creation_date.strftime('%Y-%m-%d %H:%M:%S')
113         item_d['modified_date'] = item.modified_date.strftime('%Y-%m-%d %H:%M:%S')
114         item_d['location'] = item.location.name
115
116         # Item status if exists
117         if item.status is None:
118             item_d['status'] = ''
119         else:
120             item_d['status'] = item.status.name
121
122         # Stored flowcells on device
123         if item.longtermstorage_set.count() > 0:
124             item_d['flowcells'] = ','.join([ lts.flowcell.flowcell_id for lts in item.longtermstorage_set.all() ])
125         else:
126             item_d['flowcells'] = ''
127
128         item_d['type'] = item.item_type.name
129         rows.append(item_d)
130
131     d['rows'] = rows
132
133     return HttpResponse(json.dumps(d), content_type="application/javascript")
134
135 @login_required
136 def all_index(request):
137     """
138     Inventory Index View
139     """
140     # build changelist
141     item_changelist = HTSChangeList(request, Item,
142         list_filter=[],
143         search_fields=[],
144         list_per_page=200,
145         model_admin=ItemAdmin(Item, None)
146     )
147
148     context_dict = {
149         'item_changelist': item_changelist,
150         'page_name': 'Inventory Index'
151     }
152     context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
153
154     return render(request,
155                   'inventory/inventory_all_index.html',
156                   context_dict)
157
158 @login_required
159 def index(request):
160     """
161     Inventory Index View
162     """
163     # build changelist
164     item_changelist = HTSChangeList(request, ItemType,
165         list_filter=[],
166         search_fields=['name', 'description'],
167         list_per_page=50,
168         model_admin=ItemTypeAdmin(ItemType, None)
169     )
170
171     context_dict = {
172         'item_changelist': item_changelist,
173         'page_name': 'Inventory Index'
174     }
175     context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
176     return render(request,
177                   'inventory/inventory_index.html',
178                   context_dict)
179
180 @login_required
181 def itemtype_index(request, name):
182     """
183     Inventory Index View
184     """
185
186     name = name.replace('%20', ' ')
187
188     itemtype = ItemType.objects.get(name=name)
189
190     # build changelist
191     item_changelist = HTSChangeList(request, Item,
192         list_filter=[],
193         search_fields=[],
194         list_per_page=200,
195         model_admin=ItemAdmin(Item, None)
196     )
197
198     context_dict = {
199         'item_changelist': item_changelist,
200         'page_name': 'Inventory Index'
201     }
202     context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
203
204     return render(request,
205                   'inventory/inventory_itemtype_index.html',
206                   context_dict)
207
208
209 @login_required
210 def item_summary_by_barcode(request, barcode_id, msg=''):
211     """
212     Display a summary for an item by barcode
213     """
214     try:
215         item = Item.objects.get(barcode_id=barcode_id)
216     except ObjectDoesNotExist as e:
217         item = None
218
219     return item_summary_by_uuid(request, None, msg, item)
220
221
222 @login_required
223 def item_summary_by_uuid(request, uuid, msg='', item=None):
224     """
225     Display a summary for an item
226     """
227     # Use item instead of looking it up if it is passed.
228     if item is None:
229         try:
230             item = Item.objects.get(uuid=uuid)
231         except ObjectDoesNotExist as e:
232             item = None
233
234     context_dict = {
235         'page_name': 'Item Summary',
236         'item': item,
237         'uuid': uuid,
238         'msg': msg
239     }
240     context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
241
242     return render(request,
243                   'inventory/inventory_summary.html',
244                   context_dict)
245
246
247 def __expand_context(context, item):
248     """
249     If EXPAND_CONTEXT dictionary has item.item_type.name function registered, use it to expand context
250     """
251     if item.item_type.name in EXPAND_CONTEXT:
252         expand_func = EXPAND_CONTEXT[item.item_type.name]
253         expand_func(context, item)
254
255 def _item_print(item, request):
256     """
257     Prints an item given a type of item label to print
258     """
259     #FIXME: Hard coding this for now... need to abstract later.
260     context = {'item': item}
261     __expand_context(context, item)
262
263     # Print using barcode_id
264     if not item.force_use_uuid and (item.barcode_id is None or len(item.barcode_id.strip())):
265         context['use_uuid'] = False
266         msg = 'Printing item with barcode id: %s' % (item.barcode_id)
267     # Print using uuid
268     else:
269         context['use_uuid'] = True
270         msg = 'Printing item with UUID: %s' % (item.uuid)
271
272     printer_template = getPrinterTemplateByType(item.item_type)
273
274     c = RequestContext(request, context)
275     t = Template(printer_template.template)
276     print_zpl_socket(t.render(c), host=printer_template.printer.ip_address)
277
278     return msg
279
280 @login_required
281 def item_print(request, uuid):
282     """
283     Print a label for a given item
284     """
285     try:
286         item = Item.objects.get(uuid=uuid)
287     except ObjectDoesNotExist as e:
288         item = None
289         msg = "Item with UUID %s does not exist" % (uuid)
290
291     if item is not None:
292         msg = _item_print(item, request)
293
294     return item_summary_by_uuid(request, uuid, msg)
295
296
297 def link_flowcell_and_device(request, flowcell, serial):
298     """
299     Updates database records of a flowcell being archived on a device with a particular serial #
300     """
301     assert flowcell is not None
302     assert serial is not None
303
304     LTS_UPDATED = False
305     SD_UPDATED = False
306     LIBRARY_UPDATED = False
307
308     ###########################################
309     # Retrieve Storage Device
310     try:
311         sd = Item.objects.get(barcode_id=serial)
312     except ObjectDoesNotExist as e:
313         msg = "Item with barcode_id of %s not found." % (serial)
314         raise ObjectDoesNotExist(msg)
315
316     ###########################################
317     # Retrieve FlowCell
318     try:
319         fc = FlowCell.objects.get(flowcell_id__startswith=flowcell)
320     except ObjectDoesNotExist as e:
321         msg = "FlowCell with flowcell_id of %s not found." % (flowcell)
322         raise ObjectDoesNotExist(msg)
323
324     ###########################################
325     # Retrieve or create LongTermStorage Object
326     count = fc.longtermstorage_set.count()
327     lts = None
328     if count > 1:
329         msg = "There really should only be one longtermstorage object per flowcell"
330         raise ValueError(msg)
331     elif count == 1:
332         # lts already attached to flowcell
333         lts = fc.longtermstorage_set.all()[0]
334     else:
335         lts = LongTermStorage()
336         # Attach flowcell
337         lts.flowcell = fc
338         # Need a primary keey before linking to storage devices
339         lts.save()
340         LTS_UPDATED = True
341
342
343     ############################################
344     # Link Storage to Flowcell
345
346     # Add a link to this storage device if it is not already linked.
347     if sd not in lts.storage_devices.all():
348         lts.storage_devices.add(sd)
349         SD_UPDATED = True
350
351     ###########################################
352     # Add Library Links to LTS
353
354     for lane in fc.lane_set.all():
355         if lane.library not in lts.libraries.all():
356             lts.libraries.add(lane.library)
357             LIBRARY_UPDATED = True
358
359     # Save Changes
360     lts.save()
361
362     msg = ['Success:']
363     if LTS_UPDATED or SD_UPDATED or LIBRARY_UPDATED:
364         msg.append('  LongTermStorage (LTS) Created: %s' % (LTS_UPDATED))
365         msg.append('   Storage Device Linked to LTS: %s' % (SD_UPDATED))
366         msg.append('       Libraries updated in LTS: %s' % (LIBRARY_UPDATED))
367     else:
368         msg.append('  No Updates Needed.')
369
370     return HttpResponse('\n'.join(msg))