2 use strict; use warnings;
5 use OpenSRF::Utils::Logger qw/$logger/;
6 use OpenILS::Application::AppUtils;
8 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;
20 #Class::DBI->autoupdate(1);
21 #local $OpenILS::Utils::OfflineStore::NO_TRIGGERS = 1;
23 my $U = "OpenILS::Application::AppUtils";
24 my $DB = "OpenILS::Utils::OfflineStore";
25 my $SES = "${DB}::Session";
26 my $SCRIPT = "OpenILS::Utils::OfflineStore::Script";
31 # --------------------------------------------------------------------
33 # --------------------------------------------------------------------
34 #do '##CONFIG##/upload-server.pl';
35 do 'offline-config.pl';
39 my $basedir = $config{base_dir};
40 my $wsname = $cgi->param('ws');
41 my $org = $cgi->param('org');
42 my $authtoken = $cgi->param('ses') || "";
43 my $seskey = $cgi->param('seskey');
44 my $action = $cgi->param('action'); # - create, load, execute, status
56 # --------------------------------------------------------------------
58 # This function should behave as a child_init might behave in case
59 # this is moved to mod_perl
60 # --------------------------------------------------------------------
63 $DB->DBFile($config{db});
64 OpenSRF::System->bootstrap_client(config_file => $config{bootstrap} );
68 sub _ol_debug_params {
70 my @params = $cgi->param;
71 @params = sort { $a cmp $b } @params;
72 $s .= "$_=" . $cgi->param($_) . "\n" for @params;
74 warn '-'x60 ."\n$s\n";
78 # --------------------------------------------------------------------
79 # Finds the requestor and other info specific to this request
80 # --------------------------------------------------------------------
83 # fetch the requestor object
84 ($requestor, $evt) = $U->checkses($authtoken);
85 ol_handle_result($evt) if $evt;
88 # try the param, the workstation, and finally the user's ws org
90 $wsobj = ol_fetch_workstation($wsname);
91 $org = $wsobj->owning_lib if $wsobj;
92 $org = $requestor->ws_ou unless $org;
93 ol_handle_result(OpenILS::Event->new('OFFLINE_NO_ORG')) unless $org;
98 # --------------------------------------------------------------------
99 # Runs the requested action
100 # --------------------------------------------------------------------
105 if( $action eq 'create' ) {
107 $evt = $U->check_perms($requestor->id, $org, 'OFFLINE_UPLOAD');
108 ol_handle_result($evt) if $evt;
109 $payload = ol_create_session();
111 } elsif( $action eq 'load' ) {
113 $evt = $U->check_perms($requestor->id, $org, 'OFFLINE_UPLOAD');
114 ol_handle_result($evt) if $evt;
115 $payload = ol_load();
117 } elsif( $action eq 'execute' ) {
119 $evt = $U->check_perms($requestor->id, $org, 'OFFLINE_EXECUTE');
120 ol_handle_result($evt) if $evt;
121 $payload = ol_execute();
123 } elsif( $action eq 'status' ) {
125 $evt = $U->check_perms($requestor->id, $org, 'OFFLINE_VIEW');
126 ol_handle_result($evt) if $evt;
127 $payload = ol_status();
130 ol_handle_event('SUCCESS', payload => $payload );
134 # --------------------------------------------------------------------
135 # Creates a new session
136 # --------------------------------------------------------------------
137 sub ol_create_session {
139 my $desc = $cgi->param('desc') || "";
140 $seskey = time . "_${$}_" . int(rand() * 1000);
142 $logger->debug("offline: user ".$requestor->id.
143 " creating new session with key $seskey and description $desc");
149 description => $desc,
150 creator => $requestor->id,
151 create_time => CORE::time(),
160 # --------------------------------------------------------------------
161 # Holds the meta-info for a script file
162 # --------------------------------------------------------------------
163 sub ol_create_script {
166 my $session = ol_find_session($seskey);
167 my $delta = $cgi->param('delta') || 0;
169 my $script = $session->add_to_scripts(
171 requestor => $requestor->id,
172 create_time => CORE::time,
173 workstation => $wsname,
174 logfile => "$basedir/pending/$org/$seskey/$wsname.log",
175 time_delta => $delta,
181 # --------------------------------------------------------------------
182 # Finds the current session in the db
183 # --------------------------------------------------------------------
184 sub ol_find_session {
185 my $ses = $SES->retrieve($seskey);
186 ol_handle_event('OFFLINE_INVALID_SESSION', payload => $seskey) unless $ses;
190 # --------------------------------------------------------------------
191 # Finds a script object in the DB based on workstation and seskey
192 # --------------------------------------------------------------------
194 my $ws = shift || $wsname;
195 my $sk = shift || $seskey;
196 my ($script) = $SCRIPT->search( session => $seskey, workstation => $ws );
200 # --------------------------------------------------------------------
201 # Creates a new script in the database and loads the new script file
202 # --------------------------------------------------------------------
204 my $session = ol_find_session;
205 my $handle = $cgi->upload('file');
206 my $outdir = "$basedir/pending/$org/$seskey";
207 my $outfile = "$outdir/$wsname.log";
209 ol_handl_event('OFFLINE_SESSION_FILE_EXISTS') if ol_find_script();
210 ol_handle_event('OFFLINE_SESSION_ACTIVE') if $session->in_process;
211 ol_handle_event('OFFLINE_SESSION_COMPLETE') if $session->end_time;
213 qx/mkdir -p $outdir/;
215 open(FILE, ">>$outfile") or ol_handle_event('OFFLINE_FILE_ERROR');
216 while( <$handle> ) { print FILE; $x++;}
219 ol_create_script($x);
225 # --------------------------------------------------------------------
226 sub ol_handle_result {
228 my $json = JSON->perl2JSON($obj);
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));
289 # --------------------------------------------------------------------
290 # Returns all scripts and sessions for the given org
291 # --------------------------------------------------------------------
292 } elsif( $type eq 'sessions' ) {
293 my @sessions = $SES->search( org => $org );
295 # can I do this in the DB without raw SQL?
296 @sessions = sort { $a->create_time <=> $b->create_time } @sessions;
298 push( @data, ol_flesh_session($_) ) for @sessions;
299 ol_handle_result(\@data);
301 # --------------------------------------------------------------------
302 # Returns total commands and completed commands counts
303 # --------------------------------------------------------------------
304 } elsif( $type eq 'summary' ) {
305 my $session = ol_find_session();
307 $logger->debug("offline: retrieving summary info ".
308 "for session ".$session->key." with completed=".$session->num_complete);
311 $count += $_->count for ($session->scripts);
313 { total => $count, num_complete => $session->num_complete });
318 sub ol_fetch_workstation {
320 $logger->debug("offline: Fetching workstation $name");
321 my $ws = $U->storagereq(
322 'open-ils.storage.direct.actor.workstation.search.name', $name);
323 ol_handle_result(OpenILS::Event->new('WORKSTATION_NOT_FOUND')) unless $ws;
330 # --------------------------------------------------------------------
331 # Sorts the script commands then forks a child to executes them.
332 # --------------------------------------------------------------------
335 my $session = ol_find_session();
336 ol_handle_event('OFFLINE_SESSION_ACTIVE') if $session->in_process;
337 ol_handle_event('OFFLINE_SESSION_COMPLETE') if $session->end_time;
339 my $commands = ol_collect_commands();
341 # --------------------------------------------------------------------
342 # Note that we must disconnect from opensrf before forking or the
343 # connection will be borked...
344 # --------------------------------------------------------------------
345 OpenSRF::Transport::PeerHandle->retrieve->disconnect;
346 #$session->in_process("1");
347 #$session->description("test ".CORE::time());
353 # --------------------------------------------------------------------
354 # Tell the client all is well
355 # --------------------------------------------------------------------
356 ol_handle_event('SUCCESS'); # - this exits
360 # --------------------------------------------------------------------
361 # close stdout/stderr or apache will wait on the child to finish
362 # --------------------------------------------------------------------
366 $logger->debug("offline: child $$ processing data...");
368 # --------------------------------------------------------------------
369 # The child re-connects to the opensrf network and processes
370 # the script requests
371 # --------------------------------------------------------------------
372 OpenSRF::System->bootstrap_client(config_file => $config{bootstrap});
377 #Class::DBI->autoupdate(1);
378 my $sesion = ol_find_session();
379 $session->in_process(1);
380 ol_process_commands($session, $commands);
385 $logger->error("offline: child process error $e");
390 sub ol_file_to_perl {
392 open(F, "$fname") or ol_handle_event('OFFLINE_FILE_ERROR');
395 push(@p, JSON->JSON2perl($_)) for @d;
400 # collects the commands and sorts them on timestamp+delta
401 sub ol_collect_commands {
402 my $ses = ol_find_session();
405 # cycle through every script loaded to this session
406 for my $script ($ses->scripts) {
407 my $coms = ol_file_to_perl($script->logfile);
409 # cycle through all of the commands for this script
410 for my $com (@$coms) {
411 $$com{_worksation} = $script->workstation;
412 $$com{_realtime} = $script->time_delta + $com->{timestamp};
413 push( @commands, $com );
417 # make sure thera are no blank commands
418 @commands = grep { ($_ and $_->{type}) } @commands;
421 @commands = sort { $a->{_realtime} <=> $b->{_realtime} } @commands;
423 # push user registrations to the front
424 my @regs = grep { $_->{type} eq 'register' } @commands;
425 my @others = grep { $_->{type} ne 'register' } @commands;
427 return [ @regs, @others ];
431 my (undef,undef, undef, $mday,$mon,$year) = localtime(time);
432 $mon++; $year += 1900;
433 $mday = "0$mday" unless $mday =~ /\d{2}/o;
434 $mon = "0$mon" unless $mon =~ /\d{2}/o;
435 return ($year, $mon, $mday);
439 # --------------------------------------------------------------------
440 # Moves all files from the pending directory to the archive directory
441 # and removes the pending directory
442 # --------------------------------------------------------------------
443 sub ol_archive_files {
444 my ($y, $m, $d) = ol_date();
446 my $dir = "$basedir/pending/$org/$seskey";
447 my $archdir = "$basedir/archive/$org/${y}_${m}_${d}/$seskey";
448 $logger->debug("offline: archiving files to $archdir");
450 qx/mkdir -p $archdir/;
451 qx/mv $_ $archdir/ for <$dir/*>;
456 # --------------------------------------------------------------------
457 # Appends results to the results file.
458 # --------------------------------------------------------------------
460 sub ol_append_result {
465 $obj = JSON->perl2JSON($obj);
468 open($rhandle, ">>$basedir/pending/$org/$seskey/results")
469 or ol_handle_event('OFFLINE_FILE_ERROR');
472 print $rhandle "$obj\n";
473 close($rhandle) if $last;
478 # --------------------------------------------------------------------
479 # Runs the commands and returns the list of errors
480 # --------------------------------------------------------------------
481 sub ol_process_commands {
484 my $commands = shift;
487 $session->start_time(CORE::time);
489 for my $d ( @$commands ) {
492 my $last = ($x++ == scalar(@$commands) - 1) ? 1 : 0;
493 my $res = { command => $d };
495 $res->{event} = ol_handle_checkin($d) if $t eq 'checkin';
496 $res->{event} = ol_handle_inhouse($d) if $t eq 'in_house_use';
497 $res->{event} = ol_handle_checkout($d) if $t eq 'checkout';
498 $res->{event} = ol_handle_renew($d) if $t eq 'renew';
499 $res->{event} = ol_handle_register($d) if $t eq 'register';
502 ol_append_result($res, $last);
503 $session->num_complete( $session->num_complete + 1 );
505 $logger->debug("offline: set session [".$session->key."] num_complete to ".$session->num_complete);
508 $session->end_time(CORE::time);
509 $session->in_process(0);
513 # --------------------------------------------------------------------
514 # Runs an in_house_use action
515 # --------------------------------------------------------------------
516 sub ol_handle_inhouse {
519 my $realtime = $command->{_realtime};
520 my $ws = $command->{_workstation};
521 my $barcode = $command->{barcode};
522 my $count = $command->{count} || 1;
523 my $use_time = $command->{use_time} || "";
525 $logger->activity("offline: in_house_use : requestor=". $requestor->id.", realtime=$realtime, ".
526 "workstation=$ws, barcode=$barcode, count=$count, use_time=$use_time");
528 my $ids = $U->simplereq(
530 'open-ils.circ.in_house_use.create', $authtoken,
531 { barcode => $barcode, count => $count, location => &offline_org, use_time => $use_time } );
533 return OpenILS::Event->new('SUCCESS', payload => $ids) if( ref($ids) eq 'ARRAY' );
539 # --------------------------------------------------------------------
540 # Pulls the relevant circ args from the command, fetches data where
542 # --------------------------------------------------------------------
543 sub ol_circ_args_from_command {
546 my $type = $command->{type};
547 my $realtime = $command->{_realtime};
548 my $ws = $command->{_workstation};
549 my $barcode = $command->{barcode} || "";
550 my $cotime = $command->{checkout_time} || "";
551 my $pbc = $command->{patron_barcode};
552 my $due_date = $command->{due_date} || "";
553 my $noncat = ($command->{noncat}) ? "yes" : "no"; # for logging
555 $logger->activity("offline: $type : requestor=". $requestor->id.
556 ", realtime=$realtime, workstation=$ws, checkout_time=$cotime, ".
557 "patron=$pbc, due_date=$due_date, noncat=$noncat");
560 permit_override => 1,
562 checkout_time => $cotime,
563 patron_barcode => $pbc,
564 due_date => $due_date };
566 if( $command->{noncat} ) {
568 $args->{noncat_type} = $command->{noncat_type};
569 $args->{noncat_count} = $command->{noncat_count};
577 # --------------------------------------------------------------------
578 # Performs a checkout action
579 # --------------------------------------------------------------------
580 sub ol_handle_checkout {
582 my $args = ol_circ_args_from_command($command);
583 return $U->simplereq(
584 'open-ils.circ', 'open-ils.circ.checkout', $authtoken, $args );
588 # --------------------------------------------------------------------
589 # Performs the renewal action
590 # --------------------------------------------------------------------
591 sub ol_handle_renew {
593 my $args = ol_circ_args_from_command($command);
595 return $U->simplereq(
596 'open-ils.circ', 'open-ils.circ.renew', $authtoken, $args );
600 # --------------------------------------------------------------------
601 # Runs a checkin action
602 # --------------------------------------------------------------------
603 sub ol_handle_checkin {
606 my $realtime = $command->{_realtime};
607 my $ws = $command->{_workstation};
608 my $barcode = $command->{barcode};
609 my $backdate = $command->{backdate} || "";
611 $logger->activity("offline: checkin : requestor=". $requestor->id.
612 ", realtime=$realtime, ". "workstation=$ws, barcode=$barcode, backdate=$backdate");
614 return $U->simplereq(
616 'open-ils.circ.checkin', $authtoken,
617 { barcode => $barcode, backdate => $backdate } );
622 # --------------------------------------------------------------------
623 # Registers a new patron
624 # --------------------------------------------------------------------
625 sub ol_handle_register {
628 my $barcode = $command->{user}->{card}->{barcode};
629 delete $command->{user}->{card};
631 $logger->info("offline: creating new user with barcode $barcode");
633 # now, create the user
634 my $actor = Fieldmapper::actor::user->new;
635 my $card = Fieldmapper::actor::card->new;
638 # username defaults to the barcode
639 $actor->usrname( ($actor->usrname) ? $actor->usrname : $barcode );
641 # Set up all of the virtual IDs, isnew, etc.
645 $actor->cards([$card]);
650 $card->barcode($barcode);
656 for my $resp (@{$command->{user}->{survey_responses}}) {
657 my $sr = Fieldmapper::action::survey_response->new;
658 $sr->$_( $resp->{$_} ) for keys %$resp;
662 $logger->debug("offline: created new survey response for survey ".$sr->survey);
664 delete $command->{user}->{survey_responses};
665 $actor->survey_responses(\@sresp) if @sresp;
667 # extract the billing address
668 if( my $addr = $command->{user}->{billing_address} ) {
669 $billing_address = Fieldmapper::actor::user_address->new;
670 $billing_address->$_($addr->{$_}) for keys %$addr;
671 $billing_address->isnew(1);
672 $billing_address->id(-1);
673 $billing_address->usr(-1);
674 delete $command->{user}->{billing_address};
675 $logger->debug("offline: read billing address ".$billing_address->street1);
678 # extract the mailing address
679 if( my $addr = $command->{user}->{mailing_address} ) {
680 $mailing_address = Fieldmapper::actor::user_address->new;
681 $mailing_address->$_($addr->{$_}) for keys %$addr;
682 $mailing_address->isnew(1);
683 $mailing_address->id(-2);
684 $mailing_address->usr(-1);
685 delete $command->{user}->{mailing_address};
686 $logger->debug("offline: read mailing address ".$mailing_address->street1);
689 # make sure we have values for both
690 $billing_address ||= $mailing_address;
691 $mailing_address ||= $billing_address;
693 $actor->billing_address($billing_address->id);
694 $actor->mailing_address($mailing_address->id);
695 $actor->addresses([$mailing_address]);
697 push( @{$actor->addresses}, $billing_address )
698 unless $billing_address->id eq $mailing_address->id;
700 # pull all of the rest of the data from the command blob
701 $actor->$_( $command->{user}->{$_} ) for keys %{$command->{user}};
703 $logger->debug("offline: creating user object...");
704 $actor = $U->simplereq(
706 'open-ils.actor.patron.update', $authtoken, $actor);
708 return $actor if(ref($actor) eq 'HASH'); # an event occurred
710 return OpenILS::Event->new('SUCCESS', payload => $actor);