7049320c9f79b5fd7adbc0ca4d6dbe3856dc97be
[htsworkflow.git] / htsworkflow / frontend / inventory / views.py
1 from htsworkflow.frontend.inventory.models import Item, LongTermStorage
2 from htsworkflow.frontend.experiments.models import FlowCell
3 from htsworkflow.frontend.bcmagic.forms import BarcodeMagicForm
4 from htsworkflow.frontend.bcprinter.util import print_zpl_socket
5 from htsworkflow.frontend import settings
6 #from htsworkflow.util.jsonutil import encode_json
7
8 from django.core.exceptions import ObjectDoesNotExist
9 from django.http import HttpResponse, HttpResponseRedirect
10 from django.shortcuts import render_to_response
11 from django.template import RequestContext
12 from django.template.loader import get_template
13 from django.contrib.auth.decorators import login_required
14
15 try:
16     import json
17 except ImportError, e:
18     import simplejson as json
19
20 INVENTORY_CONTEXT_DEFAULTS = {
21     'app_name': 'Inventory Tracker',
22     'bcmagic': BarcodeMagicForm()
23 }
24
25 INVENTORY_ITEM_PRINT_DEFAULTS = {
26     'default': 'inventory/default.zpl',
27     'host': settings.BCPRINTER_PRINTER1_HOST
28 }
29
30 def getTemplateByType(item_type):
31     """
32     returns template to use given item_type
33     """
34     if item_type in INVENTORY_ITEM_PRINT_DEFAULTS:
35         return INVENTORY_ITEM_PRINT_DEFAULTS[item_type]
36     else:
37         return INVENTORY_ITEM_PRINT_DEFAULTS['default']
38
39 @login_required
40 def data_items(request):
41     """
42     Returns items in json format
43     """
44     item_list = Item.objects.all()
45     d = { 'results': len(item_list) }
46     rows = []
47     
48     for item in item_list:
49         item_d = {}
50         item_d['uuid'] = item.uuid
51         item_d['barcode_id'] = item.barcode_id
52         item_d['model_id'] = item.item_info.model_id
53         item_d['part_number'] = item.item_info.part_number
54         item_d['lot_number'] = item.item_info.lot_number
55         item_d['vendor'] = item.item_info.vendor.name
56         item_d['creation_date'] = item.creation_date.strftime('%Y-%m-%d %H:%M:%S')
57         item_d['modified_date'] = item.modified_date.strftime('%Y-%m-%d %H:%M:%S')
58         item_d['location'] = item.location.name
59         
60         # Item status if exists
61         if item.status is None:
62             item_d['status'] = ''
63         else:
64             item_d['status'] = item.status.name
65             
66         # Stored flowcells on device
67         if item.longtermstorage_set.count() > 0:
68             item_d['flowcells'] = ','.join([ lts.flowcell.flowcell_id for lts in item.longtermstorage_set.all() ])
69         else:
70             item_d['flowcells'] = ''
71         
72         item_d['type'] = item.item_type.name
73         rows.append(item_d)
74     
75     d['rows'] = rows
76     
77     return HttpResponse(json.dumps(d), content_type="application/javascript")
78
79 @login_required
80 def index(request):
81     """
82     Inventory Index View
83     """
84     context_dict = {
85         'page_name': 'Inventory Index'
86     }
87     context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
88     
89     return render_to_response('inventory/inventory_index.html',
90                               context_dict,
91                               context_instance=RequestContext(request))
92     
93 @login_required
94 def item_summary(request, uuid, msg=''):
95     """
96     Display a summary for an item
97     """
98     try:
99         item = Item.objects.get(uuid=uuid)
100     except ObjectDoesNotExist, e:
101         item = None
102     
103     context_dict = {
104         'page_name': 'Item Summary',
105         'item': item,
106         'uuid': uuid,
107         'msg': msg
108     }
109     context_dict.update(INVENTORY_CONTEXT_DEFAULTS)
110     
111     return render_to_response('inventory/inventory_summary.html',
112                               context_dict,
113                               context_instance=RequestContext(request))
114
115
116 def _item_print(item, request):
117     """
118     Prints an item given a type of item label to print
119     """
120     #FIXME: Hard coding this for now... need to abstract later.
121     context = {'item': item}
122     
123     # Print using barcode_id
124     if not item.force_use_uuid and (item.barcode_id is None or len(item.barcode_id.strip())):
125         context['use_uuid'] = False
126         msg = 'Printing item with barcode id: %s' % (item.barcode_id)
127     # Print using uuid
128     else:
129         context['use_uuid'] = True
130         msg = 'Printing item with UUID: %s' % (item.uuid)
131     
132     c = RequestContext(request, context)
133     t = get_template(getTemplateByType(item.item_type.name))
134     print_zpl_socket(t.render(c))
135     
136     return msg
137
138 @login_required
139 def item_print(request, uuid):
140     """
141     Print a label for a given item
142     """
143     try:
144         item = Item.objects.get(uuid=uuid)
145     except ObjectDoesNotExist, e:
146         item = None
147         msg = "Item with UUID %s does not exist" % (uuid)
148     
149     if item is not None:
150         msg = _item_print(item, request)
151     
152     return item_summary(request, uuid, msg)
153
154
155 def link_flowcell_and_device(request, flowcell, serial):
156     """
157     Updates database records of a flowcell being archived on a device with a particular serial #
158     """
159     assert flowcell is not None
160     assert serial is not None
161     
162     LTS_UPDATED = False
163     SD_UPDATED = False
164     LIBRARY_UPDATED = False
165         
166     ###########################################
167     # Retrieve Storage Device
168     try:
169         sd = Item.objects.get(barcode_id=serial)
170     except ObjectDoesNotExist, e:
171         msg = "Item with barcode_id of %s not found." % (serial)
172         raise ObjectDoesNotExist(msg)
173     
174     ###########################################
175     # Retrieve FlowCell
176     try:    
177         fc = FlowCell.objects.get(flowcell_id=flowcell)
178     except ObjectDoesNotExist, e:
179         msg = "FlowCell with flowcell_id of %s not found." % (flowcell)
180         raise ObjectDoesNotExist(msg)
181     
182     ###########################################
183     # Retrieve or create LongTermStorage Object
184     count = fc.longtermstorage_set.count()
185     lts = None
186     if count > 1:
187         msg = "There really should only be one longtermstorage object per flowcell"
188         raise ValueError, msg
189     elif count == 1:
190         # lts already attached to flowcell
191         lts = fc.longtermstorage_set.all()[0]
192     else:
193         lts = LongTermStorage()
194         # Attach flowcell
195         lts.flowcell = fc
196         # Need a primary keey before linking to storage devices
197         lts.save()
198         LTS_UPDATED = True
199         
200         
201     ############################################
202     # Link Storage to Flowcell
203     
204     # Add a link to this storage device if it is not already linked.
205     if sd not in lts.storage_devices.all():
206         lts.storage_devices.add(sd)
207         SD_UPDATED = True
208     
209     ###########################################
210     # Add Library Links to LTS
211     
212     if fc.lane_1_library not in lts.libraries.all():
213         lts.libraries.add(fc.lane_1_library)
214         LIBRARY_UPDATED = True
215         print 1
216     
217     if fc.lane_2_library not in lts.libraries.all():
218         lts.libraries.add(fc.lane_2_library)
219         LIBRARY_UPDATED = True
220         print 2
221     
222     if fc.lane_3_library not in lts.libraries.all():
223         lts.libraries.add(fc.lane_3_library)
224         LIBRARY_UPDATED = True
225         print 3
226     
227     if fc.lane_4_library not in lts.libraries.all():
228         lts.libraries.add(fc.lane_4_library)
229         LIBRARY_UPDATED = True
230         print 4
231     
232     
233     if fc.lane_5_library not in lts.libraries.all():
234         lts.libraries.add(fc.lane_5_library)
235         LIBRARY_UPDATED = True
236         print 5
237     
238     if fc.lane_6_library not in lts.libraries.all():
239         lts.libraries.add(fc.lane_6_library)
240         LIBRARY_UPDATED = True
241         print 6
242     
243     if fc.lane_7_library not in lts.libraries.all():
244         lts.libraries.add(fc.lane_7_library)
245         LIBRARY_UPDATED = True
246         print 7
247     
248     if fc.lane_8_library not in lts.libraries.all():
249         lts.libraries.add(fc.lane_8_library)
250         LIBRARY_UPDATED = True
251         print 8
252         
253     # Save Changes
254     lts.save()
255     
256     msg = ['Success:']
257     if LTS_UPDATED or SD_UPDATED or LIBRARY_UPDATED:
258         msg.append('  LongTermStorage (LTS) Created: %s' % (LTS_UPDATED))
259         msg.append('   Storage Device Linked to LTS: %s' % (SD_UPDATED))
260         msg.append('       Libraries updated in LTS: %s' % (LIBRARY_UPDATED))
261     else:
262         msg.append('  No Updates Needed.')
263     
264     return HttpResponse('\n'.join(msg))