forked from sahana/eden
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinv.py
1685 lines (1494 loc) · 72.7 KB
/
inv.py
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Inventory Management
A module to record inventories of items at a locations (sites),
including Warehouses, Offices, Shelters & Hospitals
"""
module = request.controller
resourcename = request.function
if not settings.has_module(module):
raise HTTP(404, body="Module disabled: %s" % module)
# -----------------------------------------------------------------------------
def index():
""" Module's Home Page """
return s3db.cms_index(module, alt_function="index_alt")
# -----------------------------------------------------------------------------
def index_alt():
"""
Module homepage for non-Admin users when no CMS content found
"""
# Just redirect to the list of Warehouses
redirect(URL(f="warehouse"))
# -----------------------------------------------------------------------------
def index2():
"""
Alternative Application Home page
- custom View
"""
# Need CRUD String
table = s3db.table("cr_shelter", None)
module_name = settings.modules[module].name_nice
response.title = module_name
response.view = "inv/index.html"
if s3.debug:
# Start of TEST CODE for multiple dataTables,
#this also required views/inv/index.html to be modified
from s3.s3data import S3DataTable
representation = request.extension
if representation == "html" or get_vars.id == "warehouse_list_1":
resource = s3db.resource("inv_warehouse")
totalrows = resource.count()
list_fields = ["id",
"name",
"organisation_id",
]
orderby = "inv_warehouse.name asc"
if representation == "aadata":
query, orderby, left = resource.datatable_filter(list_fields, get_vars)
if orderby is None:
orderby = default_orderby
start = int(get_vars.iDisplayStart) if get_vars.iDisplayStart else 0
limit = int(get_vars.iDisplayLength) if get_vars.iDisplayLength else s3.ROWSPERPAGE
data = resource.select(list_fields,
start=start,
limit=limit,
orderby=orderby,
count=True,
represent=True)
filteredrows = data["numrows"]
if totalrows is None:
totalrows = filteredrows
rfields = data["rfields"]
rows = data["rows"]
dt = S3DataTable(rfields, rows)
dt.defaultActionButtons(resource)
if representation == "html":
warehouses = dt.html(totalrows,
filteredrows,
"warehouse_list_1",
dt_bFilter="true",
dt_group=2,
dt_ajax_url=URL(c="inv",
f="index2",
extension="aadata",
vars={"id":"warehouse_list_1"},
),
)
else:
warehouse = dt.json(totalrows,
filteredrows,
"warehouse_list_1",
int(get_vars.sEcho),
)
return warehouse
# Second Table
if representation == "html" or get_vars.id == "inventory_list_1":
if "Adjust" in request.post_vars:
if request.post_vars.selected == "":
inventory = "Well you could have selected something :("
else:
inventory = "Adjustment not currently supported... :-) you selected the following items: %s" % request.post_vars.selected
else:
resource = s3db.resource("inv_inv_item")
totalrows = resource.count()
table = resource.table
stable = s3db.supply_item
list_fields = ["id",
"site_id",
"item_id$name",
"quantity",
"pack_value",
"total_value",
]
orderby = "inv_inv_item.site_id asc"
if representation == "aadata":
query, orderby, left = resource.datatable_filter(list_fields, get_vars)
if orderby is None:
orderby = default_orderby
site_list = {}
data = resource.select(list_fields,
limit=None,
orderby=orderby,
count=True)
filteredrows = data["numrows"]
if totalrows is None:
totalrows = filteredrows
rows = data["rows"]
for row in rows:
site_id = row["inv_inv_item.site_id"]
if site_id not in site_list:
site_list[site_id] = 1
else:
site_list[site_id] += 1
formatted_site_list = {}
repr = table.site_id.represent
for (key,value) in site_list.items():
formatted_site_list[str(repr(key))] = value
if isinstance(orderby, bool):
orderby = [table.site_id, stable.name, ~table.quantity]
start = int(get_vars.iDisplayStart) if get_vars.iDisplayStart else 0
limit = int(get_vars.iDisplayLength) if get_vars.iDisplayLength else s3.ROWSPERPAGE
data = resource.select(list_fields,
orderby=orderby,
start=start,
limit=limit,
represent=True)
rfields = data["rfields"]
rows = data["rows"]
dt = S3DataTable(rfields,
rows,
orderby=orderby,
)
custom_actions = [dict(label=str(T("Warehouse")),
_class="action-icon",
img="/%s/static/img/markers/gis_marker.image.Agri_Commercial_Food_Distribution_Center_S1.png" % appname,
url=URL(c="inv", f="warehouse",
args=["[id]", "update"]
)
),
]
dt.defaultActionButtons(resource, custom_actions)
if representation == "html":
rows = current.db(table.quantity<100.0).select(table.id, table.quantity)
errorList = []
warningList = []
alertList = []
for row in rows:
if row.quantity < 0.0:
errorList.append(row.id)
elif row.quantity == 0.0:
warningList.append(row.id)
else:
alertList.append(row.id)
inventory = dt.html(totalrows,
filteredrows,
"inventory_list_1",
dt_bFilter="true",
dt_group=[1,2],
dt_group_totals=[formatted_site_list],
dt_action_col=-1,
dt_ajax_url=URL(c="inv",
f="index2",
extension="aadata",
vars={"id":"inventory_list_1"},
),
dt_bulk_actions = "Adjust",
dt_styles = {"dtdisable": errorList,
"dtwarning": warningList,
"dtalert": alertList,
},
#dt_text_maximum_len = 10,
#dt_text_condense_len = 8,
#dt_group_space = "true",
dt_shrink_groups = "accordion",
#dt_shrink_groups = "individual",
)
s3.actions = None
elif representation == "aadata":
inventory = dt.json(totalrows,
filteredrows,
"inventory_list_1",
int(get_vars.sEcho),
dt_action_col=-1,
dt_bulk_actions = "Adjust",
dt_group_totals=[formatted_site_list],
)
return inventory
else:
# Probably not the way to do it.... but
s3db.configure("inv_inv_item",
list_fields=list_fields,
report_groupby="site_id",
pdf_groupby="site_id",
)
s3.filter = filter
r = s3_request("inv", "inv_item",
vars={"orderby" : orderby})
r.resource = resource
output = r(
pdf_groupby='site_id',
dt_group=1,
)
return output
# Third table
if representation == "html" or get_vars.id == "supply_list_1":
resource = s3db.resource("supply_item")
list_fields = ["id",
"name",
"um",
"model",
]
orderby = "inv_inv_item.site_id asc"
if representation == "aadata":
query, orderby, left = resource.datatable_filter(list_fields, get_vars)
if orderby is None:
orderby = default_orderby
data = resource.select(list_fields,
limit=None,
orderby=orderby,
count=True,
represent=True)
rows = data["rows"]
rfields = data["rfields"]
numrows = data["numrows"]
dt = S3DataTable(rfields, rows)
dt.defaultActionButtons(resource)
if representation == "html":
supply_items = dt.html(numrows,
numrows,
"supply_list_1",
dt_displayLength=10,
dt_action_col=1,
dt_ajax_url=URL(c="inv",
f="index2",
extension="aadata",
vars={"id": "supply_list_1"},
),
)
else:
supply_items = dt.json(numrows,
numrows,
"supply_list_1",
int(get_vars.sEcho),
dt_action_col=1,
)
return supply_items
r = s3_request(prefix = "inv", name = "inv_item")
return dict(module_name=module_name,
warehouses = warehouses,
inventory = inventory,
supply_items = supply_items,
r = r,
)
# End of TEST CODE
return dict(module_name=module_name)
# -----------------------------------------------------------------------------
def warehouse():
"""
RESTful CRUD controller
"""
if "viewing" in get_vars:
viewing = get_vars.viewing
tn, id = viewing.split(".", 1)
if tn == "inv_warehouse":
request.args.insert(0, id)
# CRUD pre-process
def prep(r):
if r.component:
component_name = r.component_name
if component_name == "inv_item":
# Filter out items which are already in this inventory
s3db.inv_prep(r)
# Remove the Warehouse Name from the list_fields
list_fields = s3db.get_config("inv_inv_item", "list_fields")
try:
list_fields.remove("site_id")
s3db.configure("inv_inv_item", list_fields=list_fields)
except:
pass
elif component_name == "recv" or \
component_name == "send":
# Filter out items which are already in this inventory
s3db.inv_prep(r)
elif component_name == "human_resource":
s3db.org_site_staff_config(r)
elif component_name == "req":
s3db.req_prep(r)
if r.method != "update" and r.method != "read":
# Hide fields which don't make sense in a Create form
# inc list_create (list_fields over-rides)
s3db.req_create_form_mods()
elif component_name == "asset":
# Default/Hide the Organisation & Site fields
record = r.record
atable = s3db.asset_asset
field = atable.organisation_id
field.default = record.organisation_id
field.readable = field.writable = False
field = atable.site_id
field.default = record.site_id
field.readable = field.writable = False
# Stay within Warehouse tab
s3db.configure("asset_asset",
create_next = None)
elif r.id:
r.table.obsolete.readable = r.table.obsolete.writable = True
# "show_obsolete" var option can be added (btn?) later to
# disable this filter
if r.method in [None, "list"] and \
not r.vars.get("show_obsolete", False):
r.resource.add_filter(db.inv_warehouse.obsolete != True)
return True
s3.prep = prep
# CRUD post-process
def postp(r, output):
if r.interactive and not r.component and r.method != "import":
# Change Action buttons to open Stock Tab by default
read_url = URL(f="warehouse", args=["[id]", "inv_item"])
update_url = URL(f="warehouse", args=["[id]", "inv_item"])
s3_action_buttons(r,
read_url=read_url,
update_url=update_url)
else:
cname = r.component_name
if cname == "human_resource":
# Modify action button to open staff instead of human_resource
read_url = URL(c="hrm", f="staff", args=["[id]"])
update_url = URL(c="hrm", f="staff", args=["[id]", "update"])
s3_action_buttons(r, read_url=read_url,
#delete_url=delete_url,
update_url=update_url)
if "add_btn" in output:
del output["add_btn"]
return output
s3.postp = postp
if "extra_data" in get_vars:
resourcename = "inv_item"
else:
resourcename = "warehouse"
csv_stylesheet = "%s.xsl" % resourcename
output = s3_rest_controller(module, resourcename,
rheader=s3db.inv_rheader,
hide_filter = {"inv_item": False,
"_default": True,
},
csv_template = resourcename,
csv_stylesheet = csv_stylesheet,
# Extra fields for CSV uploads:
#csv_extra_fields = [
# dict(label="Organisation",
# field=s3db.org_organisation_id(comment=None))
#]
)
if "add_btn" in output:
del output["add_btn"]
return output
# -----------------------------------------------------------------------------
def supplier():
"""
Filtered version of the organisation() REST controller
"""
get_vars["organisation_type.name"] = "Supplier"
# Load model
table = s3db.org_organisation
# Modify CRUD Strings
s3.crud_strings.org_organisation = Storage(
label_create = T("Create Supplier"),
title_display = T("Supplier Details"),
title_list = T("Suppliers"),
title_update = T("Edit Supplier"),
title_upload = T("Import Suppliers"),
label_list_button = T("List Suppliers"),
label_delete_button = T("Delete Supplier"),
msg_record_created = T("Supplier added"),
msg_record_modified = T("Supplier updated"),
msg_record_deleted = T("Supplier deleted"),
msg_list_empty = T("No Suppliers currently registered")
)
# Modify filter_widgets
filter_widgets = s3db.get_config("org_organisation", "filter_widgets")
# Remove type (always 'Supplier')
filter_widgets.pop(1)
# Remove sector (not relevant)
filter_widgets.pop(1)
return s3db.org_organisation_controller()
# =============================================================================
def inv_item():
""" REST Controller """
# If this url has a viewing track items then redirect to track_movement
viewing = get_vars.get("viewing", None)
if viewing:
tn, id = viewing.split(".", 1)
if tn == "inv_track_item":
table = s3db.inv_track_item
record = db(table.id == id).select(table.item_id,
limitby=(0, 1)).first()
redirect(URL(c = "inv",
f = "track_movement",
args = [],
vars = {"viewing" : "%s.%s" % ("inv_inv_item", record.item_id)}
))
tablename = "inv_inv_item"
# Load model to be able to override CRUD string(s)
table = s3db[tablename]
# Limit site_id to sites the user has permissions for
auth.permitted_facilities(table=table,
error_msg=T("You do not have permission for any site to add an inventory item."))
s3.crud_strings[tablename].msg_list_empty = T("No Stock currently registered")
report = get_vars.get("report")
if report == "mon":
s3.crud_strings[tablename].update(dict(
title_list = T("Monetization Report"),
subtitle_list = T("Monetization Details"),
#msg_list_empty = T("No Stock currently registered"),
))
s3db.configure(tablename,
list_fields = ["id",
(T("Donor"), "supply_org_id"),
(T("Items/Description"), "item_id"),
(T("Quantity"), "quantity"),
(T("Unit"), "item_pack_id"),
(T("Unit Value"), "pack_value"),
(T("Total Value"), "total_value"),
(T("Remarks"), "comments"),
"status",
]
)
else:
s3db.configure(tablename,
insertable = settings.get_inv_direct_stock_edits(),
list_fields = ["id",
"site_id",
"item_id",
#(T("Item Code"), "item_code"),
"item_id$item_code",
#(T("Category"), "item_category"),
"item_id$item_category_id",
"quantity",
"pack_value",
#(T("Total Value"), "total_value"),
]
)
if len(request.args) > 1 and request.args[1] == "track_item":
# remove CRUD generated buttons in the tabs
s3db.configure("inv_track_item",
create=False,
listadd=False,
editable=False,
deletable=False,
)
else:
s3.filter = (table.quantity != 0)
def prep(r):
if r.method != "report":
s3.dataTable_group = 1
return True
s3.prep = prep
# Import pre-process
def import_prep(data):
"""
Deletes all Stock records of the organisation/branch
before processing a new data import
"""
resource, tree = data
xml = current.xml
tag = xml.TAG
att = xml.ATTRIBUTE
if s3.importerReplace:
if tree is not None:
root = tree.getroot()
expr = "/%s/%s[@%s='org_organisation']/%s[@%s='name']" % \
(tag.root, tag.resource, att.name, tag.data, att.field)
orgs = root.xpath(expr)
otable = s3db.org_organisation
stable = s3db.org_site
itable = s3db.inv_inv_item
for org in orgs:
org_name = org.get("value", None) or org.text
if org_name:
try:
org_name = json.loads(xml.xml_decode(org_name))
except:
pass
if org_name:
query = (otable.name == org_name) & \
(stable.organisation_id == otable.id) & \
(itable.site_id == stable.id)
resource = s3db.resource("inv_inv_item", filter=query)
# Use cascade=True so that the deletion gets
# rolled back if the import fails:
resource.delete(format="xml", cascade=True)
resource.skip_import = True
s3.import_prep = import_prep
# Upload for configuration (add replace option)
s3.importerPrep = lambda: dict(ReplaceOption=T("Remove existing data before import"))
output = s3_rest_controller(#csv_extra_fields = [dict(label="Organisation",
# field=s3db.org_organisation_id(comment=None))
# ],
pdf_paper_alignment = "Landscape",
pdf_table_autogrow = "B",
pdf_groupby = "site_id, item_id",
pdf_orderby = "expiry_date, supply_org_id",
rheader=s3db.inv_rheader,
)
if "add_btn" in output and not settings.get_inv_direct_stock_edits():
del output["add_btn"]
return output
# -----------------------------------------------------------------------------
def track_movement():
""" REST Controller """
table = s3db.inv_track_item
s3db.configure("inv_track_item",
create=False,
listadd=False,
editable=False,
deletable=False,
)
def prep(r):
if r.interactive:
if "viewing" in get_vars:
dummy, item_id = get_vars.viewing.split(".")
if item_id != "None":
filter = (table.send_inv_item_id == item_id ) | \
(table.recv_inv_item_id == item_id)
s3.filter = filter
return True
s3.prep = prep
output = s3_rest_controller("inv", "track_item",
rheader = s3db.inv_rheader,
)
if "add_btn" in output:
del output["add_btn"]
return output
# -----------------------------------------------------------------------------
def inv_item_quantity():
"""
"""
try:
item_id = request.args[0]
except:
raise HTTP(400, current.xml.json_message(False, 400, "No value provided!"))
table = s3db.inv_inv_item
ptable = db.supply_item_pack
query = (table.id == item_id) & \
(table.item_pack_id == ptable.id)
record = db(query).select(table.quantity,
ptable.quantity,
limitby=(0, 1)).first()
d = {"iquantity" : record.inv_inv_item.quantity,
"pquantity" : record.supply_item_pack.quantity,
}
output = json.dumps(d)
response.headers["Content-Type"] = "application/json"
return output
# -----------------------------------------------------------------------------
def inv_item_packs():
"""
Called by S3OptionsFilter to provide the pack options for a
particular Item
"""
try:
item_id = request.args[0]
except:
raise HTTP(400, current.xml.json_message(False, 400, "No value provided!"))
table = s3db.inv_inv_item
ptable = db.supply_item_pack
query = (table.id == item_id) & \
(table.item_id == ptable.item_id)
records = db(query).select(ptable.id,
ptable.name,
ptable.quantity)
output = records.json()
response.headers["Content-Type"] = "application/json"
return output
# =============================================================================
def send():
""" RESTful CRUD controller """
return s3db.inv_send_controller()
# ==============================================================================
def send_commit():
"""
Send a Shipment containing all items in a Commitment
"""
return s3db.req_send_commit()
# -----------------------------------------------------------------------------
def send_process():
""" Process a Shipment """
return s3db.inv_send_process()
# -----------------------------------------------------------------------------
def send_returns():
"""
This will cancel a shipment that has been sent
@todo need to roll back commitments
"""
try:
send_id = request.args[0]
except:
redirect(f="send")
stable = s3db.inv_send
if not auth.s3_has_permission("update", stable, record_id=send_id):
session.error = T("You do not have permission to return this sent shipment.")
send_record = db(stable.id == send_id).select(stable.status,
limitby=(0, 1)
).first()
inv_ship_status = s3db.inv_ship_status
if send_record.status == inv_ship_status["IN_PROCESS"]:
session.error = T("This shipment has not been sent - it cannot be returned because it can still be edited.")
if session.error:
redirect(URL(c="inv", f="send",
args=[send_id]))
rtable = s3db.inv_recv
tracktable = s3db.inv_track_item
# Okay no error so far, change the status to Returning
stable[send_id] = dict(status = inv_ship_status["RETURNING"],
owned_by_user = None,
owned_by_group = ADMIN)
recv_row = db(tracktable.send_id == send_id).select(tracktable.recv_id,
limitby = (0, 1)).first()
if recv_row:
recv_id = recv_row.recv_id
rtable[recv_id] = dict(date = request.utcnow,
status = inv_ship_status["RETURNING"],
owned_by_user = None,
owned_by_group = ADMIN)
# Set all track items to status of returning
db(tracktable.send_id == send_id).update(status = s3db.inv_tracking_status["RETURNING"])
session.confirmation = T("Sent Shipment has returned, indicate how many items will be returned to Warehouse.")
redirect(URL(c="inv", f="send",
args=[send_id, "track_item"]))
# -----------------------------------------------------------------------------
def return_process():
"""
Return some stock from a shipment back into the warehouse
"""
try:
send_id = request.args[0]
except:
redirect(f="send")
stable = s3db.inv_send
if not auth.s3_has_permission("update", stable, record_id=send_id):
session.error = T("You do not have permission to return this sent shipment.")
send_record = db(stable.id == send_id).select(stable.status,
limitby=(0, 1)
).first()
inv_ship_status = s3db.inv_ship_status
if send_record.status != inv_ship_status["RETURNING"]:
session.error = T("This shipment has not been returned.")
if session.error:
redirect(URL(c="inv", f="send",
args=[send_id]))
invtable = s3db.inv_inv_item
rtable = s3db.inv_recv
tracktable = s3db.inv_track_item
# Okay no error so far, let's move the goods back into the warehouse
# and then change the status to received
# Update Receive record & lock for editing
# Move each item to the site
track_rows = db(tracktable.send_id == send_id).select(tracktable.id,
tracktable.quantity,
tracktable.return_quantity,
tracktable.send_inv_item_id,
)
for track_item in track_rows:
send_inv_id = track_item.send_inv_item_id
return_qnty = track_item.return_quantity
if return_qnty == None:
return_qnty = 0
# update the receive quantity in the tracking record
tracktable[track_item.id] = dict(recv_quantity = track_item.quantity - return_qnty)
if return_qnty:
db(invtable.id == send_inv_id).update(quantity = invtable.quantity + return_qnty)
stable[send_id] = dict(status = inv_ship_status["RECEIVED"],
owned_by_user = None,
owned_by_group = ADMIN)
recv_row = db(tracktable.send_id == send_id).select(tracktable.recv_id,
limitby = (0, 1)).first()
if recv_row:
recv_id = recv_row.recv_id
rtable[recv_id] = dict(date = request.utcnow,
status = inv_ship_status["RECEIVED"],
owned_by_user = None,
owned_by_group = ADMIN)
# Change the status for all track items in this shipment to Received
db(tracktable.send_id == send_id).update(status = s3db.inv_tracking_status["RECEIVED"])
redirect(URL(f = "send",
args = [send_id]))
# -----------------------------------------------------------------------------
def send_cancel():
"""
This will cancel a shipment that has been sent
@todo need to roll back commitments
"""
try:
send_id = request.args[0]
except:
redirect(f="send")
stable = s3db.inv_send
if not auth.s3_has_permission("delete", stable, record_id=send_id):
session.error = T("You do not have permission to cancel this sent shipment.")
send_record = db(stable.id == send_id).select(stable.status,
limitby=(0, 1)).first()
inv_ship_status = s3db.inv_ship_status
if send_record.status != inv_ship_status["SENT"]:
session.error = T("This shipment has not been sent - it has NOT been canceled because can still be edited.")
if session.error:
redirect(URL(c="inv", f="send",
args=[send_id]))
rtable = s3db.inv_recv
tracktable = s3db.inv_track_item
# Okay no error so far, let's delete that baby
# Change the send and recv status to cancelled
db(stable.id == send_id).update(status = inv_ship_status["CANCEL"],
owned_by_user = None,
owned_by_group = ADMIN)
recv_row = db(tracktable.send_id == send_id).select(tracktable.recv_id,
limitby = (0, 1)).first()
if recv_row:
recv_id = recv_row.recv_id
db(rtable.id == recv_id).update(date = request.utcnow,
status = inv_ship_status["CANCEL"],
owned_by_user = None,
owned_by_group = ADMIN)
# Change the track items status to canceled and then delete them
# If they are linked to a request then the in transit total will also be reduced
# Records can only be deleted if the status is In Process (or preparing)
# so change the status before we delete
db(tracktable.send_id == send_id).update(status = inv_tracking_status["IN_PROCESS"])
track_rows = db(tracktable.send_id == send_id).select(tracktable.id)
for track_item in track_rows:
s3.inv_track_item_deleting(track_item.id)
# Now change the status to (cancelled)
db(tracktable.send_id == send_id).update(status = inv_tracking_status["CANCEL"])
session.confirmation = T("Sent Shipment canceled and items returned to Warehouse")
redirect(URL(f = "send",
args = [send_id]))
# =============================================================================
def recv():
""" RESTful CRUD controller """
recvtable = s3db.inv_recv
# Limit site_id to sites the user has permissions for
if settings.get_inv_shipment_name() == "order":
error_msg = T("You do not have permission for any facility to add an order.")
else:
error_msg = T("You do not have permission for any facility to receive a shipment.")
auth.permitted_facilities(table=recvtable, error_msg=error_msg)
tracktable = s3db.inv_track_item
atable = s3db.inv_adj_item
# The inv_recv record might be created when the shipment is send and so it
# might not have the recipient identified. If it is null then set it to
# the person who is logged in (the default)
id = request.args(0)
if id and isinstance(id, int):
record = db(recvtable.id == id).select(recvtable.recipient_id,
limitby=(0, 1)).first()
try:
if record.recipient_id is None:
db(recvtable.id == id).update(recipient_id=auth.s3_logged_in_person())
except:
pass
status = s3db.inv_ship_status
SHIP_STATUS_IN_PROCESS = status["IN_PROCESS"]
SHIP_STATUS_SENT = status["SENT"]
SHIP_STATUS_RECEIVED = status["RECEIVED"]
SHIP_STATUS_CANCEL = status["CANCEL"]
def set_recv_attr(status):
recvtable.sender_id.readable = False
recvtable.sender_id.writable = False
recvtable.grn_status.readable = False
recvtable.grn_status.writable = False
recvtable.cert_status.readable = False
recvtable.cert_status.writable = False
recvtable.eta.readable = False
recvtable.req_ref.writable = True
if status == SHIP_STATUS_IN_PROCESS:
recvtable.send_ref.writable = True
recvtable.recv_ref.readable = False
recvtable.sender_id.readable = False
else:
# Make all fields writable False
for field in recvtable.fields:
recvtable[field].writable = False
if status == SHIP_STATUS_SENT:
recvtable.date.writable = True
recvtable.recipient_id.readable = True
recvtable.recipient_id.writable = True
recvtable.comments.writable = True
status = s3db.inv_tracking_status
TRACK_STATUS_UNKNOWN = status["UNKNOWN"]
TRACK_STATUS_PREPARING = status["IN_PROCESS"]
TRACK_STATUS_TRANSIT = status["SENT"]
TRACK_STATUS_UNLOADING = status["UNLOADING"]
TRACK_STATUS_ARRIVED = status["RECEIVED"]
TRACK_STATUS_CANCELED = status["CANCEL"]
def set_track_attr(status):
# By default Make all fields writable False
for field in tracktable.fields:
tracktable[field].writable = False
# Hide some fields
tracktable.send_id.readable = False
tracktable.recv_id.readable = False
tracktable.bin.readable = False
tracktable.adj_item_id.readable = False
tracktable.recv_quantity.readable = True
if status == TRACK_STATUS_PREPARING:
# show some fields
tracktable.item_source_no.writable = True
tracktable.item_id.writable = True
tracktable.item_pack_id.writable = True
tracktable.quantity.writable = True
tracktable.currency.writable = True
tracktable.pack_value.writable = True
tracktable.expiry_date.writable = True
tracktable.recv_bin.writable = True
tracktable.owner_org_id.writable = True
tracktable.supply_org_id.writable = True
tracktable.inv_item_status.writable = True
tracktable.comments.writable = True
tracktable.recv_quantity.readable = False
# hide some fields
tracktable.send_inv_item_id.readable = False
# change some labels - NO - use consistent labels
#tracktable.quantity.label = T("Quantity Delivered")
tracktable.recv_bin.label = T("Bin")
elif status == TRACK_STATUS_TRANSIT:
# Hide the values that will be copied from the inv_inv_item record
tracktable.send_inv_item_id.readable = False
tracktable.send_inv_item_id.writable = False
tracktable.item_source_no.readable = True
tracktable.item_source_no.writable = False
# Display the values that can only be entered on create
tracktable.recv_quantity.writable = True
tracktable.recv_bin.readable = True
tracktable.recv_bin.writable = True
tracktable.comments.writable = True
# This is a received purchase so change the label to reflect this - NO - use consistent labels
#tracktable.quantity.label = T("Quantity Delivered")
elif status == TRACK_STATUS_ARRIVED:
tracktable.item_source_no.readable = True
tracktable.item_source_no.writable = False
tracktable.item_id.writable = False
tracktable.send_inv_item_id.writable = False
tracktable.item_pack_id.writable = False
tracktable.quantity.writable = False
tracktable.currency.writable = False
tracktable.pack_value.writable = False
tracktable.expiry_date.writable = False
tracktable.owner_org_id.writable = False
tracktable.supply_org_id.writable = False
tracktable.recv_bin.readable = True
tracktable.recv_bin.writable = True
def prep(r):
record = r.record
if (record and
(record.status != SHIP_STATUS_IN_PROCESS and
record.status != SHIP_STATUS_SENT)):
# Now that the shipment has been sent
# lock the record so that it can't be meddled with
s3db.configure("inv_recv",
create = False,
deletable = False,
editable = False,
listadd = False,
)
if r.component and r.component.name == "track_item":
# Set the track_item attributes
# Can only create or delete track items for a recv record if the status is preparing
if r.method == "create" or r.method == "delete":
if record.status != SHIP_STATUS_IN_PROCESS:
return False
if r.component_id:
track_record = db(tracktable.id == r.component_id).select(tracktable.status,
limitby=(0, 1)
).first()
set_track_attr(track_record.status)
else:
set_track_attr(TRACK_STATUS_PREPARING)
tracktable.status.readable = False
if r.record and r.record.status == SHIP_STATUS_IN_PROCESS:
s3.crud_strings.inv_recv.title_update = \
s3.crud_strings.inv_recv.title_display = T("Process Received Shipment")
# Default the Supplier/Donor to the Org sending the shipment
tracktable.supply_org_id.default = record.organisation_id