Update the inventory tracker code for the split from lanes being
[htsworkflow.git] / htsworkflow / frontend / inventory / views.py
1 from htsworkflow.frontend.inventory.models import Item, LongTermStorage, ItemType
2 from htsworkflow.frontend.inventory.bcmagic import item_search
3 from htsworkflow.frontend.bcmagic.plugin import register_search_plugin
4 from htsworkflow.frontend.experiments.models import FlowCell
5 from htsworkflow.frontend.bcmagic.forms import BarcodeMagicForm
6 from htsworkflow.frontend.bcmagic.utils import print_zpl_socket
7 from htsworkflow.frontend import settings
8 #from htsworkflow.util.jsonutil import encode_json
9
10 from django.core.exceptions import ObjectDoesNotExist
11 from django.http import HttpResponse, HttpResponseRedirect
12 from django.shortcuts import render_to_response
13 from django.template import RequestContext, Template
14 from django.template.loader import get_template
15 from django.contrib.auth.decorators import login_required
16
17 register_search_plugin('Inventory Item', item_search)
18
19 try:
20     import json
21 except ImportError, e:
22     import simplejson as 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 index(request):
137     """
138     Inventory Index View
139     """
140     context_dict = {
141         'page_name': 'Inventory Index'
142     }
143     context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
144     
145     return render_to_response('inventory/inventory_index.html',
146                               context_dict,
147                               context_instance=RequestContext(request))
148     
149
150 @login_required
151 def item_summary_by_barcode(request, barcode_id, msg=''):
152     """
153     Display a summary for an item by barcode
154     """
155     try:
156         item = Item.objects.get(barcode_id=barcode_id)
157     except ObjectDoesNotExist, e:
158         item = None
159         
160     return item_summary_by_uuid(request, None, msg, item)
161     
162
163 @login_required
164 def item_summary_by_uuid(request, uuid, msg='', item=None):
165     """
166     Display a summary for an item
167     """
168     # Use item instead of looking it up if it is passed.
169     if item is None:
170         try:
171             item = Item.objects.get(uuid=uuid)
172         except ObjectDoesNotExist, e:
173             item = None
174     
175     context_dict = {
176         'page_name': 'Item Summary',
177         'item': item,
178         'uuid': uuid,
179         'msg': msg
180     }
181     context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
182     
183     return render_to_response('inventory/inventory_summary.html',
184                               context_dict,
185                               context_instance=RequestContext(request))
186
187
188
189     
190     
191
192 def __expand_context(context, item):
193     """
194     If EXPAND_CONTEXT dictionary has item.item_type.name function registered, use it to expand context
195     """
196     if item.item_type.name in EXPAND_CONTEXT:
197         expand_func = EXPAND_CONTEXT[item.item_type.name]
198         expand_func(context, item)
199
200 def _item_print(item, request):
201     """
202     Prints an item given a type of item label to print
203     """
204     #FIXME: Hard coding this for now... need to abstract later.
205     context = {'item': item}
206     __expand_context(context, item)
207     
208     # Print using barcode_id
209     if not item.force_use_uuid and (item.barcode_id is None or len(item.barcode_id.strip())):
210         context['use_uuid'] = False
211         msg = 'Printing item with barcode id: %s' % (item.barcode_id)
212     # Print using uuid
213     else:
214         context['use_uuid'] = True
215         msg = 'Printing item with UUID: %s' % (item.uuid)
216     
217     printer_template = getPrinterTemplateByType(item.item_type)
218     
219     c = RequestContext(request, context)
220     t = Template(printer_template.template)
221     print_zpl_socket(t.render(c), host=printer_template.printer.ip_address)
222     
223     return msg
224
225 @login_required
226 def item_print(request, uuid):
227     """
228     Print a label for a given item
229     """
230     try:
231         item = Item.objects.get(uuid=uuid)
232     except ObjectDoesNotExist, e:
233         item = None
234         msg = "Item with UUID %s does not exist" % (uuid)
235     
236     if item is not None:
237         msg = _item_print(item, request)
238     
239     return item_summary_by_uuid(request, uuid, msg)
240
241
242 def link_flowcell_and_device(request, flowcell, serial):
243     """
244     Updates database records of a flowcell being archived on a device with a particular serial #
245     """
246     assert flowcell is not None
247     assert serial is not None
248     
249     LTS_UPDATED = False
250     SD_UPDATED = False
251     LIBRARY_UPDATED = False
252         
253     ###########################################
254     # Retrieve Storage Device
255     try:
256         sd = Item.objects.get(barcode_id=serial)
257     except ObjectDoesNotExist, e:
258         msg = "Item with barcode_id of %s not found." % (serial)
259         raise ObjectDoesNotExist(msg)
260     
261     ###########################################
262     # Retrieve FlowCell
263     try:    
264         fc = FlowCell.objects.get(flowcell_id=flowcell)
265     except ObjectDoesNotExist, e:
266         msg = "FlowCell with flowcell_id of %s not found." % (flowcell)
267         raise ObjectDoesNotExist(msg)
268     
269     ###########################################
270     # Retrieve or create LongTermStorage Object
271     count = fc.longtermstorage_set.count()
272     lts = None
273     if count > 1:
274         msg = "There really should only be one longtermstorage object per flowcell"
275         raise ValueError, msg
276     elif count == 1:
277         # lts already attached to flowcell
278         lts = fc.longtermstorage_set.all()[0]
279     else:
280         lts = LongTermStorage()
281         # Attach flowcell
282         lts.flowcell = fc
283         # Need a primary keey before linking to storage devices
284         lts.save()
285         LTS_UPDATED = True
286         
287         
288     ############################################
289     # Link Storage to Flowcell
290     
291     # Add a link to this storage device if it is not already linked.
292     if sd not in lts.storage_devices.all():
293         lts.storage_devices.add(sd)
294         SD_UPDATED = True
295     
296     ###########################################
297     # Add Library Links to LTS
298
299     for lane in fc.lane_set.all():
300         if lane.library not in lts.libraries.all():
301             lts.libraries.add(lane.library)
302             LIBRARY_UPDATED = True        
303         
304     # Save Changes
305     lts.save()
306     
307     msg = ['Success:']
308     if LTS_UPDATED or SD_UPDATED or LIBRARY_UPDATED:
309         msg.append('  LongTermStorage (LTS) Created: %s' % (LTS_UPDATED))
310         msg.append('   Storage Device Linked to LTS: %s' % (SD_UPDATED))
311         msg.append('       Libraries updated in LTS: %s' % (LIBRARY_UPDATED))
312     else:
313         msg.append('  No Updates Needed.')
314     
315     return HttpResponse('\n'.join(msg))