-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_barcodes.cgi
More file actions
executable file
·1369 lines (1181 loc) · 42 KB
/
request_barcodes.cgi
File metadata and controls
executable file
·1369 lines (1181 loc) · 42 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
#!/usr/bin/perl
use strict; use warnings;
# CVS $Revision: 1.17 $ committed on $Date: 2006/09/22 13:21:18 $ by $Author: tbooth $
#Testing - capture all warnings.
# use Carp;
# $SIG{__WARN__} = sub { confess(@_) };
# Request some barcodes for yourself.
use barcodeUtil('-connect');
use TableIO;
#use Encode;
# Detect mod_perl
our $apache = (%{Apache::Registry::} || %{ModPerl::Registry::}) ? 1 : 0;
if($apache)
{
die "This code is too crufty to run under mod_perl, and is not going to do so " .
"without a MAJOR cleanup!\n ";
}
#Basically, the -connect junk in barcodeUtil needs to be ripped out so that:
# - The module is initialised once
# - The configuration is read and reset on each run
# - The CGI object is generated once on each run
# (if several Handlebars are running, the module may be using a different config each time,
# so a full flush is best!)
# - The database connections are properly cached (or re-made every time)
#My cruft about connecting in the BEGIN stage will no longer wash.
# I also need to use something like CGI::Application and have a single stub script to dispatch
# calls to the right run modes. This would allow me to run several instances on one server without
# a load of messy symlinks (GenQuery does this properly!)
# No need to load CGI::Carp - barcodeUtil does this for you!
# use CGI::Carp qw(fatalsToBrowser);
#First load in the config file
our %CONFIG = %{bcgetconfig()};
our $PAGE_TITLE = $CONFIG{PAGE_TITLE};
our $PAGE_DESC = $CONFIG{PAGE_DESC};
our $DISPOSE_MASK = $CONFIG{DISPOSE_MASK} || '--';
our $MAX_CODES = $barcodeUtil::MAX_CODES;
our $STRICT_USER_NAMES = $barcodeUtil::STRICT_USER_NAMES;
our $STYLESHEET = $barcodeUtil::STYLESHEET;
our $ENABLE_PRINTING = $barcodeUtil::ENABLE_PRINTING;
our $ENABLE_PLUGIN = $CONFIG{ENABLE_PLUGIN} || '';
our $_PLUGIN_HANDLE = undef;
our $PAGE_MAINTAINER = $CONFIG{PAGE_MAINTAINER};
#A CGI query object
our $q = bcgetqueryobj();
#Trap if I manage to get stuck in some error loop
#due to my crazy error handling.
our $errorloop = 0;
#Other modules
use Data::Dumper; #For teh debugging and some error reporting
use IO::String;
{ package IO::String; no warnings;
sub str{${shift()->string_ref }} }
#Get params
our $username = lc($q->param("username") || '');
our $bctype = $q->param("bctype");
our $bcquantity = bcdequote($q->param("bcquantity"));
our $bccomments = $q->param("bccomments");
our $bcreqrange = bcdequote($q->param("bcreqrange"));
our $impfile = $q->param("impfile");
our $displist = $q->param("displist");
our $dispcomments = $q->param("dispcomments");
#Set auto-newline so the HTML source is legible
$\ = "\n";
#Things we may need to do:
#
# 1) Display the request form
# 2) Allocate some numbers
# 2a) Show some information about a type. (popup)
# 2b) Show table of users of the system. (popup)
# 3) Confirm allocation and offer download
# 4) Confirm search and offer download of data.
# 5) Receive updates and report result (2 phase?)
# 7) Generate a CSV (or whatever) file
# 8) Dispose a batch of codes.
#Validate user, numbers, etc.
sub main
{
my $error = "";
MAIN: for(1){
if($q->param("reqcsv")) #7
{
$q->delete("reqcsv");
my $base = bcdequote($q->param("base") || $q->param("blocklist")) or
$error="Internal error: Request for export made with no valid base specified.", last MAIN;
my($dispoption, $expformat);
for($q->param("dispoption") || '')
{
$dispoption = 'mask';
/omit/i and $dispoption = 'omit';
/include/i and $dispoption = 'incl';
}
#reqcsv should not report any user errors. It may die with an internal
#error in which case CGI::Carp will pick up the pieces.
$expformat = $q->param("expformat");
reqcsv($base, $dispoption, $expformat);
#reqcsv will output a text file. We don't want any stray HTML in there,
#so at this point return:
return 1;
}
#Only emit the header if this was not a download request.
print bcheader();
if($q->param("typespopup")) #2a
{
#Now as a convenience we can supply a list of types, comma sepearted.
#Default is to show all types in alphabetical order.
my $typeslist;
if(my $tl = $q->param("tl"))
{
$typeslist = [split(",", $tl)];
}
print $q->start_html( -style=>{src=>$STYLESHEET}, -title=>"Info" ),
$q->div( {-id=>"typereport"},
$q->h3("Types of barcode available") .
bctypereport($typeslist)
);
last MAIN;
}
if($q->param("userpopup")) #2b
{
print $q->start_html( -style=>{src=>$STYLESHEET}, -title=>"Info" ),
$q->div( {-id=>"userreport"},
$q->h3("Registered users of the barcode system") .
bcuserreport()
);
last MAIN;
}
if($q->param("reqcodes")) #2
{
$q->delete("reqcodes");
#Some quick checking
$username or $error =
"You need to supply a user name - click <u>Show Users</u> to see a list.", last MAIN;
bcchkuser($username) or $error =
"The user '$username' is not known - click <u>Show Users</u> to see a list.", last MAIN;
$bcquantity or $error =
"How many barcodes do you want to allocate?", last MAIN;
$bcquantity <= $MAX_CODES or $error =
"You can only request up to $MAX_CODES barcodes at a time.", last MAIN;
#Check bctype is valid - this is a security issue since this string will
#be pasted unquoted into SQL.
my $bcrealtype = bczapspaces($bctype);
bcchkbctype($bcrealtype) or $error="Internal error: Invalid barcode type set.", last MAIN;
my $base = bcallocate($bcquantity, $username, $bcrealtype, $bccomments)
or $error="Failed to allocate codes! Aieeee!!!", last MAIN;
my $qbase = bcquote($base);
my $lastcode = bcquote($base + $bcquantity - 1);
#Construct a link to the printing page
my $printingpage = "print_barcodes.cgi?fromcode=$qbase&tocode=$lastcode&username=$username";
#Offer a download
print bcstarthtml("Request successful"),
bcnavbanner(),
bch1("Barcodes allocated"),
$q->p("You have allocated the block of barcodes from $qbase to $lastcode
inclusive to user <b>$username</b>. <br />
These codes now refer to samples of the type <b>$bctype</b>" .
($bccomments
? $q->escapeHTML(", with the comment: \"$bccomments\"")
: ""
) .
". <br /><br />
You should now download an empty data template and fill it out
in your favoured spreadsheet program."),
offer_download($base);
if($ENABLE_PRINTING)
{
print $q->p("Print or request labels with these codes : " .
$q->a({-href=>$printingpage}, "Go to printing page") );
}
print $q->hr,
$q->p({style=>"font-weight:bold"},
"The format of the records is as follows:"),
bcdescribetype($bcrealtype);
last MAIN;
}
if($q->param("reqexp")) #4
{
$q->delete("reqexp");
#Determine the base of this allocation block
#If code is invalid we just end up with undef.
my $base;
$base = ( $bcreqrange ? bcrangemembertobase($bcreqrange) : undef);
#So the user has supplied a name and possibly a code.
#Validate the name and show them the list of their stuff,
#with the appropriate line selected if appropriate.
if(!$username)
{
if($STRICT_USER_NAMES)
{
$error =
"You need to supply a user name - click <u>Show Users</u> to see a list.", last MAIN;
}
elsif(!$base)
{
#The user supplied an invalid code
$error =
"You need to supply a username or a valid barcode in the range to be downloaded.", last MAIN;
}
else
{
#It's OK - we can infer the user name from the code
($username) = bcgetinfofornumber($base);
}
}
else
{
bcchkuser($username) or $error =
"The user $username is not known - click <u>Show Users</u> to see a list.", last MAIN;
#We have a problem if the code does not belong to the user...
if($base)
{
[bcgetinfofornumber($base)]->[0] eq $username or $base = undef;
}
}
#What if several username boxes are filled in?
#We're ok - only the one for the submitted form gets sent.
#Right ho:
print bcstarthtml("$PAGE_TITLE - Main Request Interface"),
bcnavbanner(),
bch1("Ready to export barcode data"),
expform2($base);
last MAIN;
}
if($q->param("reqimp")) #5
{
$q->delete("reqimp");
my $headings;
my @numbers;
my ($owner, $type, $count, $tcount, $empties, $addedrows);
#Check that a file has been provided and that we can load it into DBD::AnyData
$impfile or $error="You must supply a spreadsheet or CSV file to be uploaded", last MAIN;
my $impfilehandle = $q->upload("impfile") or
$error=$q->cgi_error() || "Internal server error - unable to process uploaded file.", last MAIN;
#Save the file in the log for later
my ($impfileextn) = ($impfile =~ /.*\.(.*)/);
binmode $impfilehandle;
bclogevent( 'upload', $username || 'blank', 0, $impfileextn, $impfilehandle );
my $tableio = new TableIO();
my $impreader;
eval{$impreader = $tableio->get_reader($impfilehandle, $impfile)};
$@ and $error="Unable to load the file:\n$@", last MAIN;
#Check that there is a 'barcode' column
my $bcfound = $impreader->find_barcode_column();
defined($bcfound) or $error="No barcode column found in the uploaded file.", last MAIN;
#Get numbers (ie the barcode column)
@numbers = @{$impreader->get_all_barcodes()};
#Ensure that there is no junk or blanks, as this stuffs up the SQL later
$tcount = @numbers; #The total rows in the file.
@numbers = map {bcdequote($_) || ()} @numbers;
$count = @numbers or $error="No data in this file!", last MAIN;
#Validate that all numbers are of same type and owner
for($numbers[0])
{
eval{
($owner, $type) = bcgetinfofornumber($_);
};
$@ and $error="While checking first line ($_):\n$@", last MAIN;
#If strict user checking is in force, check now.
if($STRICT_USER_NAMES)
{
my $idxq = bcquote($_);
$username or $error = "You need to give a username to upload data.", last MAIN;
$username eq $owner or $error =
"You are trying to modify code $idxq but it belongs to $owner and you gave the username $username.",
last MAIN;
}
}
for(my $nn=1; $nn < @numbers; $nn++)
{
my ($xowner, $xtype);
eval{
($xowner, $xtype) = bcgetinfofornumber($numbers[$nn])
};
$@ and $error="While checking line " . ($nn + 1) . " (code " . bcquote($numbers[$nn]) . "):\n$@", last MAIN;
$xowner ne $owner and $error="All barcodes in an uploaded file must have the same owner.\n".
"Barcodes in this file belong to both $owner and $xowner.", last MAIN;
$xtype ne $type and $error="All barcodes in an uploaded file must be of the same type.\n".
"Barcodes of both types $type and $xtype found in this file.", last MAIN;
}
#Print a message saying please wait
print bcstarthtml("$PAGE_TITLE - Main Request Interface"),
bcnavbanner(),
bch1("Data import in progress"),
$q->p("Reading file <i>$impfile</i>"),
$q->p("<b>$count codes</b> found of type <b>" . bczapunderscores($type). "</b> with owner <b>$owner</b>."),
$q->p("Processing...");
#Strip out disposed numbers
my %disposedhash;
for(@numbers)
{
$disposedhash{$_}++ if bcdisposedateandcomments($_);
}
@numbers = grep {!$disposedhash{$_}} @numbers;
my $disposedcount = scalar(keys(%disposedhash));
#Delete, then re-insert all rows
eval{
my $deletedhash = bcexpungerecords(\@numbers, $type);
$empties = importrecords($impreader, $bcfound, $type, $deletedhash, \%disposedhash);
#The number of new rows will be $tcount - $empties - $disposedcount - scalar(keys(%$deletedhash))
$addedrows = $tcount - $empties - $disposedcount - scalar(keys(%$deletedhash));
};
if($@)
{
#Not too good
bcrollback();
$impreader->flush();
$error="Failed to process all records - all updates have been rolled back.\n
$@", last MAIN;
}
#Commit
bccommit();
#Now is a good time to update the link index
#This is the only point I should need to worry about indexing as it is the only time the data
#tables get updated.
eval{
no warnings qw(once);
require barcodeIndexer;
$barcodeIndexer::IGNORE_ERRORS = 0;
barcodeIndexer::indexcodes(@numbers);
bccommit();
} or bcrollback(); #If that fails, never mind. The index is not crucial.
#Were there empties, disposed, etc? Report!
print $q->start_p;
#Remember that empties = completely blank lines + lines without data
$empties and print
"Skipped <b>$empties empty lines</b> in the imported file.", $q->br;
$disposedcount and print
"Will not update <b>$disposedcount disposed codes</b>.", $q->br;
$empties + $disposedcount == $tcount and print
"All the lines in this file were empty or referred to disposed codes - nothing will be updated!", $q->br;
$addedrows == 1 and print
"<b>1 new record</b> was added.", $q->br;
$addedrows != 1 and print
"<b>$addedrows new records</b> were added.", $q->br;
$empties + $disposedcount != $tcount and print
"Total of <b>", $tcount - $empties - $disposedcount, " lines</b> from this file logged in the database.", $q->br;
print $q->end_p;
#Report success.
print $q->p($q->b("DONE - All data successfully committed to the database.")),
$q->hr, $q->hr;
# $impreader->flush();
#Don't quit - show the main page again.
}
if($q->param("reqdisp")) #8
{
$q->delete("reqdisp");
#Remove rogue chars and normalise space
my @disparr = eval{ displist_normalise($displist) };
$@ and $error = $@, last MAIN;
!@disparr and $error = "You did not specify any barcodes to dispose.", last MAIN;
#Check that all codes are allocated
my @notdisposable = checkallocated(\@disparr, 4);
if(@notdisposable)
{
if(@notdisposable == 1)
{
#The only reason for refusing a disposal is if the thing is unallocated.
$error = "The barcode " . bcquote($notdisposable[0]) . " is not allocated yet.";
}
elsif(@notdisposable <= 3)
{
$error = scalar(@notdisposable) . " of the barcodes you asked to dispose of are not allocated.\n" .
"These were: " . join(', ', map {bcquote($_)} @notdisposable) . ".";
}
else
{
$error = "Some of the barcodes you asked to dispose of are not allocated.\n" .
"eg. " . join(', ', map {bcquote($_)} @notdisposable[0..2]) . ", etc...";
}
last MAIN;
}
#Finally check the owner matches
if($STRICT_USER_NAMES)
{
$username or $error = "You must supply the correct user name to dispose of barcodes.", last MAIN;
for my $acode (@disparr)
{
my ($codeowner) = bcgetinfofornumber($acode);
if($username ne $codeowner)
{
$error = "You are trying to dispose of code " . bcquote($acode) . " but it belongs to $codeowner, not $username.";
last MAIN;
}
}
}
#Mark all deletions
my($disposedlist, $nodatalist, $alreadydisplist) = bcdodisposal(\@disparr, $dispcomments);
my $dispcount = @$disposedlist;
my $nodatacount = @$nodatalist;
my $alreadydispcount = @$alreadydisplist;
my $totaldispcount = @$disposedlist + @$nodatalist;
#Commit
bccommit();
#Log it
bclogevent( 'disp', $username, $disparr[0], undef,
"Disposed of " . @disparr . " codes owned by $username with comment:\n$dispcomments.\n"
.formatcodes(\@disparr)
);
#Success
$q->delete("displist");
#Print message and then redisplay form.
print bcstarthtml("$PAGE_TITLE - Main Request Interface"),
bcnavbanner(),
bch1("Disposing of " . @disparr . " barcode" . (@disparr != 1 ? "s" : ""));
#Summary rules:
#If there was just one code just say what happened.
#Otherwise list by type.
print $q->start_p;
if(@disparr == 1)
{
#A single code
my $idxq = bcquote($disparr[0]);
print(
($dispcount)
? "Successfully disposed of barcode $idxq."
:($nodatacount)
? "Successfully disposed of barcode $idxq, which was allocated but unused."
: "The barcode $idxq was already marked as disposed!"
);
}
else
{
#More than one code
print(
($dispcount)
? "The following $dispcount barcodes were marked disposed:"
.formatcodes($disposedlist)
: "",
($nodatacount)
? "The following $nodatacount barcodes were allocated but unused, and have been marked disposed:"
.formatcodes($nodatalist)
: "",
($alreadydispcount)
? "The following $alreadydispcount codes have not been changed, as they are already disposed:"
.formatcodes($alreadydisplist)
: ""
);
}
print
$q->end_p,
$q->p("No information has been removed from the database. If you made a mistake and need to un-do
this disposal please use the \"Extra Admin\" menu or contact the database administrator."),
$q->hr, $q->hr;
}
#otherwise must be a new request #1
print bcstarthtml("$PAGE_TITLE - Main Request Interface"),
bcnavbanner(),
bch1(($PAGE_DESC ? "$PAGE_DESC - " : "") . "Request interface"),
jumplinks(),
( $CONFIG{PAGE_MESSAGE} ? $q->p($CONFIG{PAGE_MESSAGE}) : '' ),
( $ENABLE_PLUGIN ? pluginform() . $q->hr : '' ),
reqform(), $q->hr,
expform(), $q->hr,
impform(), $q->hr,
dispform(), $q->hr,
$q->p( $q->h4("Notes:"), $q->ul( {-id=>"noteslist"},
$q->li([ $q->a({-name=>'note1'}, "") .
"Use the main menu at the top of this page to access the various Handlebar features.",
"New types need to be defined within the underlying database. To get a type added,
please contact the system maintainer, $PAGE_MAINTAINER. More information
can be found in the online help.",
"If you need to change ownership or type of records,
or you need to change the comment block then this can be done manually.
Again, please contact the maintainer.",
"Usernames are used to keep track of who is doing what - there is
no security enforcement so you can make requests on behalf of any
other user.",
])
));
}
#Ending bit
if($error)
{
print bcheader(), bcstarthtml("Error - $PAGE_TITLE");
$error =~ s/\n/<br \/>\n/g;
print $q->p({-class=>"errorbox"},
"The following error occured:\n<br /><br />$error");
#Log the error too
bclogevent( 'error', $username || 'blank', 0, undef, $error );
#Clear params and go again:
if($errorloop++)
{
die "Oh dear - this script is broken.";
}
else
{
main();
}
}
else
{
print $q->end_div(), bcfooter();
}
};#done main
sub jumplinks
{
#Some quick links to navigate the page
$q->p( {-class => 'jumpto'},
"Jump to: " .
($ENABLE_PLUGIN ? $q->a({-href=>('#'.bczapspaces(lc(get_plugin_tag())))}, get_plugin_tag()) : '') .
$q->a({-href=>'#allocate'}, "Allocate") .
$q->a({-href=>'#retrieve'}, "Retrieve") .
$q->a({-href=>'#submit'}, "Submit") .
$q->a({-href=>'#dispose'}, "Dispose")
);
}
sub pluginform
{
my $ios = new IO::String;
my $pluginlink = 'plugin/' . bczapspaces(lc($ENABLE_PLUGIN)) . '.cgi';
load_plugin_pm();
print $ios
$q->a({-name=>bczapspaces(lc(get_plugin_tag()))}, ''),
$q->start_form(-name=>"gotoplugin", -method=>"GET", -action=>$pluginlink),
$q->h2( get_plugin_label() );
#Handle the case where <plugin>.pm can't be read.
if(!$_PLUGIN_HANDLE)
{
print $ios
$q->p("This Handlebar instance includes a custom helper plugin, <b>\"$ENABLE_PLUGIN\"</b>, which
can be used to quickly set up new samples."),
$q->table( {-class => "formtable"},
$q->Tr($q->td( {-style=>'padding-left:150px'}, ["", "", ""] )),
$q->Tr($q->td( ["", "", $q->submit( -name=>"gotoplugin", -value=>"Use plugin")] )),
);
}
else
{
print $ios $_PLUGIN_HANDLE->show_summary($q);
}
print $ios $q->end_form;
$ios->str;
}
sub get_plugin_tag
{
#My new idea is that if the plugin has a $ENABLE_PLUGIN.pm in plugins/
#it will be loaded and expected to supply the following methods:
# get_tag()
# get_label()
# show_summary() - shows the content to be embedded in the front page
load_plugin_pm();
$_PLUGIN_HANDLE ?
$_PLUGIN_HANDLE->get_tag() :
'Generate' ;
}
sub get_plugin_label
{
load_plugin_pm();
$_PLUGIN_HANDLE ?
$_PLUGIN_HANDLE->get_label() :
'Generate barcodes using a helper plugin' ;
}
sub load_plugin_pm
{
#Here I rely on require ... returning the last value from the eval'd file.
#This seems to be semi-documented behaviour.
eval{
$_PLUGIN_HANDLE = require("plugin/" . bczapspaces(lc($ENABLE_PLUGIN)) . '.pm');
} unless $_PLUGIN_HANDLE;
}
sub reqform
{
my $ios = new IO::String;
#Generate link to view users or describe a type
my $myurl = $q->url(-relative=>1);
my $userlink = $q->a({ -href => "javascript:;",
-onClick => "window.open(
'$myurl?userpopup=1', 'Info',
'width=800,height=600,resizable=yes,scrollbars=yes');" },
"Show users" );
my $newuserlink = $q->a({ -href => "new_user_request.cgi" }, "Register new user");
my $newtypelink = "Register new type - " . $q->a({ -href => "#note1" }, "see notes");
my $typeslist = [bczapunderscores( @{bcgetbctypes({showhidden=>0})} )];
my $typeslink = $q->a({-href => "javascript:;",
-onClick =>
"window.open(
'$myurl?typespopup=1#' +
zapspaces(
reqform.bctype[reqform.bctype.selectedIndex].value
),
'Info',
'width=800,height=600,resizable=yes,scrollbars=yes');" },
"Describe type" );
print $ios
$q->a({-name=>'allocate'}, ''),
$q->start_form(-name=>"reqform", -method=>"POST"),
$ENABLE_PLUGIN ?
$q->h2("Manually allocate a range of barcodes") :
$q->h2("Allocate a range of barcodes"),
$q->p("You must request a range of barcodes before using them, and say
what type of item they will be used to label.<br />
It is better to request too many than too few. You can request up to $MAX_CODES
in a block."),
$q->table( {-class => "formtable"},
$q->Tr($q->td( ["User name ", $q->textfield("username"), $userlink, $newuserlink] )),
$q->Tr($q->td( ["Type of item ",
$q->popup_menu( -name=>"bctype",
-values=>$typeslist ),
$typeslink, $newtypelink] )),
$q->Tr($q->td( ["How many ", $q->textfield("bcquantity"), ""] )),
$q->Tr($q->td( "Comment " ),
$q->td({-colspan=>"3"}, $q->textfield({-size=>60, -name=>"bccomments"}))),
$q->Tr($q->td( ["", "", $q->submit( -name=>"reqcodes", -value=>"Make request")] )),
),
$q->end_form;
#Now we need a JS function which replaces spaces with underscores
print $ios '<script type="text/javascript">',
bczapspaces_js(),
'</script>';
$ios->str;
}
sub expform
{
my $ios = new IO::String;
#For getting a CSV file for an allocation block.
#Will fill in data if it is there, otherwise will send out a template.
print $ios
$q->a({-name=>'retrieve'}, ''),
$q->start_form(-name=>"expform", -method=>"GET"),
$q->h2("Retrieve a spreadsheet for an allocated range of codes"),
$q->p( "You need to give your user name, and type in any number within the range
of codes you want, or just click <b>retrieve</b> to see a list of all your codes."),
$q->table( {-class => "formtable"},
$q->Tr($q->td( ["User name ", $q->textfield("username"), ""] )),
$q->Tr($q->td( ["Barcode in range ", $q->textfield("bcreqrange"), ""] )),
$q->Tr($q->td( ["", "", $q->submit( -name=>"reqexp", -value=>"Retrieve...")] )),
),
$q->end_form;
$ios->str;
}
sub expform2
{
my $ios = new IO::String;
my $base = shift();
#Everything is validated (base is a real base or undef) -
#just emit a form with a link to download the CSV
my $url = $q->url(relative=>1);
my $retrlink = $q->a({ -href=> "",
-id=> "csvlink" },
"Nothing Selected" );
#Get all allocation blocks for this user
my $blocksforuser = bcgetblocksforuser($username);
if($blocksforuser->active_blocks())
{
my $actualbase = $base || $blocksforuser->highest_active_base();
print $ios $q->start_form(-name=>"expform2", -method=>"GET"),
$q->p("These are the active blocks owned by $username:"),
$blocksforuser->render_scrolling_list({
-default=> $actualbase,
#-onChange=> "javascript:setlink(this[this.selectedIndex].value)"
}),
$q->p("If the block of codes contains disposed items, you can choose to mask them
out with <b>$DISPOSE_MASK</b>, to include them as-is or else to omit them entirely. If
you include any disposed codes in a file that you upload then they will simply
be skipped and not updated."),
$q->p("What to do with disposed codes? " .
$q->popup_menu({-name=>"dispoption", -values=>[qw(Mask Include Omit)], -default=>"Omit"})),
$q->p("Format for downloaded data: " .
$q->popup_menu({-name=>"expformat",
-values=>TableIO::get_format_names(),
-default=>"Excel"})),
$q->p("Click here to retrieve data : " . $q->submit(-name=>"reqcsv", -value=>"Download")),
$q->end_form;
# my $baseurl = $q->url(-relative=>1,-query=>0);
# print $ios '<script type="text/javascript">',
# bcquote_js(),
# qq|
# function setlink(selected_barcode){
# sb = bcquote(selected_barcode);
# var newurl = "$baseurl?reqcsv=1&base=" +sb;
# document.getElementById("csvlink").href = newurl;
# document.getElementById("csvlink").innerHTML = "CSV download (from " +sb+ ")";
# }
# setlink('$actualbase');
# </script>
# |;
}
else
{
print $ios $q->p("No active barcode blocks found in the database for $username.");
}
$ios->str;
}
sub impform
{
my $ios = new IO::String;
#Import - ie submit a CSV/Spreadsheet file to the database and get it checked in.
#Don't forget that for file uploads you need to use 'start_multipart_form'
print $ios
$q->a({-name=>'submit'}, ''),
$q->start_multipart_form(-name=>"impform", -method=>"POST"),
$q->h2("Submit barcode data to the central database"),
$q->p( "Select a spreadsheet to save in the database.
You can modify and re-submit the data as many times as you like."),
$q->start_table( {-class => "formtable"} );
if($STRICT_USER_NAMES)
{
print $ios
$q->Tr($q->td( ["User name ", $q->textfield("username"), ""] ));
}
print $ios
$q->Tr($q->td( ["File to upload ", $q->filefield(-name=>"impfile"),""] )),
$q->Tr($q->td( ["", "", $q->submit( -name=>"reqimp", -value=>"Submit")] )),
$q->end_table,
$q->end_form;
$ios->str;
}
sub dispform
{
my $ios = new IO::String;
#Delete a barcode or a whole range of codes.
print $ios
$q->a({-name=>'dispose'}, ''),
$q->start_multipart_form(-name=>"dispform", method=>"POST"),
$q->h2("Mark barcodes as being disposed"),
$q->p( "If you are disposing of samples, you can tell the database that the barcodes
are no longer in use. The information associated with the code will remain
in the database for reference. You can add a
comment to say who disposed of the items and why - the date will also be logged
automatically."),
$q->p( "Give a list of numbers to delete, separated by spaces or on several lines.
You can also specify ranges of codes in the form " . bcquote(1230) . ":" .
bcquote(1240) . "."),
$q->start_table( {-class => "formtable"} ),
$q->Tr($q->td( [ 'Codes',
$q->textarea( -name=>'displist',
-rows=>8,
-columns=>40 ), '' ]));
if($STRICT_USER_NAMES)
{
print $ios
$q->Tr($q->td( ["User name ", $q->textfield("username"), ''] ));
}
print $ios
$q->Tr($q->td( ["Comments ", $q->textfield({-size=>40 , -name=>"dispcomments"}), ''] )),
$q->Tr($q->td( [ '', '', $q->submit( -name=>"reqdisp", -value=>"Submit") ])),
$q->end_table;
;
$ios->str;
}
#Given an array of codes, check that they are all allocated
#give up after $failures failures
sub checkallocated
{
my $codes = shift;
my $failures = shift || 1;
my @failedlist;
for my $acode(@$codes)
{
eval{ bcgetinfofornumber($acode); };
if($@)
{
push @failedlist, $acode;
last unless --$failures;
}
}
return @failedlist;
}
sub displist_normalise
{
#Take the argument with the numbers in and return an array of codes
my $list = shift;
my @res;
for($list) {
#Knock out all the hyphens
tr/-//d;
#Then make sure that every character which is not a colon or a digit is converted to a space.
#And remove duplicate whitespace.
tr/:0-9/ /cs;
#Now collapse any spaces which are not bounded by digits
s/ :/:/g;s/: /:/g;
}
#Right-ho
for(split / /, $list)
{
if(/^\d+$/) { push(@res, $_) }
elsif(/^(\d+):(\d+)$/)
{
if(abs($2 - $1) > 10000) { die "Range $_ is larger than the maximum number of codes allowed
for disposal in one go. Aborting.\n" };
if($2 < $1) { push(@res, $2..$1) }
else { push(@res, $1..$2) }
}
else
{
#This catches something like 30:40:50
die "Range $_ is not a valid range of codes.\n";
}
}
return @res;
}
sub offer_download
{
my $ios = new IO::String;
#Offer the user the ability to download a CSV file (hopefully an OO file soon)
#caller guarantees that $base is a sensible number
my $base = shift;
my $link = $q->url(-relative=>1) . "?reqexp=1&bcreqrange=$base&username=$username";
#TODO - make sure this offers alternative formats.
print $ios $q->p("Click here to retrieve template : ",
$q->a({-href=>$link}, "Download Template")
),
;
$ios->str;
}
sub importrecords
{
my ( $tio, #Active TableIO object to read records from table
$bcfound, #Column containing barcode
$type,
$deletedhash, #All the codes found in the file that were already in the DB
$disposedhash ) = @_;
my $table = bctypetotable($type);
my $headings = $tio->get_column_names;
my $empties = 0;
#We need to deal with column name mismatches and fail or warn gracefully.
#First off, must make sure that all the column names are valid SQL identifiers, and detect
#any empty columns.
#Then later if there is a header mismatch it will be caught by the database
#Note - I'd originally assumed that the sheet would be rectangular, but it seems not - ie.
#we may see longer rows (but not shorter??) further down. Fortunately these are caught later
#because the database sees extra bind values. Leave in the check here as it is still applicable
#to CSV.
{local $Data::Dumper::Terse = 1;
$headings = [map {my $h = $_;
$h =~ tr/ /_/;
$h =~ s/\W//g;
$h ||
die "Invalid or blank column heading in first row of input file. " .
"This normally means that data has been inserted into a cell " .
"to the right of the last column which causes the sheet to expand and " .
"empty (undefined) headings to appear at the end. " .
"If this was the case please delete the whole final column and retry.\n" .
"Headings found were: \n" .
Dumper($headings)
} @$headings];
}
#See which columns are barcodes, other than the actual barcode.
my @colswithbarcodes = ();
for(my $nn = 0; $nn < @$headings; $nn++)
{
if(bcgetflagsforfield($type, $headings->[$nn])->{bc})
{
push @colswithbarcodes, $nn;
}
}
#Any old records should have been expunged, so just insert the new ones.
my $inserth = bcprepare("
INSERT INTO $table (" . join(', ', @$headings) . ")
VALUES (" . join(', ', ('?') x @$headings) .")
");
while( my $row = $tio->get_next_row() )
{
#Have to check and then dereference.
my @row = @$row or last;
my $fieldsfound = 0;
map { $fieldsfound++ if defined $_ && $_ ne '' } @row;
#Skip totally blank rows
if($fieldsfound == 0){ $empties++; next; }