2 use strict; use warnings;
6 use OpenSRF::Utils::Logger qw/$logger/;
7 use OpenILS::Application::AppUtils;
9 use OpenSRF::EX qw/:try/;
11 use OpenILS::Utils::Fieldmapper;
12 use Digest::MD5 qw/md5_hex/;
13 use OpenSRF::Utils qw/:daemon/;
14 use OpenILS::Utils::OfflineStore;
15 use OpenSRF::Utils::SettingsClient;
20 my $U = "OpenILS::Application::AppUtils";
21 my $DB = "OpenILS::Utils::OfflineStore";
22 my $SES = "${DB}::Session";
23 my $SCRIPT = "OpenILS::Utils::OfflineStore::Script";
25 # --------------------------------------------------------------------
27 # --------------------------------------------------------------------
29 do '##CONFIG##/offline-config.pl';
33 my $basedir = $config{base_dir} || die "Offline config error: no base_dir defined\n";
34 my $bootstrap = $config{bootstrap} || die "Offline config error: no bootstrap defined\n";
35 my $wsname = $cgi->param('ws');
36 my $org = $cgi->param('org');
37 my $authtoken = $cgi->param('ses') || "";
38 my $seskey = $cgi->param('seskey');
39 my $action = $cgi->param('action'); # - create, load, execute, status
51 # --------------------------------------------------------------------
53 # This function should behave as a child_init might behave in case
54 # this is moved to mod_perl
55 # --------------------------------------------------------------------
58 $DB->DBFile($config{db});
59 OpenSRF::System->bootstrap_client(config_file => $bootstrap );
60 Fieldmapper->import(IDL =>
61 OpenSRF::Utils::SettingsClient->new->config_value("IDL"));
65 sub _ol_debug_params {
67 my @params = $cgi->param;
68 @params = sort { $a cmp $b } @params;
69 $s .= "$_=" . $cgi->param($_) . "\n" for @params;
71 warn '-'x60 ."\n$s\n";
75 # --------------------------------------------------------------------
76 # Finds the requestor and other info specific to this request
77 # --------------------------------------------------------------------
80 # fetch the requestor object
81 ($requestor, $evt) = $U->checkses($authtoken);
82 ol_handle_result($evt) if $evt;
84 # try the param, the workstation, and finally the user's ws org
86 $wsobj = ol_fetch_workstation($wsname);
87 $org = $wsobj->owning_lib if $wsobj;
88 $org = $requestor->ws_ou unless $org;
89 ol_handle_result(OpenILS::Event->new('OFFLINE_NO_ORG')) unless $org;
94 # --------------------------------------------------------------------
95 # Runs the requested action
96 # --------------------------------------------------------------------
101 if( $action eq 'create' ) {
103 $evt = $U->check_perms($requestor->id, $org, 'OFFLINE_UPLOAD');
104 ol_handle_result($evt) if $evt;
105 $payload = ol_create_session();
107 } elsif( $action eq 'load' ) {
109 $evt = $U->check_perms($requestor->id, $org, 'OFFLINE_UPLOAD');
110 ol_handle_result($evt) if $evt;
111 $payload = ol_load();
113 } elsif( $action eq 'execute' ) {
115 $evt = $U->check_perms($requestor->id, $org, 'OFFLINE_EXECUTE');
116 ol_handle_result($evt) if $evt;
117 $payload = ol_execute();
119 } elsif( $action eq 'status' ) {
121 $evt = $U->check_perms($requestor->id, $org, 'OFFLINE_VIEW');
122 ol_handle_result($evt) if $evt;
123 $payload = ol_status();
126 ol_handle_event('SUCCESS', payload => $payload );
130 # --------------------------------------------------------------------
131 # Creates a new session
132 # --------------------------------------------------------------------
133 sub ol_create_session {
135 my $desc = $cgi->param('desc') || "";
136 $seskey = time . "_${$}_" . int(rand() * 1000);
138 $logger->debug("offline: user ".$requestor->id.
139 " creating new session with key $seskey and description $desc");
145 description => $desc,
146 creator => $requestor->id,
147 create_time => CORE::time(),
156 # --------------------------------------------------------------------
157 # Holds the meta-info for a script file
158 # --------------------------------------------------------------------
159 sub ol_create_script {
162 my $session = ol_find_session($seskey);
163 my $delta = $cgi->param('delta') || 0;
165 my $script = $session->add_to_scripts(
167 requestor => $requestor->id,
168 create_time => CORE::time,
169 workstation => $wsname,
170 logfile => "$basedir/pending/$org/$seskey/$wsname.log",
171 time_delta => $delta,
177 # --------------------------------------------------------------------
178 # Finds the current session in the db
179 # --------------------------------------------------------------------
180 sub ol_find_session {
181 my $ses = $SES->retrieve($seskey);
182 ol_handle_event('OFFLINE_INVALID_SESSION', payload => $seskey) unless $ses;
186 # --------------------------------------------------------------------
187 # Finds a script object in the DB based on workstation and seskey
188 # --------------------------------------------------------------------
190 my $ws = shift || $wsname;
191 my $sk = shift || $seskey;
192 my ($script) = $SCRIPT->search( session => $seskey, workstation => $ws );
196 # --------------------------------------------------------------------
197 # Creates a new script in the database and loads the new script file
198 # --------------------------------------------------------------------
201 my $session = ol_find_session;
202 my $handle = $cgi->upload('file');
203 my $outdir = "$basedir/pending/$org/$seskey";
204 my $outfile = "$outdir/$wsname.log";
206 ol_handle_event('OFFLINE_SESSION_FILE_EXISTS') if ol_find_script();
207 ol_handle_event('OFFLINE_SESSION_ACTIVE') if $session->in_process;
208 ol_handle_event('OFFLINE_SESSION_COMPLETE') if $session->end_time;
210 qx/mkdir -p $outdir/;
212 open(FILE, ">>$outfile") or ol_handle_event('OFFLINE_FILE_ERROR');
213 while( <$handle> ) { print FILE; $x++;}
216 ol_create_script($x);
222 # --------------------------------------------------------------------
223 sub ol_handle_result {
225 my $json = JSON->perl2JSON($obj);
227 # Clear this so it's not remembered
230 if( $cgi->param('html')) {
231 my $html = "<html><body onload='xulG.handle_event($json)'></body></html>";
232 print "content-type: text/html\n\n";
237 print "content-type: text/plain\n\n";
244 # --------------------------------------------------------------------
245 sub ol_handle_event {
246 my( $evt, @args ) = @_;
247 ol_handle_result(OpenILS::Event->new($evt, @args));
251 # --------------------------------------------------------------------
252 sub ol_flesh_session {
256 map { $data{$_} = $session->$_ } $session->columns;
259 for my $script ($session->scripts) {
261 map { $sdata{$_} = $script->$_ } $script->columns;
263 # the client doesn't need this info
264 delete $sdata{session};
266 delete $sdata{logfile};
268 push( @{$data{scripts}}, \%sdata );
275 # --------------------------------------------------------------------
276 # Returns various information on the sessions and scripts
277 # --------------------------------------------------------------------
280 my $type = $cgi->param('status_type') || "scripts";
282 # --------------------------------------------------------------------
283 # Returns info on every script upload attached to the current session
284 # --------------------------------------------------------------------
285 if( $type eq 'scripts' ) {
286 my $session = ol_find_session();
287 ol_handle_result(ol_flesh_session($session));
290 # --------------------------------------------------------------------
291 # Returns all scripts and sessions for the given org
292 # --------------------------------------------------------------------
293 } elsif( $type eq 'sessions' ) {
294 my @sessions = $SES->search( org => $org );
296 # can I do this in the DB without raw SQL?
297 @sessions = sort { $a->create_time <=> $b->create_time } @sessions;
299 push( @data, ol_flesh_session($_) ) for @sessions;
300 ol_handle_result(\@data);
303 # --------------------------------------------------------------------
304 # Returns total commands and completed commands counts
305 # --------------------------------------------------------------------
306 } elsif( $type eq 'summary' ) {
307 my $session = ol_find_session();
309 $logger->debug("offline: retrieving summary info ".
310 "for session ".$session->key." with completed=".$session->num_complete);
313 $count += $_->count for ($session->scripts);
315 { total => $count, num_complete => $session->num_complete });
319 # --------------------------------------------------------------------
320 # Returns the list of non-SUCCESS events that have occurred so far for
321 # this set of commands
322 # --------------------------------------------------------------------
323 } elsif( $type eq 'exceptions' ) {
325 my $session = ol_find_session();
326 my $resfile = "$basedir/pending/$org/$seskey/results";
327 if( $session->end_time ) {
328 $resfile = "$basedir/archive/$org/$seskey/results";
330 my $data = ol_file_to_perl($resfile);
331 $data = [ grep { $_->{event}->{ilsevent} ne '0' } @$data ];
332 ol_handle_result($data);
337 sub ol_fetch_workstation {
339 $logger->debug("offline: Fetching workstation $name");
340 my $ws = $U->storagereq(
341 'open-ils.storage.direct.actor.workstation.search.name', $name);
342 ol_handle_result(OpenILS::Event->new('ACTOR_WORKSTATION_NOT_FOUND')) unless $ws;
349 # --------------------------------------------------------------------
350 # Sorts the script commands then forks a child to executes them.
351 # --------------------------------------------------------------------
354 my $session = ol_find_session();
355 ol_handle_event('OFFLINE_SESSION_ACTIVE') if $session->in_process;
356 ol_handle_event('OFFLINE_SESSION_COMPLETE') if $session->end_time;
358 my $commands = ol_collect_commands();
360 # --------------------------------------------------------------------
361 # Note that we must disconnect from opensrf before forking or the
362 # connection will be borked...
363 # --------------------------------------------------------------------
364 OpenSRF::Transport::PeerHandle->retrieve->disconnect;
370 # --------------------------------------------------------------------
371 # Tell the client all is well
372 # --------------------------------------------------------------------
373 ol_handle_event('SUCCESS'); # - this exits
378 # --------------------------------------------------------------------
379 # close stdout/stderr or apache will wait on the child to finish
380 # --------------------------------------------------------------------
384 $logger->debug("offline: child $$ processing data...");
386 # --------------------------------------------------------------------
387 # The child re-connects to the opensrf network and processes
388 # the script requests
389 # --------------------------------------------------------------------
390 OpenSRF::System->bootstrap_client(config_file => $bootstrap);
395 #Class::DBI->autoupdate(1);
399 my $sesion = ol_find_session();
400 $session->in_process(1);
401 ol_process_commands($session, $commands);
402 ol_archive_files($session);
406 $logger->error("offline: child process error $e");
411 sub ol_file_to_perl {
413 open(F, "$fname") or ol_handle_event('OFFLINE_FILE_ERROR');
416 push(@p, JSON->JSON2perl($_)) for @d;
421 # collects the commands and sorts them on timestamp+delta
422 sub ol_collect_commands {
423 my $ses = ol_find_session();
426 # cycle through every script loaded to this session
427 for my $script ($ses->scripts) {
428 my $coms = ol_file_to_perl($script->logfile);
430 # cycle through all of the commands for this script
431 for my $com (@$coms) {
432 $$com{_workstation} = $script->workstation;
433 $$com{_realtime} = $script->time_delta + $com->{timestamp};
434 push( @commands, $com );
438 # make sure thera are no blank commands
439 @commands = grep { ($_ and $_->{type}) } @commands;
442 @commands = sort { $a->{_realtime} <=> $b->{_realtime} } @commands;
444 # push user registrations to the front
445 my @regs = grep { $_->{type} eq 'register' } @commands;
446 my @others = grep { $_->{type} ne 'register' } @commands;
448 return [ @regs, @others ];
452 my $time = shift || CORE::time;
453 my (undef,undef, undef, $mday,$mon,$year) = localtime($time);
454 $mon++; $year += 1900;
455 $mday = "0$mday" unless $mday =~ /\d{2}/o;
456 $mon = "0$mon" unless $mon =~ /\d{2}/o;
457 return ($year, $mon, $mday);
461 # --------------------------------------------------------------------
462 # Moves all files from the pending directory to the archive directory
463 # and removes the pending directory
464 # --------------------------------------------------------------------
465 sub ol_archive_files {
467 my ($y, $m, $d) = ol_date();
469 my $dir = "$basedir/pending/$org/$seskey";
470 my $archdir = "$basedir/archive/$org/$seskey";
471 $logger->debug("offline: archiving files to $archdir");
473 # Tell the db the files are moving
474 $_->logfile($archdir.'/'.$_->workstation.'.log') for ($session->scripts);
476 qx/mkdir -p $archdir/;
477 qx/mv $_ $archdir/ for <$dir/*>;
482 # --------------------------------------------------------------------
483 # Appends results to the results file.
484 # --------------------------------------------------------------------
486 sub ol_append_result {
491 $obj = JSON->perl2JSON($obj);
494 open($rhandle, ">>$basedir/pending/$org/$seskey/results")
495 or ol_handle_event('OFFLINE_FILE_ERROR');
498 print $rhandle "$obj\n";
499 close($rhandle) if $last;
504 # --------------------------------------------------------------------
505 # Runs the commands and returns the list of errors
506 # --------------------------------------------------------------------
507 sub ol_process_commands {
510 my $commands = shift;
513 $session->start_time(CORE::time);
515 for my $d ( @$commands ) {
518 my $last = ($x++ == scalar(@$commands) - 1) ? 1 : 0;
519 my $res = { command => $d };
521 $res->{event} = ol_handle_checkin($d) if $t eq 'checkin';
522 $res->{event} = ol_handle_inhouse($d) if $t eq 'in_house_use';
523 $res->{event} = ol_handle_checkout($d) if $t eq 'checkout';
524 $res->{event} = ol_handle_renew($d) if $t eq 'renew';
525 $res->{event} = ol_handle_register($d) if $t eq 'register';
528 ol_append_result($res, $last);
529 $session->num_complete( $session->num_complete + 1 );
531 $logger->debug("offline: set session [".$session->key."] num_complete to ".$session->num_complete);
534 $session->end_time(CORE::time);
535 $session->in_process(0);
539 # --------------------------------------------------------------------
540 # Runs an in_house_use action
541 # --------------------------------------------------------------------
542 sub ol_handle_inhouse {
545 my $realtime = $command->{_realtime};
546 my $ws = $command->{_workstation};
547 my $barcode = $command->{barcode};
548 my $count = $command->{count} || 1;
549 my $use_time = $command->{use_time} || "";
551 $logger->activity("offline: in_house_use : requestor=". $requestor->id.", realtime=$realtime, ".
552 "workstation=$ws, barcode=$barcode, count=$count, use_time=$use_time");
554 my $ids = $U->simplereq(
556 'open-ils.circ.in_house_use.create', $authtoken,
557 { barcode => $barcode, count => $count, location => $org, use_time => $use_time } );
559 return OpenILS::Event->new('SUCCESS', payload => $ids) if( ref($ids) eq 'ARRAY' );
565 # --------------------------------------------------------------------
566 # Pulls the relevant circ args from the command, fetches data where
568 # --------------------------------------------------------------------
569 sub ol_circ_args_from_command {
572 my $type = $command->{type};
573 my $realtime = $command->{_realtime};
574 my $ws = $command->{_workstation};
575 my $barcode = $command->{barcode} || "";
576 my $cotime = $command->{checkout_time} || "";
577 my $pbc = $command->{patron_barcode};
578 my $due_date = $command->{due_date} || "";
579 my $noncat = ($command->{noncat}) ? "yes" : "no"; # for logging
581 $logger->activity("offline: $type : requestor=". $requestor->id.
582 ", realtime=$realtime, workstation=$ws, checkout_time=$cotime, ".
583 "patron=$pbc, due_date=$due_date, noncat=$noncat");
586 permit_override => 1,
588 checkout_time => $cotime,
589 patron_barcode => $pbc,
590 due_date => $due_date };
592 if( $command->{noncat} ) {
594 $args->{noncat_type} = $command->{noncat_type};
595 $args->{noncat_count} = $command->{noncat_count};
603 # --------------------------------------------------------------------
604 # Performs a checkout action
605 # --------------------------------------------------------------------
606 sub ol_handle_checkout {
608 my $args = ol_circ_args_from_command($command);
609 return $U->simplereq(
610 'open-ils.circ', 'open-ils.circ.checkout', $authtoken, $args );
614 # --------------------------------------------------------------------
615 # Performs the renewal action
616 # --------------------------------------------------------------------
617 sub ol_handle_renew {
619 my $args = ol_circ_args_from_command($command);
621 return $U->simplereq(
622 'open-ils.circ', 'open-ils.circ.renew', $authtoken, $args );
626 # --------------------------------------------------------------------
627 # Runs a checkin action
628 # --------------------------------------------------------------------
629 sub ol_handle_checkin {
632 my $realtime = $command->{_realtime};
633 my $ws = $command->{_workstation};
634 my $barcode = $command->{barcode};
635 my $backdate = $command->{backdate} || "";
637 $logger->activity("offline: checkin : requestor=". $requestor->id.
638 ", realtime=$realtime, ". "workstation=$ws, barcode=$barcode, backdate=$backdate");
640 return $U->simplereq(
642 'open-ils.circ.checkin', $authtoken,
643 { barcode => $barcode, backdate => $backdate } );
648 # --------------------------------------------------------------------
649 # Registers a new patron
650 # --------------------------------------------------------------------
651 sub ol_handle_register {
654 my $barcode = $command->{user}->{card}->{barcode};
655 delete $command->{user}->{card};
657 $logger->info("offline: creating new user with barcode $barcode");
659 # now, create the user
660 my $actor = Fieldmapper::actor::user->new;
661 my $card = Fieldmapper::actor::card->new;
664 # username defaults to the barcode
665 $actor->usrname( ($actor->usrname) ? $actor->usrname : $barcode );
667 # Set up all of the virtual IDs, isnew, etc.
671 $actor->cards([$card]);
676 $card->barcode($barcode);
682 for my $resp (@{$command->{user}->{survey_responses}}) {
683 my $sr = Fieldmapper::action::survey_response->new;
684 $sr->$_( $resp->{$_} ) for keys %$resp;
688 $logger->debug("offline: created new survey response for survey ".$sr->survey);
690 delete $command->{user}->{survey_responses};
691 $actor->survey_responses(\@sresp) if @sresp;
693 # extract the billing address
694 if( my $addr = $command->{user}->{billing_address} ) {
695 $billing_address = Fieldmapper::actor::user_address->new;
696 $billing_address->$_($addr->{$_}) for keys %$addr;
697 $billing_address->isnew(1);
698 $billing_address->id(-1);
699 $billing_address->usr(-1);
700 delete $command->{user}->{billing_address};
701 $logger->debug("offline: read billing address ".$billing_address->street1);
704 # extract the mailing address
705 if( my $addr = $command->{user}->{mailing_address} ) {
706 $mailing_address = Fieldmapper::actor::user_address->new;
707 $mailing_address->$_($addr->{$_}) for keys %$addr;
708 $mailing_address->isnew(1);
709 $mailing_address->id(-2);
710 $mailing_address->usr(-1);
711 delete $command->{user}->{mailing_address};
712 $logger->debug("offline: read mailing address ".$mailing_address->street1);
715 # make sure we have values for both
716 $billing_address ||= $mailing_address;
717 $mailing_address ||= $billing_address;
719 $actor->billing_address($billing_address->id);
720 $actor->mailing_address($mailing_address->id);
721 $actor->addresses([$mailing_address]);
723 push( @{$actor->addresses}, $billing_address )
724 unless $billing_address->id eq $mailing_address->id;
726 # pull all of the rest of the data from the command blob
727 $actor->$_( $command->{user}->{$_} ) for keys %{$command->{user}};
729 $logger->debug("offline: creating user object...");
730 $actor = $U->simplereq(
732 'open-ils.actor.patron.update', $authtoken, $actor);
734 return $actor if(ref($actor) eq 'HASH'); # an event occurred
736 return OpenILS::Event->new('SUCCESS', payload => $actor);