]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
thinko ... do NOT comment out "use base"
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Storage / Publisher / action.pm
1 package OpenILS::Application::Storage::Publisher::action;
2 use base qw/OpenILS::Application::Storage::Publisher/;
3 use OpenSRF::Utils::Logger qw/:level/;
4 use OpenSRF::Utils qw/:datetime/;
5 use OpenSRF::AppSession;
6 use OpenSRF::EX qw/:try/;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Utils::PermitHold;
9 use DateTime;
10 use DateTime::Format::ISO8601;
11 use OpenILS::Utils::Penalty;
12
13 sub isTrue {
14         my $v = shift;
15         return 1 if ($v == 1);
16         return 1 if ($v =~ /^t/io);
17         return 1 if ($v =~ /^y/io);
18         return 0;
19 }
20
21 my $parser = DateTime::Format::ISO8601->new;
22 my $log = 'OpenSRF::Utils::Logger';
23
24 sub open_noncat_circs {
25         my $self = shift;
26         my $client = shift;
27         my $user = shift;
28
29         my $a = action::non_cataloged_circulation->table;
30         my $c = config::non_cataloged_type->table;
31
32         my $sql = <<"   SQL";
33                 SELECT  a.id
34                   FROM  $a a
35                         JOIN $c c ON (a.item_type = c.id)
36                   WHERE a.circ_time + c.circ_duration > current_timestamp
37                         AND a.patron = ?
38         SQL
39
40         return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
41 }
42 __PACKAGE__->register_method(
43         api_name        => 'open-ils.storage.action.open_non_cataloged_circulation.user',
44         api_level       => 1,
45         argc            => 1,
46         method          => 'open_noncat_circs',
47 );
48
49
50 sub ou_hold_requests {
51         my $self = shift;
52         my $client = shift;
53         my $ou = shift;
54
55         my $h_table = action::hold_request->table;
56         my $c_table = asset::copy->table;
57         my $o_table = actor::org_unit->table;
58
59         my $SQL = <<"   SQL";
60                 SELECT  h.id
61                   FROM  $h_table h
62                         JOIN $c_table cp ON (cp.id = h.current_copy)
63                         JOIN $o_table ou ON (ou.id = cp.circ_lib)
64                   WHERE ou.id = ?
65                         AND h.capture_time IS NULL
66                         AND h.cancel_time IS NULL
67                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
68                   ORDER BY h.request_time
69         SQL
70
71         my $sth = action::hold_request->db_Main->prepare_cached($SQL);
72         $sth->execute($ou);
73
74         $client->respond($_) for (
75                 map {
76                         $self
77                                 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
78                                 ->run($_)
79                 } map {
80                         $_->[0]
81                 } @{ $sth->fetchall_arrayref }
82         );
83         return undef;
84 }
85 __PACKAGE__->register_method(
86         api_name        => 'open-ils.storage.action.targeted_hold_request.org_unit',
87         api_level       => 1,
88         argc            => 1,
89         stream          => 1,
90         method          => 'ou_hold_requests',
91 );
92
93
94 sub overdue_circs {
95         my $grace = shift;
96     my $upper_interval = shift || '1 millennium';
97
98         my $c_t = action::circulation->table;
99
100         if ($grace && $grace =~ /^\d+$/o) {
101         $grace = " - ($grace * (fine_interval))";
102     } else {
103         $grace = '';
104     } 
105
106         my $sql = <<"   SQL";
107                 SELECT  *
108                   FROM  $c_t
109                   WHERE stop_fines IS NULL
110                         AND due_date < ( CURRENT_TIMESTAMP $grace)
111             AND fine_interval < ?::INTERVAL
112         SQL
113
114         my $sth = action::circulation->db_Main->prepare_cached($sql);
115         $sth->execute($upper_interval);
116
117         return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
118
119 }
120
121 sub complete_reshelving {
122         my $self = shift;
123         my $client = shift;
124         my $window = shift;
125
126         local $OpenILS::Application::Storage::WRITE = 1;
127
128         throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
129                 unless (interval_to_seconds( $window ));
130
131         my $setting = actor::org_unit_setting->table;
132         my $circ = action::circulation->table;
133         my $cp = asset::copy->table;
134
135         my $sql = <<"   SQL";
136                 UPDATE  $cp
137                   SET   status = 0
138                   WHERE id IN (
139             SELECT  id
140               FROM  (SELECT cp.id, MAX(circ.checkin_time)
141                       FROM  $cp cp
142                             JOIN $circ circ ON (circ.target_copy = cp.id)
143                             LEFT JOIN $setting setting
144                                 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
145                       WHERE circ.checkin_time IS NOT NULL
146                             AND cp.status = 7
147                       GROUP BY 1
148                       HAVING MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? )  AS INTERVAL)
149                     ) AS foo
150                                 UNION ALL
151             SELECT  cp.id
152                            FROM $cp cp 
153                     LEFT JOIN $setting setting
154                         ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
155                     LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
156               WHERE cp.status = 7 AND circ.id IS NULL
157                     AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? )  AS INTERVAL)
158           )
159         SQL
160
161         my $sth = action::circulation->db_Main->prepare_cached($sql);
162         $sth->execute($window, $window);
163
164         return $sth->rows;
165
166 }
167 __PACKAGE__->register_method(
168         api_name        => 'open-ils.storage.action.circulation.reshelving.complete',
169         api_level       => 1,
170         argc            => 1,
171         method          => 'complete_reshelving',
172 );
173
174 sub mark_longoverdue {
175         my $self = shift;
176         my $client = shift;
177         my $window = shift;
178
179         local $OpenILS::Application::Storage::WRITE = 1;
180
181         throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
182                 unless (interval_to_seconds( $window ));
183
184         my $setting = actor::org_unit_setting->table;
185         my $circ = action::circulation->table;
186
187         my $sql = <<"   SQL";
188                 UPDATE  $circ
189                   SET   stop_fines = 'LONGOVERDUE',
190                         stop_fines_time = now()
191                   WHERE id IN (
192                     SELECT  circ.id
193                       FROM  $circ circ
194                             LEFT JOIN $setting setting
195                                 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
196                       WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
197                             AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? )  AS INTERVAL)
198                   )
199         SQL
200
201         my $sth = action::circulation->db_Main->prepare_cached($sql);
202         $sth->execute($window);
203
204         return $sth->rows;
205
206 }
207 __PACKAGE__->register_method(
208         api_name        => 'open-ils.storage.action.circulation.long_overdue',
209         api_level       => 1,
210         argc            => 1,
211         method          => 'mark_longoverdue',
212 );
213
214 sub auto_thaw_frozen_holds {
215         my $self = shift;
216         my $client = shift;
217
218         local $OpenILS::Application::Storage::WRITE = 1;
219
220         my $holds = action::hold_request->table;
221
222         my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
223
224         my $sth = action::hold_request->db_Main->prepare_cached($sql);
225         $sth->execute();
226
227         return $sth->rows;
228
229 }
230 __PACKAGE__->register_method(
231         api_name        => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
232         api_level       => 1,
233         stream          => 0,
234         argc            => 0,
235         method          => 'auto_thaw_frozen_holds',
236 );
237
238 sub grab_overdue {
239         my $self = shift;
240         my $client = shift;
241         my $grace = shift || '';
242
243         $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
244
245         return undef;
246
247 }
248 __PACKAGE__->register_method(
249         api_name        => 'open-ils.storage.action.circulation.overdue',
250         api_level       => 1,
251         stream          => 1,
252         method          => 'grab_overdue',
253 );
254
255 sub nearest_hold {
256         my $self = shift;
257         my $client = shift;
258         my $here = shift;
259         my $cp = shift;
260         my $limit = int(shift()) || 10;
261         my $age = shift() || '0 seconds';
262
263         my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
264                 SELECT  h.id
265                   FROM  action.hold_request h
266                         JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
267                         JOIN action.hold_copy_map hm ON (hm.hold = h.id)
268                   WHERE hm.target_copy = ?
269                         AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
270                         AND h.capture_time IS NULL
271                         AND h.cancel_time IS NULL
272                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
273             AND h.frozen IS FALSE
274                 ORDER BY
275                         p.prox,
276             CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END,
277                         h.selection_depth DESC,
278                         h.request_time
279                 LIMIT $limit
280         SQL
281         
282         $client->respond( $_ ) for ( @$ids );
283         return undef;
284 }
285 __PACKAGE__->register_method(
286         api_name        => 'open-ils.storage.action.hold_request.nearest_hold',
287         api_level       => 1,
288         stream          => 1,
289         method          => 'nearest_hold',
290 );
291
292 sub next_resp_group_id {
293         my $self = shift;
294         my $client = shift;
295
296         # XXX This is not replication safe!!!
297
298         my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
299                 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
300         SQL
301         return $id;
302 }
303 __PACKAGE__->register_method(
304         api_name        => 'open-ils.storage.action.survey_response.next_group_id',
305         api_level       => 1,
306         method          => 'next_resp_group_id',
307 );
308
309 sub patron_circ_summary {
310         my $self = shift;
311         my $client = shift;
312         my $id = ''.shift();
313
314         return undef unless ($id);
315         my $c_table = action::circulation->table;
316         my $b_table = money::billing->table;
317
318         $log->debug("Retrieving patron summary for id $id", DEBUG);
319
320         my $select = <<"        SQL";
321                 SELECT  COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
322                   FROM  $c_table c
323                         LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
324                   WHERE c.usr = ?
325                         AND c.xact_finish IS NULL
326                         AND (
327                                 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
328                                 OR c.stop_fines IS NULL
329                         )
330         SQL
331
332         return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
333 }
334 __PACKAGE__->register_method(
335         api_name        => 'open-ils.storage.action.circulation.patron_summary',
336         api_level       => 1,
337         method          => 'patron_circ_summary',
338 );
339
340 #XXX Fix stored proc calls
341 sub find_local_surveys {
342         my $self = shift;
343         my $client = shift;
344         my $ou = ''.shift();
345
346         return undef unless ($ou);
347         my $s_table = action::survey->table;
348
349         my $select = <<"        SQL";
350                 SELECT  s.*
351                   FROM  $s_table s
352                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
353                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
354         SQL
355
356         my $sth = action::survey->db_Main->prepare_cached($select);
357         $sth->execute($ou);
358
359         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
360
361         return undef;
362 }
363 __PACKAGE__->register_method(
364         api_name        => 'open-ils.storage.action.survey.all',
365         api_level       => 1,
366         stream          => 1,
367         method          => 'find_local_surveys',
368 );
369
370 #XXX Fix stored proc calls
371 sub find_opac_surveys {
372         my $self = shift;
373         my $client = shift;
374         my $ou = ''.shift();
375
376         return undef unless ($ou);
377         my $s_table = action::survey->table;
378
379         my $select = <<"        SQL";
380                 SELECT  s.*
381                   FROM  $s_table s
382                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
383                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
384                         AND s.opac IS TRUE;
385         SQL
386
387         my $sth = action::survey->db_Main->prepare_cached($select);
388         $sth->execute($ou);
389
390         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
391
392         return undef;
393 }
394 __PACKAGE__->register_method(
395         api_name        => 'open-ils.storage.action.survey.opac',
396         api_level       => 1,
397         stream          => 1,
398         method          => 'find_opac_surveys',
399 );
400
401 sub hold_pull_list {
402         my $self = shift;
403         my $client = shift;
404         my $ou = shift;
405         my $limit = shift || 10;
406         my $offset = shift || 0;
407
408         return undef unless ($ou);
409         my $h_table = action::hold_request->table;
410         my $a_table = asset::copy->table;
411
412         my $idlist = 1 if ($self->api_name =~/id_list/o);
413
414         my $status_filter = '';
415         $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
416
417         my $select = <<"        SQL";
418                 SELECT  h.*
419                   FROM  $h_table h
420                         JOIN $a_table a ON (h.current_copy = a.id)
421                   WHERE a.circ_lib = ?
422                         AND h.capture_time IS NULL
423                         AND h.cancel_time IS NULL
424                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
425                         $status_filter
426                   ORDER BY h.request_time ASC
427                   LIMIT $limit
428                   OFFSET $offset
429         SQL
430
431         my $sth = action::survey->db_Main->prepare_cached($select);
432         $sth->execute($ou);
433
434         if ($idlist) {
435                 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
436         } else {
437                 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
438         }
439
440         return undef;
441 }
442 __PACKAGE__->register_method(
443         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
444         api_level       => 1,
445         stream          => 1,
446         signature       => [
447                 "Returns the hold ids for a specific library's pull list.",
448                 [ [org_unit => "The library's org id", "number"],
449                   [limit => 'An optional page size, defaults to 10', 'number'],
450                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
451                 ],
452                 ['A list of holds for the stated library to pull for', 'array']
453         ],
454         method          => 'hold_pull_list',
455 );
456 __PACKAGE__->register_method(
457         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
458         api_level       => 1,
459         stream          => 1,
460         signature       => [
461                 "Returns the holds for a specific library's pull list.",
462                 [ [org_unit => "The library's org id", "number"],
463                   [limit => 'An optional page size, defaults to 10', 'number'],
464                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
465                 ],
466                 ['A list of holds for the stated library to pull for', 'array']
467         ],
468         method          => 'hold_pull_list',
469 );
470 __PACKAGE__->register_method(
471         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
472         api_level       => 1,
473         stream          => 1,
474         signature       => [
475                 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
476                 [ [org_unit => "The library's org id", "number"],
477                   [limit => 'An optional page size, defaults to 10', 'number'],
478                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
479                 ],
480                 ['A list of holds for the stated library to pull for', 'array']
481         ],
482         method          => 'hold_pull_list',
483 );
484 __PACKAGE__->register_method(
485         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
486         api_level       => 1,
487         stream          => 1,
488         signature       => [
489                 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
490                 [ [org_unit => "The library's org id", "number"],
491                   [limit => 'An optional page size, defaults to 10', 'number'],
492                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
493                 ],
494                 ['A list of holds for the stated library to pull for', 'array']
495         ],
496         method          => 'hold_pull_list',
497 );
498
499 sub find_optional_surveys {
500         my $self = shift;
501         my $client = shift;
502         my $ou = ''.shift();
503
504         return undef unless ($ou);
505         my $s_table = action::survey->table;
506
507         my $select = <<"        SQL";
508                 SELECT  s.*
509                   FROM  $s_table s
510                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
511                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
512                         AND s.required IS FALSE;
513         SQL
514
515         my $sth = action::survey->db_Main->prepare_cached($select);
516         $sth->execute($ou);
517
518         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
519
520         return undef;
521 }
522 __PACKAGE__->register_method(
523         api_name        => 'open-ils.storage.action.survey.optional',
524         api_level       => 1,
525         stream          => 1,
526         method          => 'find_optional_surveys',
527 );
528
529 sub find_required_surveys {
530         my $self = shift;
531         my $client = shift;
532         my $ou = ''.shift();
533
534         return undef unless ($ou);
535         my $s_table = action::survey->table;
536
537         my $select = <<"        SQL";
538                 SELECT  s.*
539                   FROM  $s_table s
540                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
541                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
542                         AND s.required IS TRUE;
543         SQL
544
545         my $sth = action::survey->db_Main->prepare_cached($select);
546         $sth->execute($ou);
547
548         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
549
550         return undef;
551 }
552 __PACKAGE__->register_method(
553         api_name        => 'open-ils.storage.action.survey.required',
554         api_level       => 1,
555         stream          => 1,
556         method          => 'find_required_surveys',
557 );
558
559 sub find_usr_summary_surveys {
560         my $self = shift;
561         my $client = shift;
562         my $ou = ''.shift();
563
564         return undef unless ($ou);
565         my $s_table = action::survey->table;
566
567         my $select = <<"        SQL";
568                 SELECT  s.*
569                   FROM  $s_table s
570                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
571                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
572                         AND s.usr_summary IS TRUE;
573         SQL
574
575         my $sth = action::survey->db_Main->prepare_cached($select);
576         $sth->execute($ou);
577
578         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
579
580         return undef;
581 }
582 __PACKAGE__->register_method(
583         api_name        => 'open-ils.storage.action.survey.usr_summary',
584         api_level       => 1,
585         stream          => 1,
586         method          => 'find_usr_summary_surveys',
587 );
588
589
590 sub generate_fines {
591         my $self = shift;
592         my $client = shift;
593         my $grace = shift;
594         my $circ = shift;
595         my $overbill = shift;
596
597         local $OpenILS::Application::Storage::WRITE = 1;
598
599         my @circs;
600         if ($circ) {
601                 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
602         } else {
603                 push @circs, overdue_circs($grace);
604         }
605
606         my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
607
608         my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
609         for my $c (@circs) {
610         
611                 try {
612                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
613                                 $log->debug("Cleaning up after previous transaction\n");
614                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
615                         }
616                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
617                         $log->info("Processing circ ".$c->id."...\n");
618
619
620                         my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
621         
622                         my $due = $due_dt->epoch;
623                         my $now = time;
624
625                         my $fine_interval = $c->fine_interval;
626             $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
627                         $fine_interval = interval_to_seconds( $fine_interval );
628         
629                         if ( $fine_interval >= interval_to_seconds('1d') ) {    
630                                 my $tz_offset_s = 0;
631                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
632                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
633                                 }
634         
635                                 $due -= ($due % $fine_interval) + $tz_offset_s;
636                                 $now -= ($now % $fine_interval) + $tz_offset_s;
637                         }
638         
639                         $client->respond(
640                                 "ARG! Overdue circulation ".$c->id.
641                                 " for item ".$c->target_copy.
642                                 " (user ".$c->usr.").\n".
643                                 "\tItem was due on or before: ".localtime($due)."\n");
644         
645                         my @fines = money::billing->search_where(
646                                 { xact => $c->id,
647                                   btype => 1,
648                                   billing_ts => { '>' => $c->due_date } },
649                                 { order_by => 'billing_ts DESC'}
650                         );
651
652                         my $f_idx = 0;
653                         my $fine = $fines[$f_idx] if (@fines);
654                         if ($overbill) {
655                                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
656                         }
657
658                         my $current_fine_total = 0;
659                         $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
660         
661                         my $last_fine;
662                         if ($fine) {
663                                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
664                                 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
665                         } else {
666                                 $log->info( "Potential first billing for circ ".$c->id );
667                                 $last_fine = $due;
668
669                                 if (0) {
670                                         if (my $h = $hoo{$c->circ_lib}) { 
671
672                                                 $log->info( "Circ lib has an hours-of-operation entry" );
673                                                 # find the day after the due date...
674                                                 $due_dt = $due_dt->add( days => 1 );
675
676                                                 # get the day of the week for that day...
677                                                 my $dow = $due_dt->day_of_week_0;
678                                                 my $dow_open = "dow_${dow}_open";
679                                                 my $dow_close = "dow_${dow}_close";
680
681                                                 my $count = 0;
682                                                 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
683                                                         # if the circ lib is closed, add a day to the grace period...
684
685                                                         $grace++;
686                                                         $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
687                                                         $log->info( "Day of week $dow open $dow_open, close $dow_close" );
688
689                                                         $due_dt = $due_dt->add( days => 1 );
690                                                         $dow = $due_dt->day_of_week_0;
691                                                         $dow_open = "dow_${dow}_open";
692                                                         $dow_close = "dow_${dow}_close";
693
694                                                         $count++;
695
696                                                         # and check for up to a week
697                                                         last if ($count > 6);
698                                                 }
699                                         }
700                                 }
701                         }
702
703
704                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
705                         if ($pending_fine_count < 1 + $grace) {
706                                 $client->respond( "\tNo fines to create.  " );
707                                 if ($grace && $now < $due + $fine_interval * $grace) {
708                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
709                                         $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
710                                 } else {
711                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
712                                 }
713                                 next;
714                         }
715         
716                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
717
718                         my $recuring_fine = int($c->recuring_fine * 100);
719                         my $max_fine = int($c->max_fine * 100);
720
721                         my ($latest_billing_ts, $latest_amount) = ('',0);
722                         for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
723         
724                                 if ($current_fine_total >= $max_fine) {
725                                         $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
726                                         $client->respond(
727                                                 "\tMaximum fine level of ".$c->max_fine.
728                                                 " reached for this circulation.\n".
729                                                 "\tNo more fines will be generated.\n" );
730                                         last;
731                                 }
732                                 
733                                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
734
735                                 my $dow = $billing_ts->day_of_week_0();
736                                 my $dow_open = "dow_${dow}_open";
737                                 my $dow_close = "dow_${dow}_close";
738
739                                 if (my $h = $hoo{$c->circ_lib}) {
740                                         next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
741                                 }
742
743                                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
744                                 my @cl = actor::org_unit::closed_date->search_where(
745                                                 { close_start   => { '<=' => $timestamptz },
746                                                   close_end     => { '>=' => $timestamptz },
747                                                   org_unit      => $c->circ_lib }
748                                 );
749                                 next if (@cl);
750         
751                                 $current_fine_total += $recuring_fine;
752                                 $latest_amount += $recuring_fine;
753                                 $latest_billing_ts = $timestamptz;
754
755                                 money::billing->create(
756                                         { xact          => ''.$c->id,
757                                           note          => "System Generated Overdue Fine",
758                                           billing_type  => "Overdue materials",
759                                           btype         => 1,
760                                           amount        => sprintf('%0.2f', $recuring_fine/100),
761                                           billing_ts    => $timestamptz,
762                                         }
763                                 );
764
765                         }
766
767                         $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
768                                 if ($latest_billing_ts and $latest_amount);
769
770                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
771
772                         if(1) { 
773
774                 # Caluclate penalties inline
775                                 OpenILS::Utils::Penalty->calculate_penalties(
776                                         undef, $c->usr->to_fieldmapper->id.'', $c->circ_lib->to_fieldmapper->id.'');
777
778                         } else {
779
780                 # Calculate penalties with an aysnc call to the penalty server.  This approach
781                 # may lead to duplicate penalties since multiple penalty processes for a
782                 # given user may be running at the same time. Leave this here for reference 
783                 # in case we later find that asyc calls are needed in some environments.
784                                 $penalty->request(
785                                     'open-ils.penalty.patron_penalty.calculate',
786                                     { patronid  => ''.$c->usr,
787                                     context_org => ''.$c->circ_lib,
788                                     update      => 1,
789                                     background  => 1,
790                                     }
791                             )->gather(1);
792                         }
793
794                 } catch Error with {
795                         my $e = shift;
796                         $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
797                         $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
798                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
799                         throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
800                 };
801         }
802 }
803 __PACKAGE__->register_method(
804         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
805         api_level       => 1,
806         stream          => 1,
807         method          => 'generate_fines',
808 );
809
810
811
812 sub new_hold_copy_targeter {
813         my $self = shift;
814         my $client = shift;
815         my $check_expire = shift;
816         my $one_hold = shift;
817
818         local $OpenILS::Application::Storage::WRITE = 1;
819
820         $self->{target_weight} = {};
821
822         my $holds;
823
824         try {
825                 if ($one_hold) {
826                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
827                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
828                 } elsif ( $check_expire ) {
829
830                         # what's the retarget time threashold?
831                         my $time = time;
832                         $check_expire ||= '12h';
833                         $check_expire = interval_to_seconds( $check_expire );
834
835                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
836                         $year += 1900;
837                         $mon += 1;
838                         my $expire_threshold = sprintf(
839                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
840                                 $year, $mon, $mday, $hour, $min, $sec
841                         );
842
843                         # find all the holds holds needing retargeting
844                         $holds = [ action::hold_request->search_where(
845                                                         { capture_time => undef,
846                                                           fulfillment_time => undef,
847                                                           cancel_time => undef,
848                                                           frozen => 'f',
849                                                           prev_check_time => { '<=' => $expire_threshold },
850                                                         },
851                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
852
853                         # find all the holds holds needing first time targeting
854                         push @$holds, action::hold_request->search(
855                                                         capture_time => undef,
856                                                         fulfillment_time => undef,
857                                                         prev_check_time => undef,
858                                                         frozen => 'f',
859                                                         cancel_time => undef,
860                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
861                 } else {
862
863                         # find all the holds holds needing first time targeting ONLY
864                         $holds = [ action::hold_request->search(
865                                                         capture_time => undef,
866                                                         fulfillment_time => undef,
867                                                         prev_check_time => undef,
868                                                         cancel_time => undef,
869                                                         frozen => 'f',
870                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
871                 }
872         } catch Error with {
873                 my $e = shift;
874                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
875         };
876
877         my @closed = actor::org_unit::closed_date->search_where(
878                 { close_start => { '<=', 'now' },
879                   close_end => { '>=', 'now' } }
880         );
881
882     if ($check_expire) {
883
884         # $check_expire, if it exists, was already converted to seconds
885         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
886             $year += 1900;
887         $mon += 1;
888
889             my $next_check_time = sprintf(
890                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
891                 $year, $mon, $mday, $hour, $min, $sec
892         );
893
894
895             my @closed_at_next = actor::org_unit::closed_date->search_where(
896                     { close_start => { '<=', $next_check_time },
897                   close_end => { '>=', $next_check_time } }
898             );
899
900         my @new_closed;
901         for my $c_at_n (@closed_at_next) {
902             if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
903                 push @new_closed, $c_at_n;
904             }
905         }
906         @closed = @new_closed;
907     }
908
909         my @successes;
910         my $actor = OpenSRF::AppSession->create('open-ils.actor');
911
912         for my $hold (@$holds) {
913                 try {
914                         #start a transaction if needed
915                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
916                                 $log->debug("Cleaning up after previous transaction\n");
917                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
918                         }
919                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
920                         $log->info("Processing hold ".$hold->id."...\n");
921
922                         #first, re-fetch the hold, to make sure it's not captured already
923                         $hold->remove_from_object_index();
924                         $hold = action::hold_request->retrieve( $hold->id );
925
926                         die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
927
928                         # remove old auto-targeting maps
929                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
930                         $_->delete for (@oldmaps);
931
932                         if ($hold->expire_time) {
933                                 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
934                                 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
935
936                                         # cancel cause = un-targeted expiration
937                                         $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
938                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
939
940                                         # tell A/T the hold was cancelled
941                                         my $fm_hold = $hold->to_fieldmapper;
942                                         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
943                                         $ses->request('open-ils.trigger.event.autocreate', 
944                                                 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
945
946                                         die "OK\n";
947                                 }
948                         }
949
950                         my $all_copies = [];
951
952                         # find filters for MR holds
953                         my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
954
955                         # find all the potential copies
956                         if ($hold->hold_type eq 'M') {
957                                 for my $r ( map
958                                                 {$_->record}
959                                                 metabib::record_descriptor
960                                                         ->search(
961                                                                 record => [
962                                                                         map {
963                                                                                 isTrue($_->deleted) ?  () : ($_->id)
964                                                                         } metabib::metarecord->retrieve($hold->target)->source_records
965                                                                 ],
966                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
967                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
968                                                                 ( $lang    ? (item_lang => $lang)                : () ),
969                                                         )
970                                 ) {
971                                         my ($rtree) = $self
972                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
973                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
974
975                                         for my $cn ( @{ $rtree->call_numbers } ) {
976                                                 push @$all_copies,
977                                                         asset::copy->search_where(
978                                                                 { id => [map {$_->id} @{ $cn->copies }],
979                                                                   deleted => 'f' }
980                                                         ) if ($cn && @{ $cn->copies });
981                                         }
982                                 }
983                         } elsif ($hold->hold_type eq 'T') {
984                                 my ($rtree) = $self
985                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
986                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
987
988                                 unless ($rtree) {
989                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
990                                         die "OK\n";
991                                 }
992
993                                 for my $cn ( @{ $rtree->call_numbers } ) {
994                                         push @$all_copies,
995                                                 asset::copy->search_where(
996                                                         { id => [map {$_->id} @{ $cn->copies }],
997                                                           deleted => 'f' }
998                                                 ) if ($cn && @{ $cn->copies });
999                                 }
1000                         } elsif ($hold->hold_type eq 'V') {
1001                                 my ($vtree) = $self
1002                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1003                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1004
1005                                 push @$all_copies,
1006                                         asset::copy->search_where(
1007                                                 { id => [map {$_->id} @{ $vtree->copies }],
1008                                                   deleted => 'f' }
1009                                         ) if ($vtree && @{ $vtree->copies });
1010                                         
1011                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1012                                 my $_cp = asset::copy->retrieve($hold->target);
1013                                 push @$all_copies, $_cp if $_cp;
1014                         }
1015
1016                         # trim unholdables
1017                         @$all_copies = grep {   isTrue($_->status->holdable) && 
1018                                                 isTrue($_->location->holdable) && 
1019                                                 isTrue($_->holdable) &&
1020                                                 !isTrue($_->deleted)
1021                                         } @$all_copies;
1022
1023                         # let 'em know we're still working
1024                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1025                         
1026                         # if we have no copies ...
1027                         if (!ref $all_copies || !@$all_copies) {
1028                                 $log->info("\tNo copies available for targeting at all!\n");
1029                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1030
1031                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1032                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1033                                 die "OK\n";
1034                         }
1035
1036                         my $copy_count = @$all_copies;
1037
1038                         # map the potentials, so that we can pick up checkins
1039                         # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1040                         # XXX the potentials list.  If this is the cased, hold_copy_map creation will move down further.
1041                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1042                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1043
1044                         #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1045
1046                         my @good_copies;
1047                         for my $c (@$all_copies) {
1048                                 # current target
1049                                 next if ($c->id eq $hold->current_copy);
1050
1051                                 # circ lib is closed
1052                                 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1053
1054                                 # target of another hold
1055                                 next if (action::hold_request
1056                                                 ->search_where(
1057                                                         { current_copy => $c->id,
1058                                                           fulfillment_time => undef,
1059                                                           cancel_time => undef,
1060                                                         }
1061                                                 )
1062                                 );
1063
1064                                 # we passed all three, keep it
1065                                 push @good_copies, $c if ($c);
1066                                 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1067                         }
1068
1069                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1070
1071                         my $old_best = $hold->current_copy;
1072                         $hold->update({ current_copy => undef }) if ($old_best);
1073         
1074                         if (!scalar(@good_copies)) {
1075                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1076                                 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1077                                         # the old copy is still available
1078                                         $log->debug("\tPushing current_copy back onto the targeting list");
1079                                         push @good_copies, $old_best;
1080                                 } else {
1081                                         # oops, old copy is not available
1082                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1083                                         $hold->update( { prev_check_time => 'today' } );
1084                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1085                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1086                                         die "OK\n";
1087                                 }
1088                         }
1089
1090                         my $prox_list = [];
1091                         $$prox_list[0] =
1092                         [
1093                                 grep {
1094                                         $_->circ_lib == $hold->pickup_lib
1095                                 } @good_copies
1096                         ];
1097
1098                         $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1099                         # $all_copies is now a list of copies not at the pickup library
1100
1101                         my $best = choose_nearest_copy($hold, $prox_list);
1102                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1103
1104                         if (!$best) {
1105                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1106
1107                                 my $max_loops = $actor->request(
1108                                         'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib => 'circ.holds.max_org_unit_target_loops'
1109                                 )->gather(1);
1110
1111                                 if (defined($max_loops)) {
1112                                         my %circ_lib_map =  map { $_->circ_lib => 1 } @$all_copies;
1113                                         my $circ_lib_list = [keys %circ_lib_map];
1114         
1115                                         my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1116         
1117                                         # Grab the "biggest" loop for this hold so far
1118                                         my $current_loop = $cstore->request(
1119                                                 'open-ils.cstore.json_query',
1120                                                 { distinct => 1,
1121                                                   select => { aufhmxl => ['max'] },
1122                                                   from => 'aufhmxl',
1123                                                   where => { hold => $hold->id}
1124                                                 }
1125                                         )->gather(1);
1126         
1127                                         $current_loop = $current_loop->{max} if ($current_loop);
1128                                         $current_loop ||= 1;
1129         
1130                                         my $exclude_list = $cstore->request(
1131                                                 'open-ils.cstore.json_query.atomic',
1132                                                 { distinct => 1,
1133                                                   select => { aufhol => [circ_lib] },
1134                                                   from => 'aufhol',
1135                                                   where => { hold => $hold->id}
1136                                                 }
1137                                         )->gather(1);
1138         
1139                                         my @keepers;
1140                                         if ($exclude_list && @$exclude_list) {
1141                                                 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1142                                                 # check to see if we've used up every library in the potentials list
1143                                                 for my $l ( @$circ_lib_list ) {
1144                                                         my $keep = 1;
1145                                                         for my $ex ( @$exclude_list ) {
1146                                                                 if ($ex eq $l) {
1147                                                                         $keep = 0;
1148                                                                         last;
1149                                                                 }
1150                                                         }
1151                                                         push(@keepers, $l) if ($keep);
1152                                                 }
1153                                         } else {
1154                                                 @keepers = @$circ_lib_list;
1155                                         }
1156         
1157                                         $current_loop++ if (!@keepers);
1158         
1159                                         if ($max_loops && $max_loops <= $current_loop) {
1160                                                 # We haven't exceeded max_loops yet
1161                                                 my @keeper_copies;
1162                                                 for my $cp ( @$all_copies ) {
1163                                                         push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1164                                                 }
1165                                         } else {
1166                                                 # We have, and should remove potentials and cancel the hold
1167                                                 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1168                                                 $_->delete for (@oldmaps);
1169
1170                                                 # cancel cause = un-targeted expiration
1171                                                 $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1172                                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1173
1174                                                 # tell A/T the hold was cancelled
1175                                                 my $fm_hold = $hold->to_fieldmapper;
1176                                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1177                                                 $ses->request('open-ils.trigger.event.autocreate', 
1178                                                         'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1179
1180                                                 die "OK\n";
1181                                         }
1182                                 }
1183
1184                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1185
1186                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1187
1188                                 $best = choose_nearest_copy($hold, $prox_list);
1189                         }
1190
1191                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1192                         if ($old_best) {
1193                                 # hold wasn't fulfilled, record the fact
1194                         
1195                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1196                                 action::unfulfilled_hold_list->create(
1197                                                 { hold => ''.$hold->id,
1198                                                   current_copy => ''.$old_best->id,
1199                                                   circ_lib => ''.$old_best->circ_lib,
1200                                                 });
1201                         }
1202
1203                         if ($best) {
1204                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1205                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1206                         } elsif (
1207                                 $old_best &&
1208                                 action::hold_request
1209                                         ->search_where(
1210                                                 { current_copy => $old_best->id,
1211                                                   fulfillment_time => undef,
1212                                                   cancel_time => undef,
1213                                                 }       
1214                                         )
1215                         ) {     
1216                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1217                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1218                         } else {
1219                                 $hold->update( { prev_check_time => 'now' } );
1220                                 $log->info( "\tThere were no targetable copies for the hold" );
1221                         }
1222
1223                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1224                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1225
1226                         push @successes,
1227                                 { hold => $hold->id,
1228                                   old_target => ($old_best ? $old_best->id : undef),
1229                                   eligible_copies => $copy_count,
1230                                   target => ($best ? $best->id : undef) };
1231
1232                 } otherwise {
1233                         my $e = shift;
1234                         if ($e !~ /^OK/o) {
1235                                 $log->error("Processing of hold failed:  $e");
1236                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1237                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1238                         }
1239                 };
1240         }
1241
1242         return \@successes;
1243 }
1244 __PACKAGE__->register_method(
1245         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1246         api_level       => 1,
1247         method          => 'new_hold_copy_targeter',
1248 );
1249
1250 my $locations;
1251 my $statuses;
1252 my %cache = (titles => {}, cns => {});
1253 sub hold_copy_targeter {
1254         my $self = shift;
1255         my $client = shift;
1256         my $check_expire = shift;
1257         my $one_hold = shift;
1258
1259         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1260         $self->{user_filter}->connect;
1261         $self->{client} = $client;
1262
1263         my $time = time;
1264         $check_expire ||= '12h';
1265         $check_expire = interval_to_seconds( $check_expire );
1266
1267         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1268         $year += 1900;
1269         $mon += 1;
1270         my $expire_threshold = sprintf(
1271                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1272                 $year, $mon, $mday, $hour, $min, $sec
1273         );
1274
1275
1276         $statuses ||= [ config::copy_status->search(holdable => 't') ];
1277
1278         $locations ||= [ asset::copy_location->search(holdable => 't') ];
1279
1280         my $holds;
1281
1282         %cache = (titles => {}, cns => {});
1283
1284         try {
1285                 if ($one_hold) {
1286                         $holds = [ action::hold_request->search(id => $one_hold) ];
1287                 } else {
1288                         $holds = [ action::hold_request->search_where(
1289                                                         { capture_time => undef,
1290                                                           prev_check_time => { '<=' => $expire_threshold },
1291                                                         },
1292                                                         { order_by => 'request_time,prev_check_time' } ) ];
1293                         push @$holds, action::hold_request->search_where(
1294                                                         { capture_time => undef,
1295                                                           prev_check_time => undef,
1296                                                         },
1297                                                         { order_by => 'request_time' } );
1298                 }
1299         } catch Error with {
1300                 my $e = shift;
1301                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1302         };
1303
1304         for my $hold (@$holds) {
1305                 try {
1306                         #action::hold_request->db_Main->begin_work;
1307                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1308                                 $client->respond("Cleaning up after previous transaction\n");
1309                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1310                         }
1311                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1312                         $client->respond("Processing hold ".$hold->id."...\n");
1313
1314                         my $copies;
1315
1316                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1317                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1318
1319                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1320                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1321                         
1322                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1323                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1324                         
1325                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1326
1327                         unless (ref $copies || !@$copies) {
1328                                 $client->respond("\tNo copies available for targeting at all!\n");
1329                         }
1330
1331                         my @good_copies;
1332                         for my $c (@$copies) {
1333                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1334                                 push @good_copies, $c if ($c);
1335                         }
1336
1337                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1338
1339                         my $old_best = $hold->current_copy;
1340                         $hold->update({ current_copy => undef });
1341         
1342                         if (!scalar(@good_copies)) {
1343                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1344                                 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1345                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
1346                                         push @good_copies, asset::copy->retrieve( $old_best );
1347                                 } else {
1348                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1349                                         next;
1350                                 }
1351                         }
1352
1353                         my $prox_list;
1354                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1355                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1356
1357                         my $best = choose_nearest_copy($hold, $prox_list);
1358
1359                         if (!$best) {
1360                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1361                                 $best = choose_nearest_copy($hold, $prox_list);
1362                         }
1363
1364                         if ($old_best) {
1365                                 # hold wasn't fulfilled, record the fact
1366                         
1367                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1368                                 action::unfulfilled_hold_list->create(
1369                                                 { hold => ''.$hold->id,
1370                                                   current_copy => ''.$old_best->id,
1371                                                   circ_lib => ''.$old_best->circ_lib,
1372                                                 });
1373                         }
1374
1375                         if ($best) {
1376                                 $hold->update( { current_copy => ''.$best->id } );
1377                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1378                         }
1379
1380                         $hold->update( { prev_check_time => 'now' } );
1381                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1382
1383                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1384                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1385
1386                         #action::hold_request->dbi_commit;
1387
1388                 } otherwise {
1389                         my $e = shift;
1390                         $log->error("Processing of hold failed:  $e");
1391                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1392                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1393                         #action::hold_request->dbi_rollback;
1394                 };
1395         }
1396
1397         $self->{user_filter}->disconnect;
1398         $self->{user_filter}->finish;
1399         delete $$self{user_filter};
1400         return undef;
1401 }
1402 #__PACKAGE__->register_method(
1403 #       api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1404 #       api_level       => 0,
1405 #       stream          => 1,
1406 #       method          => 'hold_copy_targeter',
1407 #);
1408
1409
1410 sub copy_hold_capture {
1411         my $self = shift;
1412         my $hold = shift;
1413         my $cps = shift;
1414
1415         if (!defined($cps)) {
1416                 try {
1417                         $cps = [ asset::copy->search( id => $hold->target ) ];
1418                 } catch Error with {
1419                         my $e = shift;
1420                         die "Could not retrieve initial volume list:\n\n$e\n";
1421                 };
1422         }
1423
1424         my @copies = grep { $_->holdable } @$cps;
1425
1426         for (my $i = 0; $i < @$cps; $i++) {
1427                 next unless $$cps[$i];
1428                 
1429                 my $cn = $cache{cns}{$copies[$i]->call_number};
1430                 my $rec = $cache{titles}{$cn->record};
1431                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1432                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1433                 $copies[$i] = undef if (
1434                         !$copies[$i] ||
1435                         !$self->{user_filter}->request(
1436                                 'open-ils.circ.permit_hold',
1437                                 $hold->to_fieldmapper, do {
1438                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1439                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1440                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1441                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1442                                         $cp_fm;
1443                                 },
1444                                 { title => $rec->to_fieldmapper,
1445                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1446                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1447                                 })->gather(1)
1448                 );
1449                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1450         }
1451
1452         @copies = grep { $_ } @copies;
1453
1454         my $count = @copies;
1455
1456         return unless ($count);
1457         
1458         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1459         
1460         my @maps;
1461         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1462         for my $c (@copies) {
1463                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1464         }
1465         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1466
1467         return \@copies;
1468 }
1469
1470
1471 sub choose_nearest_copy {
1472         my $hold = shift;
1473         my $prox_list = shift;
1474
1475         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1476                 next unless (ref $$prox_list[$p]);
1477
1478                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1479                 next unless (@capturable);
1480
1481                 my $rand = int(rand(scalar(@capturable)));
1482                 while (my ($c) = splice(@capturable,$rand)) {
1483                         return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1484                                 { title => $c->call_number->record->to_fieldmapper,
1485                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1486                                   patron => $hold->usr->to_fieldmapper,
1487                                   copy => $c->to_fieldmapper,
1488                                   requestor => $hold->requestor->to_fieldmapper,
1489                                   request_lib => $hold->request_lib->to_fieldmapper,
1490                                    pickup_lib => $hold->pickup_lib->id,
1491                                 }
1492                         ));
1493
1494                         last unless(@capturable);
1495                         $rand = int(rand(scalar(@capturable)));
1496                 }
1497         }
1498 }
1499
1500 sub create_prox_list {
1501         my $self = shift;
1502         my $lib = shift;
1503         my $copies = shift;
1504
1505         my $actor = OpenSRF::AppSession->create('open-ils.actor');
1506
1507         my @prox_list;
1508         for my $cp (@$copies) {
1509                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1510                 next unless (defined($prox));
1511
1512                 # Fetch the weighting value for hold targeting, defaulting to 1
1513                 $self->{target_weight} ||= $actor->request(
1514                         'open-ils.actor.ou_setting.ancestor_default' => $lib => 'circ.holds.org_unit_target_weight'
1515                 )->gather(1) || 1;
1516
1517                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1518                 for my $w ( 1 .. $self->{target_weight} ) {
1519                         push @{$prox_list[$prox]}, $cp;
1520                 }
1521         }
1522         return \@prox_list;
1523 }
1524
1525 sub volume_hold_capture {
1526         my $self = shift;
1527         my $hold = shift;
1528         my $vols = shift;
1529
1530         if (!defined($vols)) {
1531                 try {
1532                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1533                         $cache{cns}{$_->id} = $_ for (@$vols);
1534                 } catch Error with {
1535                         my $e = shift;
1536                         die "Could not retrieve initial volume list:\n\n$e\n";
1537                 };
1538         }
1539
1540         my @v_ids = map { $_->id } @$vols;
1541
1542         my $cp_list;
1543         try {
1544                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1545         
1546         } catch Error with {
1547                 my $e = shift;
1548                 warn "Could not retrieve copy list:\n\n$e\n";
1549         };
1550
1551         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1552 }
1553
1554 sub title_hold_capture {
1555         my $self = shift;
1556         my $hold = shift;
1557         my $titles = shift;
1558
1559         if (!defined($titles)) {
1560                 try {
1561                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1562                         $cache{titles}{$_->id} = $_ for (@$titles);
1563                 } catch Error with {
1564                         my $e = shift;
1565                         die "Could not retrieve initial title list:\n\n$e\n";
1566                 };
1567         }
1568
1569         my @t_ids = map { $_->id } @$titles;
1570         my $cn_list;
1571         try {
1572                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1573         
1574         } catch Error with {
1575                 my $e = shift;
1576                 warn "Could not retrieve volume list:\n\n$e\n";
1577         };
1578
1579         $cache{cns}{$_->id} = $_ for (@$cn_list);
1580
1581         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1582 }
1583
1584 sub metarecord_hold_capture {
1585         my $self = shift;
1586         my $hold = shift;
1587
1588         my $titles;
1589         try {
1590                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1591         
1592         } catch Error with {
1593                 my $e = shift;
1594                 die "Could not retrieve initial title list:\n\n$e\n";
1595         };
1596
1597         try {
1598                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1599
1600                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1601         
1602         } catch Error with {
1603                 my $e = shift;
1604                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1605         };
1606
1607
1608         $cache{titles}{$_->id} = $_ for (@$titles);
1609         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1610 }
1611
1612 1;