-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathShipment.php
More file actions
3293 lines (2701 loc) · 150 KB
/
Shipment.php
File metadata and controls
3293 lines (2701 loc) · 150 KB
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
<?php
namespace SynchWeb\Page;
use Exception;
use SynchWeb\Database\DatabaseQueryBuilder;
use SynchWeb\Page;
use SynchWeb\Shipment\Courier\DHL;
use SynchWeb\Shipment\ShippingService;
use SynchWeb\Email;
use SynchWeb\ImagingShared;
use SynchWeb\Shipment\ShippingService\ShippingService as ShippingServiceShippingService;
use SynchWeb\Utils;
class Shipment extends Page
{
public static $arg_list = array(
'did' => '\d+',
'cid' => '\d+',
'sid' => '\d+',
'lcid' => '\d+',
'pid' => '\d+',
'iid' => '\d+',
'visit' => '\w+\d+-\d+',
'current' => '\d',
'all' => '\d',
'ty' => '\w+',
'imager' => '\d',
'imid' => '\d+',
'requestedimager' => '\d',
'firstexperimentdate' => '\d\d-\d\d-\d\d\d\d',
// cache name
'name' => '\w+',
// Dewar Fields
'CODE' => '([\w\-])+',
'FACILITYCODE' => '([\w\-])+',
'NEWFACILITYCODE' => '([\w\-])+',
'TRACKINGNUMBERTOSYNCHROTRON' => '\w*',
'TRACKINGNUMBERFROMSYNCHROTRON' => '\w*',
'FIRSTEXPERIMENTID' => '\d+|^(?![\s\S])',
'SHIPPINGID' => '\d+',
'DEWARREGISTRYID' => '\d+',
'BARCODE' => '([\w\-])+',
'LOCATION' => '[\w|\s|\-]+',
'NEXTLOCATION' => '\w+|^(?![\s\S])',
'STATUS' => '[\w|\s|\-]+',
'PURCHASEDATE' => '\d+-\d+-\d+',
'LABCONTACTID' => '\d+',
'REPORT' => '.*',
'ADDRESS' => '.*',
'COUNTRY' => '.*',
'CITY' => '([\w\s\-])+',
'POSTCODE' => '([\w\s\-])+',
// 'DESCRIPTION' => '.*',
'EMAILADDRESS' => '.*',
'FAMILYNAME' => '.*',
'GIVENNAME' => '.*',
'LABNAME' => '.*',
'LOCALCONTACT' => '[\w|\s+|\-]+',
'NEXTLOCALCONTACT' => '\w+|^(?![\s\S])',
'PHONENUMBER' => '.*',
'VISIT' => '\w+\d+-\d+',
'NEXTVISIT' => '\w+\d+-\d+|^(?![\s\S])',
'AWBNUMBER' => '\w+',
'WEIGHT' => '\d+',
// Shipment fields
'FCODES' => '([\w\-])+',
'SENDINGLABCONTACTID' => '\d+',
'RETURNLABCONTACTID' => '\d+',
'SHIPPINGNAME' => '([\w\s\-])+',
'DELIVERYAGENT_SHIPPINGDATE' => '\d+-\d+-\d+',
'DELIVERYAGENT_DELIVERYDATE' => '\d+-\d+-\d+',
'DELIVERYAGENT_AGENTNAME' => '[\s|\w|\-]+',
'DELIVERYAGENT_AGENTCODE' => '[\w\-]+',
'DELIVERYAGENT_FLIGHTCODE' => '\d*',
'SAFETYLEVEL' => '\w+',
// 'DEWARS' => '\d+',
//'FIRSTEXPERIMENTID' => '\w+\d+-\d+',
// Fields for responsive remote questions:
'DYNAMIC' => '1?|Yes|No',
'REMOTEORMAILIN' => '.*',
'SESSIONLENGTH' => '\w+',
'ENERGY' => '.*',
'MICROFOCUSBEAM' => '1?|Yes|No',
'SCHEDULINGRESTRICTIONS' => '.*',
'LASTMINUTEBEAMTIME' => '1?|Yes|No',
'DEWARGROUPING' => '.*',
'EXTRASUPPORTREQUIREMENT' => '.*',
'MULTIAXISGONIOMETRY' => '1?|Yes|No',
'ENCLOSEDHARDDRIVE' => '1?|Yes|No',
'ENCLOSEDTOOLS' => '1?|Yes|No',
'COMMENTS' => '.*',
'assigned' => '\d',
'bl' => '[\w\-]+',
'unassigned' => '[\w\-]+',
// Container fields
'DEWARID' => '\d+',
'CAPACITY' => '\d+',
'CONTAINERTYPE' => '([\w\-])+',
'NAME' => '([\w\-])+',
'SCHEDULEID' => '\d+',
'SCREENID' => '\d+',
'PERSONID' => '\d+',
'DISPOSE' => '\d',
'REQUESTEDRETURN' => '\d',
'REQUESTEDIMAGERID' => '\d+',
'CONTAINERID' => '\d+',
'UNQUEUE' => '\d',
'EXPERIMENTTYPE' => '\w+',
'STORAGETEMPERATURE' => '[\w\-]+',
'AUTOMATED' => '\d+',
'PUCK' => '\d',
'PROCESSINGPIPELINEID' => '\d+',
'OWNERID' => '\d+',
'SOURCE' => '[\w\-]+',
'CONTAINERREGISTRYID' => '\d+',
'PROPOSALID' => '\d+',
't' => '\w+',
'RETURN' => '\d+',
'DECLAREDVALUE' => '\d+',
'DESCRIPTION' => '.*',
'DEWARS' => '\d+',
'PHYSICALLOCATION' => '[\s|\w|\-]+',
'READYBYTIME' => '\d\d:\d\d',
'CLOSETIME' => '\d\d:\d\d',
'PRODUCTCODE' => '\w',
'BEAMLINENAME' => '[\w\-]+',
'manifest' => '\d',
'currentuser' => '\d',
);
var $extra_arg_list = array(
'DYNAMIC',
'REMOTEORMAILIN',
'SESSIONLENGTH',
'ENERGY',
'MICROFOCUSBEAM',
'SCHEDULINGRESTRICTIONS',
'LASTMINUTEBEAMTIME',
'DEWARGROUPING',
'EXTRASUPPORTREQUIREMENT',
'MULTIAXISGONIOMETRY',
'ENCLOSEDHARDDRIVE',
'ENCLOSEDTOOLS'
);
public static $dispatch = array(
array('/shipments(/:sid)', 'get', '_get_shipments'),
array('/shipments', 'post', '_add_shipment'),
array('/shipments/:sid', 'patch', '_update_shipment'),
array('/shipments/:sid', 'put', '_dummy_shipment_put'),
array('/send/:sid', 'get', '_send_shipment'),
array('/countries', 'get', '_get_countries'),
array('/dewars(/:did)(/sid/:sid)(/fc/:FACILITYCODE)', 'get', '_get_dewars'),
array('/dewars', 'post', '_add_dewar'),
array('/dewars/:did', 'patch', '_update_dewar'),
array('/dewars/comments/:did', 'patch', '_update_dewar_comments'), // endpoint to allow bcr to update comments
array('/dewars/history(/did/:did)', 'get', '_get_history'),
array('/dewars/history', 'post', '_add_history'),
array('/dewars/registry/proposals', 'get', '_get_prop_dewar'),
array('/dewars/registry/proposals', 'post', '_add_prop_dewar'),
array('/dewars/registry/proposals/:DEWARREGISTRYHASPROPOSALID', 'delete', '_rem_prop_dewar'),
array('/dewars/registry(/:FACILITYCODE)', 'get', '_dewar_registry'),
array('/dewars/registry/:FACILITYCODE', 'patch', '_update_dewar_registry'),
array('/dewars/registry/:FACILITYCODE', 'put', '_add_dewar_registry'),
array('/dewars/reports(/:drid)', 'get', '_get_dewar_reports'),
array('/dewars/reports', 'post', '_add_dewar_report'),
array('/dewars/default', 'get', '_get_default_dewar'),
array('/dewars/transfer', 'post', '_transfer_dewar'),
array('/dewars/dispatch', 'post', '_dispatch_dewar'),
array('/dewars/tracking(/:DEWARID)', 'get', '_get_dewar_tracking'),
array('/containers(/:cid)(/sid/:sid)(/did/:did)', 'get', '_get_all_containers'),
array('/containers', 'post', '_add_container'),
array('/containers/:cid', 'patch', '_update_container'),
array('/containers/move', 'get', '_move_container'),
// TODO: Need to have a separate method for handling queueing and unqueueing of containers
array('/containers/queue(/:cid)', 'patch', '_queue_container'),
array('/containers/queue(/:cid)', 'get', '_queue_container'),
array('/containers/barcode/:BARCODE', 'get', '_check_container'),
array('/containers/registry(/:CONTAINERREGISTRYID)', 'get', '_container_registry'),
array('/containers/registry', 'post', '_add_container_registry'),
array('/containers/registry/:CONTAINERREGISTRYID', 'patch', '_update_container_registry'),
array('/containers/registry/proposals', 'get', '_get_prop_container'),
array('/containers/registry/proposals', 'post', '_add_prop_container'),
array('/containers/registry/proposals/:CONTAINERREGISTRYHASPROPOSALID', 'delete', '_rem_prop_container'),
array('/containers/history', 'get', '_container_history'),
array('/containers/history', 'post', '_add_container_history'),
array('/containers/reports(/:CONTAINERREPORTID)', 'get', '_get_container_reports'),
array('/containers/reports', 'post', '_add_container_report'),
array('/containers/types', 'get', '_get_container_types'),
array('/containers/notify/:BARCODE', 'get', '_notify_container'),
array('/cache/:name', 'put', '_session_cache'),
array('/cache/:name', 'get', '_get_session_cache'),
array('/terms/:sid', 'get', '_get_terms'),
array('/terms/:sid', 'patch', '_accept_terms'),
array('/awb/:sid', 'post', '_create_awb'),
array('/awb/quote', 'get', '_quote_awb'),
array('/pickup/:sid', 'post', '_rebook_pickup'),
array('/pickup/cancel/:sid', 'delete', '_cancel_pickup'),
);
// Keep session open so we can cache data
var $session_close = False;
var $dhl = null;
var $shipping_service = null;
function __construct()
{
call_user_func_array(array('parent', '__construct'), func_get_args());
global $dhl_user, $dhl_pass, $dhl_env;
$this->dhl = new DHL($dhl_user, $dhl_pass, $dhl_env);
$this->shipping_service = new ShippingService();
}
// Get the args that will be passsed into the 'extra' JSON column of the Shipping table
function _get_extra_args()
{
$extra_args = array();
foreach ($this->extra_arg_list as $arg) {
if ($this->has_arg($arg)) {
$extra_args[$arg] = $this->arg($arg);
}
}
return $extra_args;
}
# ------------------------------------------------------------------------
# List of shipments for a proposal
function _get_shipments()
{
if ($this->has_arg('all') && $this->user->hasPermission('view_manifest')) {
$args = array();
$where = '1=1';
} else {
if (!$this->has_arg('prop'))
$this->_error('No proposal specified', 'Please select a proposal first');
$args = array($this->proposalid);
$where = 'p.proposalid=:1';
}
if ($this->has_arg('sid')) {
$where .= ' AND s.shippingid=:' . (sizeof($args) + 1);
array_push($args, $this->arg('sid'));
}
if ($this->has_arg('manifest')) {
$where .= ' AND s.deliveryagent_flightcodetimestamp is NOT NULL
AND d.deliveryagent_barcode IS NOT NULL';
}
if ($this->has_arg('s')) {
$st = sizeof($args) + 1;
$where .= " AND (lower(s.shippingname) LIKE lower(CONCAT(CONCAT('%',:" . $st . "), '%')) OR lower(CONCAT(p.proposalcode,p.proposalnumber)) LIKE lower(CONCAT(CONCAT('%',:" . ($st + 1) . "), '%')))";
array_push($args, $this->arg('s'));
array_push($args, $this->arg('s'));
}
$tot = $this->db->pq("SELECT count(distinct s.shippingid) as tot
FROM proposal p
INNER JOIN shipping s ON p.proposalid = s.proposalid
LEFT OUTER JOIN labcontact c ON s.sendinglabcontactid = c.labcontactid
LEFT OUTER JOIN labcontact c2 ON s.returnlabcontactid = c2.labcontactid
LEFT OUTER JOIN dewar d ON d.shippingid = s.shippingid
WHERE $where", $args);
$tot = sizeof($tot) ? intval($tot[0]['TOT']) : 0;
$pp = $this->has_arg('per_page') ? $this->arg('per_page') : 15;
$pg = $this->has_arg('page') ? $this->arg('page') - 1 : 0;
$start = $pg * $pp;
$end = $pg * $pp + $pp;
$st = sizeof($args) + 1;
$en = $st + 1;
array_push($args, $start);
array_push($args, $end);
$order = 's.creationdate DESC';
if ($this->has_arg('sort_by')) {
$cols = array('SHIPPINGNAME' => 's.shippingname');
$dir = $this->has_arg('order') ? ($this->arg('order') == 'asc' ? 'ASC' : 'DESC') : 'ASC';
if (array_key_exists($this->arg('sort_by'), $cols))
$order = $cols[$this->arg('sort_by')] . ' ' . $dir;
}
$rows = $this->db->paginate("SELECT s.deliveryagent_agentname, s.deliveryagent_agentcode, TO_CHAR(s.deliveryagent_shippingdate, 'DD-MM-YYYY') as deliveryagent_shippingdate, TO_CHAR(s.deliveryagent_deliverydate, 'DD-MM-YYYY') as deliveryagent_deliverydate, s.safetylevel, count(d.dewarid) as dcount,s.sendinglabcontactid, c.cardname as lcout, c2.cardname as lcret, s.returnlabcontactid, s.shippingid, s.shippingname, s.shippingstatus,TO_CHAR(s.creationdate, 'DD-MM-YYYY') as created, s.isstorageshipping, s.shippingtype, s.comments, s.deliveryagent_flightcode, IF(s.deliveryAgent_label IS NOT NULL, 1, 0) as deliveryagent_has_label, TO_CHAR(s.readybytime, 'HH24:MI') as readybytime, TO_CHAR(s.closetime, 'HH24:MI') as closetime, s.physicallocation, s.deliveryagent_pickupconfirmation, TO_CHAR(s.deliveryagent_readybytime, 'HH24:MI') as deliveryAgent_readybytime, TO_CHAR(s.deliveryAgent_callintime, 'HH24:MI') as deliveryAgent_callintime, CONCAT(p.proposalcode, p.proposalnumber) as prop, TO_CHAR(s.deliveryagent_flightcodetimestamp, 'HH24:MI DD-MM-YYYY') as deliveryagent_flightcodetimestamp, sum(d.weight) as weight, pe.givenname, pe.familyname, l.name as labname, l.address, l.city, l.postcode, l.country, CONCAT(p.proposalcode, p.proposalnumber) as prop, GROUP_CONCAT(IF(d.facilitycode, d.facilitycode, d.code)) as dewars, s.deliveryagent_productcode, IF(cta.couriertermsacceptedid,1,0) as termsaccepted, GROUP_CONCAT(d.deliveryagent_barcode) as deliveryagent_barcode, pe2.login as deliveryagent_flightcodeperson, s.extra,
SUM(IF(d.dewarstatus = 'processing', 1, 0)) as processing
FROM proposal p
INNER JOIN shipping s ON p.proposalid = s.proposalid
LEFT OUTER JOIN labcontact c2 ON s.returnlabcontactid = c2.labcontactid
LEFT OUTER JOIN dewar d ON d.shippingid = s.shippingid
LEFT OUTER JOIN couriertermsaccepted cta ON cta.shippingid = s.shippingid
LEFT OUTER JOIN labcontact c ON c.labcontactid = s.sendinglabcontactid
LEFT OUTER JOIN person pe ON c.personid = pe.personid
LEFT OUTER JOIN laboratory l ON l.laboratoryid = pe.laboratoryid
LEFT OUTER JOIN person pe2 ON pe2.personid = s.deliveryagent_flightcodepersonid
WHERE $where
GROUP BY s.sendinglabcontactid, s.returnlabcontactid, s.deliveryagent_agentname, s.deliveryagent_agentcode, s.deliveryagent_shippingdate, s.deliveryagent_deliverydate, s.safetylevel, c.cardname, c2.cardname, s.shippingid, s.shippingname, s.shippingstatus,TO_CHAR(s.creationdate, 'DD-MM-YYYY'), s.isstorageshipping, s.shippingtype, s.comments, s.creationdate
ORDER BY $order", $args);
foreach ($rows as &$s) {
$s['DELIVERYAGENT_BARCODE'] = str_replace(',', ', ', $s['DELIVERYAGENT_BARCODE']);
$extra_json = json_decode($s['EXTRA'], true);
if (is_null($extra_json)) {
$extra_json = array();
foreach ($this->extra_arg_list as $arg) {
$extra_json[$arg] = "";
}
}
$s = array_merge($s, $extra_json);
}
if ($this->has_arg('sid')) {
if (sizeof($rows))
$this->_output($rows[0]);
else
$this->_error('No such shipment');
} else
$this->_output(array(
'total' => $tot,
'data' => $rows,
));
}
# ------------------------------------------------------------------------
# Dewar history
function _get_history()
{
if (!$this->has_arg('did') && !$this->has_arg('FACILITYCODE'))
$this->_error('No dewar specified');
$args = array($this->proposalid);
$where = 'p.proposalid=:1';
if ($this->has_arg('all') && ($this->bcr() || $this->staff)) {
$args = array();
$where = '1=1';
}
if ($this->has_arg('did')) {
$where .= ' AND d.dewarid=:' . (sizeof($args) + 1);
array_push($args, $this->arg('did'));
} else {
$where .= ' AND d.facilitycode=:' . (sizeof($args) + 1);
array_push($args, $this->arg('FACILITYCODE'));
}
$tot = $this->db->pq("SELECT count(h.dewartransporthistoryid) as tot
FROM dewartransporthistory h
INNER JOIN dewar d ON d.dewarid = h.dewarid
INNER JOIN shipping s ON s.shippingid = d.shippingid
INNER JOIN proposal p ON p.proposalid = s.proposalid WHERE $where", $args);
$tot = intval($tot[0]['TOT']);
$pp = $this->has_arg('per_page') ? $this->arg('per_page') : 15;
$pg = $this->has_arg('page') ? $this->arg('page') - 1 : 0;
$start = $pg * $pp;
$end = $pg * $pp + $pp;
$st = sizeof($args) + 1;
$en = $st + 1;
array_push($args, $start);
array_push($args, $end);
$rows = $this->db->paginate("SELECT s.shippingid, s.shippingname as shipment, CONCAT(p.proposalcode, p.proposalnumber, '-', b.visit_number) as visit, b.beamlinename as bl, b.beamlineoperator as localcontact, h.dewarid, h.dewarstatus,h.storagelocation,TO_CHAR(h.arrivaldate, 'DD-MM-YYYY HH24:MI') as arrival, d.comments
FROM dewartransporthistory h
INNER JOIN dewar d ON d.dewarid = h.dewarid
INNER JOIN shipping s ON d.shippingid = s.shippingid
INNER JOIN proposal p ON p.proposalid = s.proposalid
LEFT OUTER JOIN blsession b ON b.sessionid = d.firstexperimentid
WHERE $where ORDER BY h.arrivaldate DESC", $args);
$this->_output(array('total' => $tot, 'data' => $rows));
}
function _add_history()
{
global $in_contacts, $arrival_email;
global $dewar_complete_email, $dewar_complete_email_locations; // Email list to cc if dewar back from beamline
# Flag to indicate we should e-mail users their dewar has returned from BL
$send_return_email = False;
if (!$this->bcr())
$this->_error('You need to be on the internal network to add history');
if (!$this->has_arg('BARCODE'))
$this->_error('No barcode specified');
if (!$this->has_arg('LOCATION'))
$this->_error('No location specified');
$dew = $this->db->pq("SELECT CONCAT(pe.givenname, ' ', pe.familyname) as lcout, pe.emailaddress as lcoutemail, CONCAT(CONCAT(pe2.givenname, ' '), pe2.familyname) as lcret, pe2.emailaddress as lcretemail, CONCAT(p.proposalcode, p.proposalnumber, '-', e.visit_number) as firstexp, TO_CHAR(e.startdate, 'DD-MM-YYYY HH24:MI') as firstexpst, e.beamlinename, e.beamlineoperator, d.dewarid, d.trackingnumberfromsynchrotron, s.shippingid, s.shippingname, p.proposalcode, CONCAT(p.proposalcode, p.proposalnumber) as prop, d.barcode, d.facilitycode, d.firstexperimentid, d.dewarstatus
FROM dewar d
INNER JOIN shipping s ON s.shippingid = d.shippingid
LEFT OUTER JOIN labcontact c ON s.sendinglabcontactid = c.labcontactid
LEFT OUTER JOIN person pe ON pe.personid = c.personid
LEFT OUTER JOIN labcontact c2 ON s.returnlabcontactid = c2.labcontactid
LEFT OUTER JOIN person pe2 ON pe2.personid = c2.personid
INNER JOIN proposal p ON p.proposalid = s.proposalid
LEFT OUTER JOIN blsession e ON e.sessionid = d.firstexperimentid
WHERE lower(barcode) LIKE lower(:1)", array($this->arg('BARCODE')));
if (!sizeof($dew))
$this->_error('No such dewar');
else
$dew = $dew[0];
$track = $this->has_arg('TRACKINGNUMBERFROMSYNCHROTRON') ? $this->arg('TRACKINGNUMBERFROMSYNCHROTRON') : $dew['TRACKINGNUMBERFROMSYNCHROTRON'];
// What was the last history entry for this dewar?
// If it's come from a beamline, register flag so we can e-mail further down...
$last_history_results = $this->db->pq("SELECT storageLocation FROM dewartransporthistory WHERE dewarId = :1 ORDER BY DewarTransportHistoryId DESC LIMIT 1", array($dew['DEWARID']));
if (sizeof($last_history_results)) {
$last_history = $last_history_results[0];
// We only add data to dewar history in lower case from this method.
// If that ever changes, update this to become case insensitive search
$last_location = $last_history['STORAGELOCATION'];
if (!isset($dewar_complete_email_locations) || !is_array($dewar_complete_email_locations)) {
$bls = $this->_get_beamlines_from_type('all');
$send_return_email = in_array($last_location, $bls);
} else if (array_key_exists($last_location, $dewar_complete_email_locations)) {
$email_location = $dewar_complete_email_locations[$last_location];
$send_return_email = preg_match($email_location, strtolower($this->arg('LOCATION')));
}
} else {
// No history - could be a new dewar, so not necessarily an error...
if ($this->debug)
error_log("No previous dewar transport history for DewarId " . $dew['DEWARID']);
}
// If dewar status is dispatch-requested - don't change it.
// This way the dewar can be moved between storage locations and keep the record that a user requested the dispatch
// Default status is 'at-facility'
$dewarstatus = strtolower($dew['DEWARSTATUS']) == 'dispatch-requested' ? 'dispatch-requested' : 'at facility';
$this->db->pq("INSERT INTO dewartransporthistory (dewartransporthistoryid,dewarid,dewarstatus,storagelocation,arrivaldate) VALUES (s_dewartransporthistory.nextval,:1,lower(:2),lower(:3),CURRENT_TIMESTAMP) RETURNING dewartransporthistoryid INTO :id", array($dew['DEWARID'], $dewarstatus, $this->arg('LOCATION')));
$dhid = $this->db->id();
$this->db->pq("UPDATE dewar set dewarstatus=lower(:4), storagelocation=lower(:2), trackingnumberfromsynchrotron=:3 WHERE dewarid=:1", array($dew['DEWARID'], $this->arg('LOCATION'), $track, $dewarstatus));
$this->db->pq("UPDATE shipping set shippingstatus=lower(:2) WHERE shippingid=:1", array($dew['SHIPPINGID'], $dewarstatus));
$containers = $this->db->pq("SELECT containerid
FROM container
WHERE dewarid=:1", array($dew['DEWARID']));
foreach ($containers as $c) {
$this->db->pq("INSERT INTO containerhistory (containerid,status) VALUES (:1,:2)", array($c['CONTAINERID'], 'at facility'));
}
// Email
// EHCs, local contact(s), labcontact, dh, pa
$dew['NOW'] = strftime('%d-%m-%Y %H:%M');
$dew['INCONTACTS'] = $in_contacts;
$dew['TRACKINGNUMBERFROMSYNCHROTRON'] = $track;
if (strtolower($this->arg('LOCATION')) == 'stores-in' && $dew['LCOUTEMAIL']) {
$lcs = $this->db->pq("SELECT p.login
FROM person p
INNER JOIN session_has_person shp ON shp.personid = p.personid
WHERE shp.sessionid=:1 AND (shp.role = 'Local Contact' OR shp.role = 'Local Contact 2')", array($dew['FIRSTEXPERIMENTID']));
$emails = array($dew['LCOUTEMAIL'], $arrival_email);
foreach ($lcs as $lc) {
array_push($emails, $this->_get_email($lc['LOGIN']));
}
$email = new Email($dew['PROPOSALCODE'] == 'in' ? 'dewar-stores-in-in' : 'dewar-stores-in', '*** Dewar Received for ' . $dew['PROP'] . ' at ' . $dew['NOW'] . ' ***');
$email->data = $dew;
$email->send(implode(', ', $emails));
}
if (strtolower($this->arg('LOCATION')) == 'stores-out' && $dew['LCRETEMAIL']) {
$email = new Email('dewar-stores-out', '*** Dewar ready to leave Synchrotron ***');
$email->data = $dew;
$email->send($dew['LCRETEMAIL']);
}
if (strpos(strtolower($this->arg('LOCATION')), '-rack') !== false && $dew['LCRETEMAIL']) {
$dew['LOCATION'] = $this->arg('LOCATION');
$email = new Email('dewar-rack', '*** Dewar now outside Beamline ***');
$email->data = $dew;
$email->send($dew['LCRETEMAIL']);
}
if ($dew['LCRETEMAIL'] && $send_return_email) {
// Any data collections for this dewar's containers?
// Note this counts data collection ids for containers and uses the DataCollection.SESSIONID to determine the session/visit
// Should work for UDC (where container.sessionid is set) as well as any normal scheduled session (where container.sessionid is not set)
$rows = $this->db->pq("SELECT CONCAT(p.proposalcode, p.proposalnumber, '-', ses.visit_number) as visit, dc.sessionid, count(dc.datacollectionid) as dccount
FROM Dewar d
INNER JOIN Container c on c.dewarid = d.dewarid
INNER JOIN BLSample bls ON bls.containerid = c.containerid
INNER JOIN DataCollection dc ON dc.blsampleid = bls.blsampleid
INNER JOIN BLSession ses ON dc.sessionid = ses.sessionid
INNER JOIN Proposal p ON p.proposalid = ses.proposalid
WHERE d.dewarid = :1
GROUP BY dc.sessionid", array($dew['DEWARID']));
if (sizeof($rows))
$dew['DC'] = $rows;
$cc = array($dewar_complete_email ? $dewar_complete_email : null);
$owners = $this->db->pq("SELECT p.emailaddress
FROM Container c
INNER JOIN Person p ON c.ownerId = p.personId
WHERE c.dewarId = :1
GROUP BY p.emailaddress", array($dew['DEWARID']));
foreach ($owners as $owner) {
if ($owner['EMAILADDRESS'] != '') array_push($cc, $owner['EMAILADDRESS']);
}
// Log the event if debugging
if ($this->debug) error_log("Dewar " . $dew['DEWARID'] . " back from beamline...");
$email = new Email('storage-rack', '*** Visit finished, dewar awaiting instructions ***');
$email->data = $dew;
$email->send($dew['LCRETEMAIL'], implode(', ', $cc));
}
$this->_output(array('DEWARHISTORYID' => $dhid));
}
function _dewar_registry()
{
$args = array($this->proposalid);
$where = 'p.proposalid=:1';
$fields = "r.dewarregistryid, max(CONCAT(p.proposalcode, p.proposalnumber)) as prop, r.facilitycode, TO_CHAR(r.purchasedate, 'DD-MM-YYYY') as purchasedate, ROUND(TIMESTAMPDIFF('DAY',r.purchasedate, CURRENT_TIMESTAMP)/30.42,1) as age, r.labcontactid, count(distinct d.dewarid) as dewars, GROUP_CONCAT(distinct CONCAT(p.proposalcode,p.proposalnumber) SEPARATOR ', ') as proposals, r.bltimestamp, TO_CHAR(max(d.bltimestamp),'DD-MM-YYYY') as lastuse, count(dr.dewarreportid) as reports";
$group = "r.facilitycode";
if ($this->has_arg('all') && $this->staff) {
$args = array();
$where = '1=1';
}
if ($this->has_arg('FACILITYCODE')) {
$where .= ' AND r.facilitycode=:' . (sizeof($args) + 1);
array_push($args, $this->arg('FACILITYCODE'));
}
if ($this->has_arg('s')) {
$st = sizeof($args) + 1;
$where .= " AND (lower(r.facilitycode) LIKE lower(CONCAT(CONCAT('%', :" . ($st) . "), '%')) OR lower(CONCAT(p.proposalcode,p.proposalnumber)) LIKE lower(CONCAT(CONCAT('%',:" . ($st + 1) . "), '%')))";
array_push($args, $this->arg('s'), $this->arg('s'));
}
if ($this->has_arg('t')) {
if ($this->arg('t') == 'orphan')
$where .= " AND rhp.dewarregistryid IS NULL";
}
$tot = $this->db->pq("SELECT count(r.facilitycode) as tot
FROM dewarregistry r
LEFT OUTER JOIN dewarregistry_has_proposal rhp ON r.dewarregistryid = rhp.dewarregistryid
LEFT OUTER JOIN proposal p ON p.proposalid = rhp.proposalid
WHERE $where", $args);
$tot = intval($tot[0]['TOT']);
$pp = $this->has_arg('per_page') ? $this->arg('per_page') : 15;
$pg = $this->has_arg('page') ? $this->arg('page') - 1 : 0;
$start = $pg * $pp;
$end = $pg * $pp + $pp;
$st = sizeof($args) + 1;
$en = $st + 1;
array_push($args, $start);
array_push($args, $end);
$order = 'r.facilitycode';
if ($this->has_arg('sort_by')) {
$cols = array(
'FACILITYCODE' => 'r.facilitycode', 'DEWARS' => 'count(distinct d.dewarid)',
'LASTUSE' => 'max(d.bltimestamp)', 'BLTIMESTAMP' => 'r.bltimestamp',
'REPORTS' => 'count(dr.dewarreportid)'
);
$dir = $this->has_arg('order') ? ($this->arg('order') == 'asc' ? 'ASC' : 'DESC') : 'ASC';
if (array_key_exists($this->arg('sort_by'), $cols))
$order = $cols[$this->arg('sort_by')] . ' ' . $dir;
}
$rows = $this->db->paginate("SELECT $fields
FROM dewarregistry r
LEFT OUTER JOIN dewarregistry_has_proposal rhp ON r.dewarregistryid = rhp.dewarregistryid
LEFT OUTER JOIN dewarreport dr ON r.facilitycode = dr.facilitycode
LEFT OUTER JOIN proposal p ON p.proposalid = rhp.proposalid
LEFT OUTER JOIN dewar d ON d.facilitycode = r.facilitycode
LEFT OUTER JOIN shipping s ON d.shippingid = s.shippingid
WHERE $where
GROUP BY $group
ORDER BY $order", $args);
if ($this->has_arg('FACILITYCODE')) {
if (sizeof($rows))
$this->_output($rows[0]);
else
$this->_error('No such dewar');
} else
$this->_output(array('total' => $tot, 'data' => $rows));
}
function _add_dewar_registry()
{
if (!$this->staff)
$this->_error('No access');
if (!$this->has_arg('FACILITYCODE'))
$this->_error('No dewar code specified');
$fc = strtoupper($this->arg('FACILITYCODE'));
$check = $this->db->pq("SELECT dewarregistryid FROM dewarregistry WHERE facilitycode=:1", array($fc));
if (sizeof($check)) {
$this->_error('That facility code is already in use');
}
$purchase = $this->has_arg('PURCHASEDATE') ? $this->arg('PURCHASEDATE') : '';
$this->db->pq("INSERT INTO dewarregistry (facilitycode, purchasedate, bltimestamp) VALUES (:1, TO_DATE(:2, 'DD-MM-YYYY'), SYSDATE)", array($fc, $purchase));
$this->_output(array('FACILITYCODE' => $fc, 'DEWARREGISTRYID' => $this->db->id()));
}
function _update_dewar_registry()
{
if (!$this->has_arg('FACILITYCODE'))
$this->_error('No dewar code specified');
$dew = $this->db->pq("SELECT facilitycode FROM dewarregistry dr
INNER JOIN dewarregistry_has_proposal drhp ON dr.dewarregistryid = drhp.dewarregistryid
WHERE dr.facilitycode LIKE :1
AND drhp.proposalid = :2",
array($this->arg('FACILITYCODE'), $this->proposalid));
if (!sizeof($dew))
$this->_error('No such dewar');
else
$dew = $dew[0];
$fields = array('PURCHASEDATE');
if ($this->staff)
array_push($fields, 'NEWFACILITYCODE');
foreach ($fields as $f) {
if ($this->has_arg($f)) {
$fl = ':1';
if (in_array($f, array('PURCHASEDATE'))) {
$fl = "TO_DATE(:1, 'DD-MM-YYYY')";
}
if ($f == 'NEWFACILITYCODE') {
$this->db->pq("UPDATE dewarregistry SET FACILITYCODE=$fl WHERE facilitycode=:2", array($this->arg($f), $this->arg('FACILITYCODE')));
$this->_output(array('FACILITYCODE' => $this->arg($f)));
} else {
$this->db->pq("UPDATE dewarregistry SET $f=$fl WHERE facilitycode=:2", array($this->arg($f), $this->arg('FACILITYCODE')));
$this->_output(array($f => $this->arg($f)));
}
}
}
}
function _get_prop_dewar()
{
if (!$this->has_arg('DEWARREGISTRYID'))
$this->_error('No dewar specified');
$rows = $this->db->pq("SELECT drhp.dewarregistryhasproposalid,drhp.dewarregistryid,drhp.proposalid,CONCAT(p.proposalcode, p.proposalnumber) as proposal, pe.familyname, pe.givenname, pe.phonenumber, pe.emailaddress, lc.cardname, l.name as labname, l.address, l.city, l.postcode, l.country
FROM dewarregistry_has_proposal drhp
INNER JOIN proposal p ON p.proposalid = drhp.proposalid
LEFT OUTER JOIN labcontact lc ON drhp.labcontactid = lc.labcontactid
LEFT OUTER JOIN person pe ON pe.personid = lc.personid
LEFT OUTER JOIN laboratory l ON l.laboratoryid = pe.laboratoryid
WHERE drhp.dewarregistryid = :1", array($this->arg('DEWARREGISTRYID')));
$this->_output($rows);
}
function _add_prop_dewar()
{
if (!$this->staff)
$this->_error('No access');
if (!$this->has_arg('DEWARREGISTRYID'))
$this->_error('No dewar specified');
if (!$this->has_arg('PROPOSALID'))
$this->_error('No proposal specified');
if (!$this->has_arg('LABCONTACTID'))
$this->_error('No lab contact specified');
$chk = $this->db->pq("SELECT dewarregistryid
FROM dewarregistry_has_proposal
WHERE dewarregistryid = :1 AND proposalid = :2", array($this->arg('DEWARREGISTRYID'), $this->arg('PROPOSALID')));
if (sizeof($chk))
$this->_error('That dewar is already registered to that proposal');
$this->db->pq("INSERT INTO dewarregistry_has_proposal (dewarregistryid,proposalid,personid,labcontactid)
VALUES (:1,:2,:3,:4)", array($this->arg('DEWARREGISTRYID'), $this->arg('PROPOSALID'), $this->user->personId, $this->arg('LABCONTACTID')));
$this->_output(array('DEWARREGISTRYHASPROPOSALID' => $this->db->id()));
}
function _rem_prop_dewar()
{
if (!$this->staff)
$this->_error('No access');
if (!$this->has_arg('DEWARREGISTRYHASPROPOSALID'))
$this->_error('No dewar proposal specified');
$this->db->pq("DELETE FROM dewarregistry_has_proposal WHERE dewarregistryhasproposalid=:1", array($this->arg('DEWARREGISTRYHASPROPOSALID')));
}
function _get_dewar_reports()
{
if (!$this->has_arg('FACILITYCODE'))
$this->_error('No dewar specified');
$where = 'r.facilitycode=:1';
$args = array($this->arg('FACILITYCODE'));
$tot = $this->db->pq("SELECT count(r.dewarreportid) as tot
FROM dewarreport r
WHERE $where", $args);
$tot = intval($tot[0]['TOT']);
$pp = $this->has_arg('per_page') ? $this->arg('per_page') : 15;
$pg = $this->has_arg('page') ? $this->arg('page') - 1 : 0;
$start = $pg * $pp;
$end = $pg * $pp + $pp;
$st = sizeof($args) + 1;
$en = $st + 1;
array_push($args, $start);
array_push($args, $end);
$rows = $this->db->paginate("SELECT r.dewarreportid, r.report, TO_CHAR(r.bltimestamp, 'HH24:MI DD-MM-YYYY') as bltimestamp, r.attachment
FROM dewarreport r
WHERE $where ORDER BY r.bltimestamp DESC", $args);
foreach ($rows as $i => &$row) {
$row['REPORT'] = $this->db->read($row['REPORT']);
}
$this->_output(array('total' => $tot, 'data' => $rows));
}
function _add_dewar_report()
{
if (!$this->has_arg('REPORT'))
$this->_error('No report specified');
if (!$this->has_arg('FACILITYCODE'))
$this->_error('No dewar specified');
$last_visits = $this->db->pq("SELECT s.beamlineoperator as localcontact, CONCAT(p.proposalcode, p.proposalnumber, '-', s.visit_number) as visit, TO_CHAR(s.startdate, 'YYYY') as year, s.beamlinename
FROM dewar d
INNER JOIN blsession s ON d.firstexperimentid = s.sessionid
INNER JOIN shipping sh ON sh.shippingid = d.shippingid
INNER JOIN proposal p ON p.proposalid = sh.proposalid
WHERE d.facilitycode = :1
ORDER BY s.startdate DESC", array($this->arg('FACILITYCODE')));
if (!sizeof($last_visits))
$this->_error('Cant find a visit for that dewar');
else
$lv = $last_visits[0];
if (array_key_exists('ATTACHMENT', $_FILES)) {
if ($_FILES['ATTACHMENT']['name']) {
$info = pathinfo($_FILES['ATTACHMENT']['name']);
if ($info['extension'] == 'jpg') {
# dls_mxweb cant write to visits...
#$root = '/dls/'.$lv['BEAMLINENAME'].'/data/'.$lv['YEAR'].'/'.$lv['VISIT'].'/.ispyb/';
$root = '/dls_sw/dasc/ispyb2/uploads/' . $lv['YEAR'] . '/' . $lv['VISIT'] . '/';
if (!is_dir($root)) {
mkdir($root, 0755, true);
}
$file = strftime('%Y-%m-%d_%H%M') . 'dewarreport.jpg';
$this->db->pq(
"INSERT INTO dewarreport (dewarreportid,facilitycode,report,attachment,bltimestamp) VALUES (s_dewarreport.nextval,:1,:2,:3,SYSDATE) RETURNING dewarreportid INTO :id",
array($this->arg('FACILITYCODE'), $this->arg('REPORT'), $root . $file)
);
move_uploaded_file($_FILES['ATTACHMENT']['tmp_name'], $root . $file);
$lc = $this->db->pq("SELECT p.emailaddress
FROM dewarregistry r
INNER JOIN labcontact l ON l.labcontactid = r.labcontactid
INNER JOIN person p ON p.personid = l.personid
WHERE r.facilitycode=:1", array($this->arg('FACILITYCODE')));
if (sizeof($lc)) {
$recpts = array($lc[0]['EMAILADDRESS']);
$local = $this->_get_email_fn($lv['LOCALCONTACT']);
if ($local)
array_push($recpts, $local);
$this->args['NOW'] = strftime('%d-%m-%Y %H:%M');
$email = new Email('dewar-report', '*** Status Report for Dewar ' . $this->arg('FACILITYCODE') . ' at ' . $this->arg('NOW') . ' ***');
$email->data = $this->args;
$email->send(implode(', ', $recpts));
}
$this->_output(array('DEWARREPORTID' => $this->db->id()));
}
}
}
}
function _transfer_dewar()
{
global $transfer_email;
if (!$this->has_arg('DEWARID'))
$this->_error('No dewar specified');
if (!$this->has_arg('LOCATION'))
$this->_error('No location specified');
$dew = $this->db->pq("SELECT d.dewarid,s.shippingid
FROM dewar d
INNER JOIN shipping s ON s.shippingid = d.shippingid
INNER JOIN proposal p ON p.proposalid = s.proposalid
WHERE d.dewarid=:1 and p.proposalid=:2", array($this->arg('DEWARID'), $this->proposalid));
if (!sizeof($dew))
$this->_error('No such dewar');
else
$dew = $dew[0];
$this->db->pq(
"INSERT INTO dewartransporthistory (dewartransporthistoryid,dewarid,dewarstatus,storagelocation,arrivaldate)
VALUES (s_dewartransporthistory.nextval,:1,'transfer-requested',:2,CURRENT_TIMESTAMP) RETURNING dewartransporthistoryid INTO :id",
array($dew['DEWARID'], $this->arg('LOCATION'))
);
// Update dewar status to transfer-requested to keep consistent with history
$this->db->pq("UPDATE dewar set dewarstatus='transfer-requested' WHERE dewarid=:1", array($dew['DEWARID']));
if ($this->has_arg('NEXTVISIT')) {
$sessions = $this->db->pq(
"SELECT s.sessionid
FROM blsession s
INNER JOIN proposal p ON p.proposalid = s.proposalid
WHERE p.proposalid=:1 AND CONCAT(p.proposalcode, p.proposalnumber, '-', s.visit_number) LIKE :2",
array($this->proposalid, $this->arg('NEXTVISIT'))
);
$sessionId = !empty($sessions) ? $sessions[0]['SESSIONID'] : NULL;
$this->db->pq("UPDATE dewar SET firstexperimentid=:1 WHERE dewarid=:2", array($sessionId, $dew['DEWARID']));
}
$email = new Email('dewar-transfer', '*** Dewar ready for internal transfer ***');
$nextLocalContact = $this->arg('NEXTLOCALCONTACT');
$newContact = !empty($nextLocalContact) ? $nextLocalContact : $this->arg('LOCALCONTACT');
$nextLocation = $this->arg('NEXTLOCATION');
$this->args['LCEMAIL'] = $this->_get_email_fn($this->arg('LOCALCONTACT'));
$this->args['LCNEXTEMAIL'] = $this->_get_email_fn($newContact);
$this->args['NEXTLOCATION'] = !empty($nextLocation) ? $nextLocation : $this->arg('LOCATION');
$data = $this->args;
if (!array_key_exists('FACILITYCODE', $data))
$data['FACILITYCODE'] = '';
$email->data = $data;
$recpts = $transfer_email . ', ' . $this->arg('EMAILADDRESS');
if ($this->args['LCEMAIL'])
$recpts .= ', ' . $this->arg('LCEMAIL');
if ($this->args['LCNEXTEMAIL'])
$recpts .= ', ' . $this->arg('LCNEXTEMAIL');
$email->send($recpts);
$this->_output(1);
}
function _dispatch_dewar_in_shipping_service($dispatch_info, $dewar)
{
global $facility_company;
global $facility_address;
global $facility_city;
global $facility_postcode;
global $facility_country;
global $facility_phone;
global $facility_contact;
global $shipping_service_api_url;
global $facility_email;
if (!isset($shipping_service_api_url)) {
throw new Exception("Could not send request to shipping service: shipping_service_api_url not set");
}
# Create shipment
$shipment_data = array(
"consignee_company_name" => $dispatch_info['LABNAME'],
"consignee_country" => $dispatch_info['COUNTRY'],
"consignee_city" => $dispatch_info['CITY'],
"consignee_post_code" => Utils::getValueOrDefault($dispatch_info['POSTCODE'], null),
"consignee_contact_name" => $dispatch_info['GIVENNAME'] . " " . $dispatch_info['FAMILYNAME'],
"consignee_contact_phone_number" => $dispatch_info['PHONENUMBER'],
"consignee_contact_email" => $dispatch_info['EMAILADDRESS'],
"shipper_company_name" => $facility_company,
"shipper_address_line1" => $facility_address,
"shipper_city" => $facility_city,
"shipper_country" => $facility_country,
"shipper_post_code" => $facility_postcode,
"shipper_contact_name" => $facility_contact,
"shipper_contact_phone_number" => $facility_phone,
"shipper_contact_email" => $facility_email,
"internal_contact_name" => $this->has_arg('LOCALCONTACT') ? $this->args['LOCALCONTACT'] : null,
"shipment_reference" => $dispatch_info['VISIT'],
"external_id" => (int) $dispatch_info['DEWARID'],
"journey_type" => ShippingService::JOURNEY_FROM_FACILITY,
"packages" => array(array("external_id" => (int) $dispatch_info['DEWARID']))
);
# Split up address. Necessary as address is a single field in ispyb
$address_lines = explode(PHP_EOL, rtrim($dispatch_info['ADDRESS']));
$num_lines = count($address_lines);
if ($num_lines > 3) {
throw new Exception("Could not build request for shipping service: address input contains more than 3 lines (exc. city and post code)");
}
if (isset($address_lines[0])) $shipment_data['consignee_address_line1'] = $address_lines[0];
if (isset($address_lines[1])) $shipment_data['consignee_address_line2'] = $address_lines[1];
if (isset($address_lines[2])) $shipment_data['consignee_address_line3'] = $address_lines[2];
$create = ($dewar['DEWARSTATUS'] != 'dispatch-requested');
try {
if ($create === true) {
$shipment_data["proposal"] = $dewar["PROPOSAL"];
$response = $this->shipping_service->create_shipment($shipment_data);
} else {
$this->shipping_service->update_shipment($dispatch_info['DEWARID'], $shipment_data, ShippingService::JOURNEY_FROM_FACILITY);
$response = $this->shipping_service->get_shipment($dispatch_info['DEWARID'], ShippingService::JOURNEY_FROM_FACILITY);
}
$shipment_id = $response['shipmentId'];
$this->shipping_service->dispatch_shipment($shipment_id, false);
} catch (Exception $e) {
throw new Exception("Error returned from shipping service: " . $e . "\nShipment data: " . json_encode($shipment_data));
}
return $shipment_id;
}
function _dispatch_dewar()
{
global $facility_country;
global $facility_courier_countries;
global $dispatch_email;