1 from htsworkflow.frontend.samples.changelist import ChangeList
2 from htsworkflow.frontend.inventory.models import Item, LongTermStorage, ItemType
3 from htsworkflow.frontend.inventory.bcmagic import item_search
4 from htsworkflow.frontend.bcmagic.plugin import register_search_plugin
5 from htsworkflow.frontend.experiments.models import FlowCell
6 from htsworkflow.frontend.bcmagic.forms import BarcodeMagicForm
7 from htsworkflow.frontend.bcmagic.utils import print_zpl_socket
9 from django.conf import settings
10 from django.contrib.auth.decorators import login_required
11 from django.core.exceptions import ObjectDoesNotExist
12 from django.http import HttpResponse, HttpResponseRedirect
13 from django.shortcuts import render_to_response
14 from django.template import RequestContext, Template
15 from django.template.loader import get_template
17 register_search_plugin('Inventory Item', item_search)
21 except ImportError, e:
22 import simplejson as json
24 INVENTORY_CONTEXT_DEFAULTS = {
25 'app_name': 'Inventory Tracker',
26 'bcmagic': BarcodeMagicForm()
29 def __flowcell_rundate_sort(x, y):
33 if x.run_date > y.run_date:
35 elif x.run_date == y.run_date:
40 def __expand_longtermstorage_context(context, item):
42 Expand information for LongTermStorage
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() ])
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
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]
65 'Hard Drive': __expand_longtermstorage_context
68 #INVENTORY_ITEM_PRINT_DEFAULTS = {
69 # 'Hard Drive': 'inventory/hard_drive_shell.zpl',
70 # 'default': 'inventory/default.zpl',
71 # 'host': settings.BCPRINTER_PRINTER1_HOST
74 def getPrinterTemplateByType(item_type):
76 returns template to use given item_type
78 assert item_type.printertemplate_set.count() < 2
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
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)
92 return printer_template
96 def data_items(request):
98 Returns items in json format
100 item_list = Item.objects.all()
101 d = { 'results': len(item_list) }
104 for item in item_list:
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
116 # Item status if exists
117 if item.status is None:
118 item_d['status'] = ''
120 item_d['status'] = item.status.name
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() ])
126 item_d['flowcells'] = ''
128 item_d['type'] = item.item_type.name
133 return HttpResponse(json.dumps(d), content_type="application/javascript")
136 def all_index(request):
141 item_changelist = ChangeList(request, Item,
145 queryset=Item.objects.all()
149 'item_changelist': item_changelist,
150 'page_name': 'Inventory Index'
152 context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
154 return render_to_response('inventory/inventory_all_index.html',
156 context_instance=RequestContext(request))
164 item_changelist = ChangeList(request, Item,
166 search_fields=['name'],
168 queryset=ItemType.objects.all()
172 'item_changelist': item_changelist,
173 'page_name': 'Inventory Index'
175 context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
177 return render_to_response('inventory/inventory_index.html',
179 context_instance=RequestContext(request))
182 def itemtype_index(request, name):
187 name = name.replace('%20', ' ')
189 itemtype = ItemType.objects.get(name=name)
192 item_changelist = ChangeList(request, Item,
196 queryset=itemtype.item_set.all()
200 'item_changelist': item_changelist,
201 'page_name': 'Inventory Index'
203 context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
205 return render_to_response('inventory/inventory_itemtype_index.html',
207 context_instance=RequestContext(request))
211 def item_summary_by_barcode(request, barcode_id, msg=''):
213 Display a summary for an item by barcode
216 item = Item.objects.get(barcode_id=barcode_id)
217 except ObjectDoesNotExist, e:
220 return item_summary_by_uuid(request, None, msg, item)
224 def item_summary_by_uuid(request, uuid, msg='', item=None):
226 Display a summary for an item
228 # Use item instead of looking it up if it is passed.
231 item = Item.objects.get(uuid=uuid)
232 except ObjectDoesNotExist, e:
236 'page_name': 'Item Summary',
241 context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
243 return render_to_response('inventory/inventory_summary.html',
245 context_instance=RequestContext(request))
252 def __expand_context(context, item):
254 If EXPAND_CONTEXT dictionary has item.item_type.name function registered, use it to expand context
256 if item.item_type.name in EXPAND_CONTEXT:
257 expand_func = EXPAND_CONTEXT[item.item_type.name]
258 expand_func(context, item)
260 def _item_print(item, request):
262 Prints an item given a type of item label to print
264 #FIXME: Hard coding this for now... need to abstract later.
265 context = {'item': item}
266 __expand_context(context, item)
268 # Print using barcode_id
269 if not item.force_use_uuid and (item.barcode_id is None or len(item.barcode_id.strip())):
270 context['use_uuid'] = False
271 msg = 'Printing item with barcode id: %s' % (item.barcode_id)
274 context['use_uuid'] = True
275 msg = 'Printing item with UUID: %s' % (item.uuid)
277 printer_template = getPrinterTemplateByType(item.item_type)
279 c = RequestContext(request, context)
280 t = Template(printer_template.template)
281 print_zpl_socket(t.render(c), host=printer_template.printer.ip_address)
286 def item_print(request, uuid):
288 Print a label for a given item
291 item = Item.objects.get(uuid=uuid)
292 except ObjectDoesNotExist, e:
294 msg = "Item with UUID %s does not exist" % (uuid)
297 msg = _item_print(item, request)
299 return item_summary_by_uuid(request, uuid, msg)
302 def link_flowcell_and_device(request, flowcell, serial):
304 Updates database records of a flowcell being archived on a device with a particular serial #
306 assert flowcell is not None
307 assert serial is not None
311 LIBRARY_UPDATED = False
313 ###########################################
314 # Retrieve Storage Device
316 sd = Item.objects.get(barcode_id=serial)
317 except ObjectDoesNotExist, e:
318 msg = "Item with barcode_id of %s not found." % (serial)
319 raise ObjectDoesNotExist(msg)
321 ###########################################
324 fc = FlowCell.objects.get(flowcell_id__startswith=flowcell)
325 except ObjectDoesNotExist, e:
326 msg = "FlowCell with flowcell_id of %s not found." % (flowcell)
327 raise ObjectDoesNotExist(msg)
329 ###########################################
330 # Retrieve or create LongTermStorage Object
331 count = fc.longtermstorage_set.count()
334 msg = "There really should only be one longtermstorage object per flowcell"
335 raise ValueError, msg
337 # lts already attached to flowcell
338 lts = fc.longtermstorage_set.all()[0]
340 lts = LongTermStorage()
343 # Need a primary keey before linking to storage devices
348 ############################################
349 # Link Storage to Flowcell
351 # Add a link to this storage device if it is not already linked.
352 if sd not in lts.storage_devices.all():
353 lts.storage_devices.add(sd)
356 ###########################################
357 # Add Library Links to LTS
359 for lane in fc.lane_set.all():
360 if lane.library not in lts.libraries.all():
361 lts.libraries.add(lane.library)
362 LIBRARY_UPDATED = True
368 if LTS_UPDATED or SD_UPDATED or LIBRARY_UPDATED:
369 msg.append(' LongTermStorage (LTS) Created: %s' % (LTS_UPDATED))
370 msg.append(' Storage Device Linked to LTS: %s' % (SD_UPDATED))
371 msg.append(' Libraries updated in LTS: %s' % (LIBRARY_UPDATED))
373 msg.append(' No Updates Needed.')
375 return HttpResponse('\n'.join(msg))