]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
f58ff7b0799c9b3446033a7acc5eeb3ecaa3ecac
[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         my $ord_table = asset::copy_location_order->table;
412
413         my $idlist = 1 if ($self->api_name =~/id_list/o);
414         my $count = 1 if ($self->api_name =~/count$/o);
415
416         my $status_filter = '';
417         $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
418
419         my $select = <<"        SQL";
420                 SELECT  h.*
421                   FROM  $h_table h
422                         JOIN $a_table a ON (h.current_copy = a.id)
423                         LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
424                   WHERE a.circ_lib = ?
425                         AND h.capture_time IS NULL
426                         AND h.cancel_time IS NULL
427                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
428                         $status_filter
429                   ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
430                   LIMIT $limit
431                   OFFSET $offset
432         SQL
433
434     if ($count) {
435         $select = <<"        SQL";
436             SELECT    count(*)
437               FROM    $h_table h
438                   JOIN $a_table a ON (h.current_copy = a.id)
439               WHERE    a.circ_lib = ?
440                   AND h.capture_time IS NULL
441                   AND h.cancel_time IS NULL
442                   AND (h.expire_time IS NULL OR h.expire_time > NOW())
443                 $status_filter
444         SQL
445     }
446
447         my $sth = action::survey->db_Main->prepare_cached($select);
448         $sth->execute($ou);
449
450         if ($count) {
451                 $client->respond( $sth->fetchall_arrayref()->[0][0] );
452         } elsif ($idlist) {
453                 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
454         } else {
455                 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
456         }
457
458         return undef;
459 }
460 __PACKAGE__->register_method(
461         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
462         api_level       => 1,
463         stream          => 1,
464         signature       => [
465                 "Returns a count of holds for a specific library's pull list.",
466                 [ [org_unit => "The library's org id", "number"] ],
467                 ['A count of holds for the stated library to pull ', 'number']
468         ],
469         method          => 'hold_pull_list',
470 );
471 __PACKAGE__->register_method(
472         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
473         api_level       => 1,
474         stream          => 1,
475         signature       => [
476                 "Returns a status filtered count of holds for a specific library's pull list.",
477                 [ [org_unit => "The library's org id", "number"] ],
478                 ['A status filtered count of holds for the stated library to pull ', 'number']
479         ],
480         method          => 'hold_pull_list',
481 );
482 __PACKAGE__->register_method(
483         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
484         api_level       => 1,
485         stream          => 1,
486         signature       => [
487                 "Returns the hold ids for a specific library's pull list.",
488                 [ [org_unit => "The library's org id", "number"],
489                   [limit => 'An optional page size, defaults to 10', 'number'],
490                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
491                 ],
492                 ['A list of holds for the stated library to pull for', 'array']
493         ],
494         method          => 'hold_pull_list',
495 );
496 __PACKAGE__->register_method(
497         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
498         api_level       => 1,
499         stream          => 1,
500         signature       => [
501                 "Returns the holds for a specific library's pull list.",
502                 [ [org_unit => "The library's org id", "number"],
503                   [limit => 'An optional page size, defaults to 10', 'number'],
504                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
505                 ],
506                 ['A list of holds for the stated library to pull for', 'array']
507         ],
508         method          => 'hold_pull_list',
509 );
510 __PACKAGE__->register_method(
511         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
512         api_level       => 1,
513         stream          => 1,
514         signature       => [
515                 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
516                 [ [org_unit => "The library's org id", "number"],
517                   [limit => 'An optional page size, defaults to 10', 'number'],
518                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
519                 ],
520                 ['A list of holds for the stated library to pull for', 'array']
521         ],
522         method          => 'hold_pull_list',
523 );
524 __PACKAGE__->register_method(
525         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
526         api_level       => 1,
527         stream          => 1,
528         signature       => [
529                 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
530                 [ [org_unit => "The library's org id", "number"],
531                   [limit => 'An optional page size, defaults to 10', 'number'],
532                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
533                 ],
534                 ['A list of holds for the stated library to pull for', 'array']
535         ],
536         method          => 'hold_pull_list',
537 );
538
539 sub find_optional_surveys {
540         my $self = shift;
541         my $client = shift;
542         my $ou = ''.shift();
543
544         return undef unless ($ou);
545         my $s_table = action::survey->table;
546
547         my $select = <<"        SQL";
548                 SELECT  s.*
549                   FROM  $s_table s
550                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
551                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
552                         AND s.required IS FALSE;
553         SQL
554
555         my $sth = action::survey->db_Main->prepare_cached($select);
556         $sth->execute($ou);
557
558         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
559
560         return undef;
561 }
562 __PACKAGE__->register_method(
563         api_name        => 'open-ils.storage.action.survey.optional',
564         api_level       => 1,
565         stream          => 1,
566         method          => 'find_optional_surveys',
567 );
568
569 sub find_required_surveys {
570         my $self = shift;
571         my $client = shift;
572         my $ou = ''.shift();
573
574         return undef unless ($ou);
575         my $s_table = action::survey->table;
576
577         my $select = <<"        SQL";
578                 SELECT  s.*
579                   FROM  $s_table s
580                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
581                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
582                         AND s.required IS TRUE;
583         SQL
584
585         my $sth = action::survey->db_Main->prepare_cached($select);
586         $sth->execute($ou);
587
588         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
589
590         return undef;
591 }
592 __PACKAGE__->register_method(
593         api_name        => 'open-ils.storage.action.survey.required',
594         api_level       => 1,
595         stream          => 1,
596         method          => 'find_required_surveys',
597 );
598
599 sub find_usr_summary_surveys {
600         my $self = shift;
601         my $client = shift;
602         my $ou = ''.shift();
603
604         return undef unless ($ou);
605         my $s_table = action::survey->table;
606
607         my $select = <<"        SQL";
608                 SELECT  s.*
609                   FROM  $s_table s
610                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
611                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
612                         AND s.usr_summary IS TRUE;
613         SQL
614
615         my $sth = action::survey->db_Main->prepare_cached($select);
616         $sth->execute($ou);
617
618         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
619
620         return undef;
621 }
622 __PACKAGE__->register_method(
623         api_name        => 'open-ils.storage.action.survey.usr_summary',
624         api_level       => 1,
625         stream          => 1,
626         method          => 'find_usr_summary_surveys',
627 );
628
629
630 sub generate_fines {
631         my $self = shift;
632         my $client = shift;
633         my $grace = shift;
634         my $circ = shift;
635         my $overbill = shift;
636
637         local $OpenILS::Application::Storage::WRITE = 1;
638
639         my @circs;
640         if ($circ) {
641                 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
642         } else {
643                 push @circs, overdue_circs($grace);
644         }
645
646         my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
647
648         my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
649         for my $c (@circs) {
650         
651                 try {
652                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
653                                 $log->debug("Cleaning up after previous transaction\n");
654                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
655                         }
656                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
657                         $log->info("Processing circ ".$c->id."...\n");
658
659
660                         my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
661         
662                         my $due = $due_dt->epoch;
663                         my $now = time;
664
665                         my $fine_interval = $c->fine_interval;
666             $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
667                         $fine_interval = interval_to_seconds( $fine_interval );
668         
669                         if ( $fine_interval >= interval_to_seconds('1d') ) {    
670                                 my $tz_offset_s = 0;
671                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
672                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
673                                 }
674         
675                                 $due -= ($due % $fine_interval) + $tz_offset_s;
676                                 $now -= ($now % $fine_interval) + $tz_offset_s;
677                         }
678         
679                         $client->respond(
680                                 "ARG! Overdue circulation ".$c->id.
681                                 " for item ".$c->target_copy.
682                                 " (user ".$c->usr.").\n".
683                                 "\tItem was due on or before: ".localtime($due)."\n");
684         
685                         my @fines = money::billing->search_where(
686                                 { xact => $c->id,
687                                   btype => 1,
688                                   billing_ts => { '>' => $c->due_date } },
689                                 { order_by => 'billing_ts DESC'}
690                         );
691
692                         my $f_idx = 0;
693                         my $fine = $fines[$f_idx] if (@fines);
694                         if ($overbill) {
695                                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
696                         }
697
698                         my $current_fine_total = 0;
699                         $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
700         
701                         my $last_fine;
702                         if ($fine) {
703                                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
704                                 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
705                         } else {
706                                 $log->info( "Potential first billing for circ ".$c->id );
707                                 $last_fine = $due;
708
709                                 if (0) {
710                                         if (my $h = $hoo{$c->circ_lib}) { 
711
712                                                 $log->info( "Circ lib has an hours-of-operation entry" );
713                                                 # find the day after the due date...
714                                                 $due_dt = $due_dt->add( days => 1 );
715
716                                                 # get the day of the week for that day...
717                                                 my $dow = $due_dt->day_of_week_0;
718                                                 my $dow_open = "dow_${dow}_open";
719                                                 my $dow_close = "dow_${dow}_close";
720
721                                                 my $count = 0;
722                                                 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
723                                                         # if the circ lib is closed, add a day to the grace period...
724
725                                                         $grace++;
726                                                         $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
727                                                         $log->info( "Day of week $dow open $dow_open, close $dow_close" );
728
729                                                         $due_dt = $due_dt->add( days => 1 );
730                                                         $dow = $due_dt->day_of_week_0;
731                                                         $dow_open = "dow_${dow}_open";
732                                                         $dow_close = "dow_${dow}_close";
733
734                                                         $count++;
735
736                                                         # and check for up to a week
737                                                         last if ($count > 6);
738                                                 }
739                                         }
740                                 }
741                         }
742
743
744                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
745                         if ($pending_fine_count < 1 + $grace) {
746                                 $client->respond( "\tNo fines to create.  " );
747                                 if ($grace && $now < $due + $fine_interval * $grace) {
748                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
749                                         $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
750                                 } else {
751                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
752                                 }
753                                 next;
754                         }
755         
756                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
757
758                         my $recuring_fine = int($c->recuring_fine * 100);
759                         my $max_fine = int($c->max_fine * 100);
760
761                         my ($latest_billing_ts, $latest_amount) = ('',0);
762                         for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
763         
764                                 if ($current_fine_total >= $max_fine) {
765                                         $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
766                                         $client->respond(
767                                                 "\tMaximum fine level of ".$c->max_fine.
768                                                 " reached for this circulation.\n".
769                                                 "\tNo more fines will be generated.\n" );
770                                         last;
771                                 }
772                                 
773                                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
774
775                                 my $dow = $billing_ts->day_of_week_0();
776                                 my $dow_open = "dow_${dow}_open";
777                                 my $dow_close = "dow_${dow}_close";
778
779                                 if (my $h = $hoo{$c->circ_lib}) {
780                                         next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
781                                 }
782
783                                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
784                                 my @cl = actor::org_unit::closed_date->search_where(
785                                                 { close_start   => { '<=' => $timestamptz },
786                                                   close_end     => { '>=' => $timestamptz },
787                                                   org_unit      => $c->circ_lib }
788                                 );
789                                 next if (@cl);
790         
791                                 $current_fine_total += $recuring_fine;
792                                 $latest_amount += $recuring_fine;
793                                 $latest_billing_ts = $timestamptz;
794
795                                 money::billing->create(
796                                         { xact          => ''.$c->id,
797                                           note          => "System Generated Overdue Fine",
798                                           billing_type  => "Overdue materials",
799                                           btype         => 1,
800                                           amount        => sprintf('%0.2f', $recuring_fine/100),
801                                           billing_ts    => $timestamptz,
802                                         }
803                                 );
804
805                         }
806
807                         $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
808                                 if ($latest_billing_ts and $latest_amount);
809
810                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
811
812                         if(1) { 
813
814                 # Caluclate penalties inline
815                                 OpenILS::Utils::Penalty->calculate_penalties(
816                                         undef, $c->usr->to_fieldmapper->id.'', $c->circ_lib->to_fieldmapper->id.'');
817
818                         } else {
819
820                 # Calculate penalties with an aysnc call to the penalty server.  This approach
821                 # may lead to duplicate penalties since multiple penalty processes for a
822                 # given user may be running at the same time. Leave this here for reference 
823                 # in case we later find that asyc calls are needed in some environments.
824                                 $penalty->request(
825                                     'open-ils.penalty.patron_penalty.calculate',
826                                     { patronid  => ''.$c->usr,
827                                     context_org => ''.$c->circ_lib,
828                                     update      => 1,
829                                     background  => 1,
830                                     }
831                             )->gather(1);
832                         }
833
834                 } catch Error with {
835                         my $e = shift;
836                         $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
837                         $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
838                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
839                         throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
840                 };
841         }
842 }
843 __PACKAGE__->register_method(
844         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
845         api_level       => 1,
846         stream          => 1,
847         method          => 'generate_fines',
848 );
849
850
851
852 sub new_hold_copy_targeter {
853         my $self = shift;
854         my $client = shift;
855         my $check_expire = shift;
856         my $one_hold = shift;
857
858         local $OpenILS::Application::Storage::WRITE = 1;
859
860         $self->{target_weight} = {};
861
862         my $holds;
863
864         try {
865                 if ($one_hold) {
866                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
867                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
868                 } elsif ( $check_expire ) {
869
870                         # what's the retarget time threashold?
871                         my $time = time;
872                         $check_expire ||= '12h';
873                         $check_expire = interval_to_seconds( $check_expire );
874
875                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
876                         $year += 1900;
877                         $mon += 1;
878                         my $expire_threshold = sprintf(
879                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
880                                 $year, $mon, $mday, $hour, $min, $sec
881                         );
882
883                         # find all the holds holds needing retargeting
884                         $holds = [ action::hold_request->search_where(
885                                                         { capture_time => undef,
886                                                           fulfillment_time => undef,
887                                                           cancel_time => undef,
888                                                           frozen => 'f',
889                                                           prev_check_time => { '<=' => $expire_threshold },
890                                                         },
891                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
892
893                         # find all the holds holds needing first time targeting
894                         push @$holds, action::hold_request->search(
895                                                         capture_time => undef,
896                                                         fulfillment_time => undef,
897                                                         prev_check_time => undef,
898                                                         frozen => 'f',
899                                                         cancel_time => undef,
900                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
901                 } else {
902
903                         # find all the holds holds needing first time targeting ONLY
904                         $holds = [ action::hold_request->search(
905                                                         capture_time => undef,
906                                                         fulfillment_time => undef,
907                                                         prev_check_time => undef,
908                                                         cancel_time => undef,
909                                                         frozen => 'f',
910                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
911                 }
912         } catch Error with {
913                 my $e = shift;
914                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
915         };
916
917         my @closed = actor::org_unit::closed_date->search_where(
918                 { close_start => { '<=', 'now' },
919                   close_end => { '>=', 'now' } }
920         );
921
922     if ($check_expire) {
923
924         # $check_expire, if it exists, was already converted to seconds
925         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
926             $year += 1900;
927         $mon += 1;
928
929             my $next_check_time = sprintf(
930                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
931                 $year, $mon, $mday, $hour, $min, $sec
932         );
933
934
935             my @closed_at_next = actor::org_unit::closed_date->search_where(
936                     { close_start => { '<=', $next_check_time },
937                   close_end => { '>=', $next_check_time } }
938             );
939
940         my @new_closed;
941         for my $c_at_n (@closed_at_next) {
942             if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
943                 push @new_closed, $c_at_n;
944             }
945         }
946         @closed = @new_closed;
947     }
948
949         my @successes;
950         my $actor = OpenSRF::AppSession->create('open-ils.actor');
951
952         for my $hold (@$holds) {
953                 try {
954                         #start a transaction if needed
955                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
956                                 $log->debug("Cleaning up after previous transaction\n");
957                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
958                         }
959                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
960                         $log->info("Processing hold ".$hold->id."...\n");
961
962                         #first, re-fetch the hold, to make sure it's not captured already
963                         $hold->remove_from_object_index();
964                         $hold = action::hold_request->retrieve( $hold->id );
965
966                         die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
967
968                         # remove old auto-targeting maps
969                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
970                         $_->delete for (@oldmaps);
971
972                         if ($hold->expire_time) {
973                                 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
974                                 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
975
976                                         # cancel cause = un-targeted expiration
977                                         $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
978                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
979
980                                         # tell A/T the hold was cancelled
981                                         my $fm_hold = $hold->to_fieldmapper;
982                                         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
983                                         $ses->request('open-ils.trigger.event.autocreate', 
984                                                 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
985
986                                         die "OK\n";
987                                 }
988                         }
989
990                         my $all_copies = [];
991
992                         # find filters for MR holds
993                         my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
994
995                         # find all the potential copies
996                         if ($hold->hold_type eq 'M') {
997                                 for my $r ( map
998                                                 {$_->record}
999                                                 metabib::record_descriptor
1000                                                         ->search(
1001                                                                 record => [
1002                                                                         map {
1003                                                                                 isTrue($_->deleted) ?  () : ($_->id)
1004                                                                         } metabib::metarecord->retrieve($hold->target)->source_records
1005                                                                 ],
1006                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
1007                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
1008                                                                 ( $lang    ? (item_lang => $lang)                : () ),
1009                                                         )
1010                                 ) {
1011                                         my ($rtree) = $self
1012                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1013                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1014
1015                                         for my $cn ( @{ $rtree->call_numbers } ) {
1016                                                 push @$all_copies,
1017                                                         asset::copy->search_where(
1018                                                                 { id => [map {$_->id} @{ $cn->copies }],
1019                                                                   deleted => 'f' }
1020                                                         ) if ($cn && @{ $cn->copies });
1021                                         }
1022                                 }
1023                         } elsif ($hold->hold_type eq 'T') {
1024                                 my ($rtree) = $self
1025                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1026                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1027
1028                                 unless ($rtree) {
1029                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1030                                         die "OK\n";
1031                                 }
1032
1033                                 for my $cn ( @{ $rtree->call_numbers } ) {
1034                                         push @$all_copies,
1035                                                 asset::copy->search_where(
1036                                                         { id => [map {$_->id} @{ $cn->copies }],
1037                                                           deleted => 'f' }
1038                                                 ) if ($cn && @{ $cn->copies });
1039                                 }
1040                         } elsif ($hold->hold_type eq 'V') {
1041                                 my ($vtree) = $self
1042                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1043                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1044
1045                                 push @$all_copies,
1046                                         asset::copy->search_where(
1047                                                 { id => [map {$_->id} @{ $vtree->copies }],
1048                                                   deleted => 'f' }
1049                                         ) if ($vtree && @{ $vtree->copies });
1050                                         
1051                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1052                                 my $_cp = asset::copy->retrieve($hold->target);
1053                                 push @$all_copies, $_cp if $_cp;
1054                         }
1055
1056                         # trim unholdables
1057                         @$all_copies = grep {   isTrue($_->status->holdable) && 
1058                                                 isTrue($_->location->holdable) && 
1059                                                 isTrue($_->holdable) &&
1060                                                 !isTrue($_->deleted) &&
1061                                                 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1062                                         } @$all_copies;
1063
1064                         # let 'em know we're still working
1065                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1066                         
1067                         # if we have no copies ...
1068                         if (!ref $all_copies || !@$all_copies) {
1069                                 $log->info("\tNo copies available for targeting at all!\n");
1070                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1071
1072                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1073                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1074                                 die "OK\n";
1075                         }
1076
1077                         my $copy_count = @$all_copies;
1078
1079                         # map the potentials, so that we can pick up checkins
1080                         # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1081                         # XXX the potentials list.  If this is the cased, hold_copy_map creation will move down further.
1082                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1083                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1084
1085                         #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1086
1087                         my @good_copies;
1088                         for my $c (@$all_copies) {
1089                                 # current target
1090                                 next if ($c->id eq $hold->current_copy);
1091
1092                                 # circ lib is closed
1093                                 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1094
1095                                 # target of another hold
1096                                 next if (action::hold_request
1097                                                 ->search_where(
1098                                                         { current_copy => $c->id,
1099                                                           fulfillment_time => undef,
1100                                                           cancel_time => undef,
1101                                                         }
1102                                                 )
1103                                 );
1104
1105                                 # we passed all three, keep it
1106                                 push @good_copies, $c if ($c);
1107                                 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1108                         }
1109
1110                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1111
1112                         my $old_best = $hold->current_copy;
1113                         $hold->update({ current_copy => undef }) if ($old_best);
1114         
1115                         if (!scalar(@good_copies)) {
1116                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1117                                 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1118                                         # the old copy is still available
1119                                         $log->debug("\tPushing current_copy back onto the targeting list");
1120                                         push @good_copies, $old_best;
1121                                 } else {
1122                                         # oops, old copy is not available
1123                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1124                                         $hold->update( { prev_check_time => 'today' } );
1125                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1126                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1127                                         die "OK\n";
1128                                 }
1129                         }
1130
1131                         my $prox_list = [];
1132                         $$prox_list[0] =
1133                         [
1134                                 grep {
1135                                         $_->circ_lib == $hold->pickup_lib
1136                                 } @good_copies
1137                         ];
1138
1139                         $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1140                         # $all_copies is now a list of copies not at the pickup library
1141
1142                         my $best = choose_nearest_copy($hold, $prox_list);
1143                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1144
1145                         if (!$best) {
1146                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1147
1148                                 my $max_loops = $actor->request(
1149                                         'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib.'' => 'circ.holds.max_org_unit_target_loops'
1150                                 )->gather(1);
1151
1152                                 if (defined($max_loops)) {
1153                                         my %circ_lib_map =  map { $_->circ_lib => 1 } @$all_copies;
1154                                         my $circ_lib_list = [keys %circ_lib_map];
1155         
1156                                         my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1157         
1158                                         # Grab the "biggest" loop for this hold so far
1159                                         my $current_loop = $cstore->request(
1160                                                 'open-ils.cstore.json_query',
1161                                                 { distinct => 1,
1162                                                   select => { aufhmxl => ['max'] },
1163                                                   from => 'aufhmxl',
1164                                                   where => { hold => $hold->id}
1165                                                 }
1166                                         )->gather(1);
1167         
1168                                         $current_loop = $current_loop->{max} if ($current_loop);
1169                                         $current_loop ||= 1;
1170         
1171                                         my $exclude_list = $cstore->request(
1172                                                 'open-ils.cstore.json_query.atomic',
1173                                                 { distinct => 1,
1174                                                   select => { aufhol => [circ_lib] },
1175                                                   from => 'aufhol',
1176                                                   where => { hold => $hold->id}
1177                                                 }
1178                                         )->gather(1);
1179         
1180                                         my @keepers;
1181                                         if ($exclude_list && @$exclude_list) {
1182                                                 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1183                                                 # check to see if we've used up every library in the potentials list
1184                                                 for my $l ( @$circ_lib_list ) {
1185                                                         my $keep = 1;
1186                                                         for my $ex ( @$exclude_list ) {
1187                                                                 if ($ex eq $l) {
1188                                                                         $keep = 0;
1189                                                                         last;
1190                                                                 }
1191                                                         }
1192                                                         push(@keepers, $l) if ($keep);
1193                                                 }
1194                                         } else {
1195                                                 @keepers = @$circ_lib_list;
1196                                         }
1197         
1198                                         $current_loop++ if (!@keepers);
1199         
1200                                         if ($max_loops && $max_loops <= $current_loop) {
1201                                                 # We haven't exceeded max_loops yet
1202                                                 my @keeper_copies;
1203                                                 for my $cp ( @$all_copies ) {
1204                                                         push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1205                                                 }
1206                                         } else {
1207                                                 # We have, and should remove potentials and cancel the hold
1208                                                 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1209                                                 $_->delete for (@oldmaps);
1210
1211                                                 # cancel cause = un-targeted expiration
1212                                                 $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1213                                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1214
1215                                                 # tell A/T the hold was cancelled
1216                                                 my $fm_hold = $hold->to_fieldmapper;
1217                                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1218                                                 $ses->request('open-ils.trigger.event.autocreate', 
1219                                                         'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1220
1221                                                 die "OK\n";
1222                                         }
1223                                 }
1224
1225                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1226
1227                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1228
1229                                 $best = choose_nearest_copy($hold, $prox_list);
1230                         }
1231
1232                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1233                         if ($old_best) {
1234                                 # hold wasn't fulfilled, record the fact
1235                         
1236                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1237                                 action::unfulfilled_hold_list->create(
1238                                                 { hold => ''.$hold->id,
1239                                                   current_copy => ''.$old_best->id,
1240                                                   circ_lib => ''.$old_best->circ_lib,
1241                                                 });
1242                         }
1243
1244                         if ($best) {
1245                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1246                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1247                         } elsif (
1248                                 $old_best &&
1249                                 action::hold_request
1250                                         ->search_where(
1251                                                 { current_copy => $old_best->id,
1252                                                   fulfillment_time => undef,
1253                                                   cancel_time => undef,
1254                                                 }       
1255                                         )
1256                         ) {     
1257                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1258                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1259                         } else {
1260                                 $hold->update( { prev_check_time => 'now' } );
1261                                 $log->info( "\tThere were no targetable copies for the hold" );
1262                         }
1263
1264                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1265                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1266
1267                         push @successes,
1268                                 { hold => $hold->id,
1269                                   old_target => ($old_best ? $old_best->id : undef),
1270                                   eligible_copies => $copy_count,
1271                                   target => ($best ? $best->id : undef) };
1272
1273                 } otherwise {
1274                         my $e = shift;
1275                         if ($e !~ /^OK/o) {
1276                                 $log->error("Processing of hold failed:  $e");
1277                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1278                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1279                         }
1280                 };
1281         }
1282
1283         return \@successes;
1284 }
1285 __PACKAGE__->register_method(
1286         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1287         api_level       => 1,
1288         method          => 'new_hold_copy_targeter',
1289 );
1290
1291 my $locations;
1292 my $statuses;
1293 my %cache = (titles => {}, cns => {});
1294 sub hold_copy_targeter {
1295         my $self = shift;
1296         my $client = shift;
1297         my $check_expire = shift;
1298         my $one_hold = shift;
1299
1300         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1301         $self->{user_filter}->connect;
1302         $self->{client} = $client;
1303
1304         my $time = time;
1305         $check_expire ||= '12h';
1306         $check_expire = interval_to_seconds( $check_expire );
1307
1308         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1309         $year += 1900;
1310         $mon += 1;
1311         my $expire_threshold = sprintf(
1312                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1313                 $year, $mon, $mday, $hour, $min, $sec
1314         );
1315
1316
1317         $statuses ||= [ config::copy_status->search(holdable => 't') ];
1318
1319         $locations ||= [ asset::copy_location->search(holdable => 't') ];
1320
1321         my $holds;
1322
1323         %cache = (titles => {}, cns => {});
1324
1325         try {
1326                 if ($one_hold) {
1327                         $holds = [ action::hold_request->search(id => $one_hold) ];
1328                 } else {
1329                         $holds = [ action::hold_request->search_where(
1330                                                         { capture_time => undef,
1331                                                           prev_check_time => { '<=' => $expire_threshold },
1332                                                         },
1333                                                         { order_by => 'request_time,prev_check_time' } ) ];
1334                         push @$holds, action::hold_request->search_where(
1335                                                         { capture_time => undef,
1336                                                           prev_check_time => undef,
1337                                                         },
1338                                                         { order_by => 'request_time' } );
1339                 }
1340         } catch Error with {
1341                 my $e = shift;
1342                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1343         };
1344
1345         for my $hold (@$holds) {
1346                 try {
1347                         #action::hold_request->db_Main->begin_work;
1348                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1349                                 $client->respond("Cleaning up after previous transaction\n");
1350                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1351                         }
1352                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1353                         $client->respond("Processing hold ".$hold->id."...\n");
1354
1355                         my $copies;
1356
1357                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1358                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1359
1360                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1361                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1362                         
1363                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1364                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1365                         
1366                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1367
1368                         unless (ref $copies || !@$copies) {
1369                                 $client->respond("\tNo copies available for targeting at all!\n");
1370                         }
1371
1372                         my @good_copies;
1373                         for my $c (@$copies) {
1374                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1375                                 push @good_copies, $c if ($c);
1376                         }
1377
1378                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1379
1380                         my $old_best = $hold->current_copy;
1381                         $hold->update({ current_copy => undef });
1382         
1383                         if (!scalar(@good_copies)) {
1384                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1385                                 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1386                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
1387                                         push @good_copies, asset::copy->retrieve( $old_best );
1388                                 } else {
1389                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1390                                         next;
1391                                 }
1392                         }
1393
1394                         my $prox_list;
1395                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1396                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1397
1398                         my $best = choose_nearest_copy($hold, $prox_list);
1399
1400                         if (!$best) {
1401                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1402                                 $best = choose_nearest_copy($hold, $prox_list);
1403                         }
1404
1405                         if ($old_best) {
1406                                 # hold wasn't fulfilled, record the fact
1407                         
1408                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1409                                 action::unfulfilled_hold_list->create(
1410                                                 { hold => ''.$hold->id,
1411                                                   current_copy => ''.$old_best->id,
1412                                                   circ_lib => ''.$old_best->circ_lib,
1413                                                 });
1414                         }
1415
1416                         if ($best) {
1417                                 $hold->update( { current_copy => ''.$best->id } );
1418                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1419                         }
1420
1421                         $hold->update( { prev_check_time => 'now' } );
1422                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1423
1424                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1425                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1426
1427                         #action::hold_request->dbi_commit;
1428
1429                 } otherwise {
1430                         my $e = shift;
1431                         $log->error("Processing of hold failed:  $e");
1432                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1433                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1434                         #action::hold_request->dbi_rollback;
1435                 };
1436         }
1437
1438         $self->{user_filter}->disconnect;
1439         $self->{user_filter}->finish;
1440         delete $$self{user_filter};
1441         return undef;
1442 }
1443 #__PACKAGE__->register_method(
1444 #       api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1445 #       api_level       => 0,
1446 #       stream          => 1,
1447 #       method          => 'hold_copy_targeter',
1448 #);
1449
1450
1451 sub copy_hold_capture {
1452         my $self = shift;
1453         my $hold = shift;
1454         my $cps = shift;
1455
1456         if (!defined($cps)) {
1457                 try {
1458                         $cps = [ asset::copy->search( id => $hold->target ) ];
1459                 } catch Error with {
1460                         my $e = shift;
1461                         die "Could not retrieve initial volume list:\n\n$e\n";
1462                 };
1463         }
1464
1465         my @copies = grep { $_->holdable } @$cps;
1466
1467         for (my $i = 0; $i < @$cps; $i++) {
1468                 next unless $$cps[$i];
1469                 
1470                 my $cn = $cache{cns}{$copies[$i]->call_number};
1471                 my $rec = $cache{titles}{$cn->record};
1472                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1473                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1474                 $copies[$i] = undef if (
1475                         !$copies[$i] ||
1476                         !$self->{user_filter}->request(
1477                                 'open-ils.circ.permit_hold',
1478                                 $hold->to_fieldmapper, do {
1479                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1480                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1481                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1482                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1483                                         $cp_fm;
1484                                 },
1485                                 { title => $rec->to_fieldmapper,
1486                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1487                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1488                                 })->gather(1)
1489                 );
1490                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1491         }
1492
1493         @copies = grep { $_ } @copies;
1494
1495         my $count = @copies;
1496
1497         return unless ($count);
1498         
1499         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1500         
1501         my @maps;
1502         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1503         for my $c (@copies) {
1504                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1505         }
1506         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1507
1508         return \@copies;
1509 }
1510
1511
1512 sub choose_nearest_copy {
1513         my $hold = shift;
1514         my $prox_list = shift;
1515
1516         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1517                 next unless (ref $$prox_list[$p]);
1518
1519                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1520                 next unless (@capturable);
1521
1522                 my $rand = int(rand(scalar(@capturable)));
1523                 while (my ($c) = splice(@capturable,$rand)) {
1524                         return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1525                                 { title => $c->call_number->record->to_fieldmapper,
1526                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1527                                   patron => $hold->usr->to_fieldmapper,
1528                                   copy => $c->to_fieldmapper,
1529                                   requestor => $hold->requestor->to_fieldmapper,
1530                                   request_lib => $hold->request_lib->to_fieldmapper,
1531                                    pickup_lib => $hold->pickup_lib->id,
1532                                 }
1533                         ));
1534
1535                         last unless(@capturable);
1536                         $rand = int(rand(scalar(@capturable)));
1537                 }
1538         }
1539 }
1540
1541 sub create_prox_list {
1542         my $self = shift;
1543         my $lib = shift;
1544         my $copies = shift;
1545
1546         my $actor = OpenSRF::AppSession->create('open-ils.actor');
1547
1548         my @prox_list;
1549         for my $cp (@$copies) {
1550                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1551                 next unless (defined($prox));
1552
1553                 # Fetch the weighting value for hold targeting, defaulting to 1
1554                 $self->{target_weight}{$lib} ||= $actor->request(
1555                         'open-ils.actor.ou_setting.ancestor_default' => $lib.'' => 'circ.holds.org_unit_target_weight'
1556                 )->gather(1) || 1;
1557
1558                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1559                 for my $w ( 1 .. $self->{target_weight}{$lib} ) {
1560                         push @{$prox_list[$prox]}, $cp;
1561                 }
1562         }
1563         return \@prox_list;
1564 }
1565
1566 sub volume_hold_capture {
1567         my $self = shift;
1568         my $hold = shift;
1569         my $vols = shift;
1570
1571         if (!defined($vols)) {
1572                 try {
1573                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1574                         $cache{cns}{$_->id} = $_ for (@$vols);
1575                 } catch Error with {
1576                         my $e = shift;
1577                         die "Could not retrieve initial volume list:\n\n$e\n";
1578                 };
1579         }
1580
1581         my @v_ids = map { $_->id } @$vols;
1582
1583         my $cp_list;
1584         try {
1585                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1586         
1587         } catch Error with {
1588                 my $e = shift;
1589                 warn "Could not retrieve copy list:\n\n$e\n";
1590         };
1591
1592         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1593 }
1594
1595 sub title_hold_capture {
1596         my $self = shift;
1597         my $hold = shift;
1598         my $titles = shift;
1599
1600         if (!defined($titles)) {
1601                 try {
1602                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1603                         $cache{titles}{$_->id} = $_ for (@$titles);
1604                 } catch Error with {
1605                         my $e = shift;
1606                         die "Could not retrieve initial title list:\n\n$e\n";
1607                 };
1608         }
1609
1610         my @t_ids = map { $_->id } @$titles;
1611         my $cn_list;
1612         try {
1613                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1614         
1615         } catch Error with {
1616                 my $e = shift;
1617                 warn "Could not retrieve volume list:\n\n$e\n";
1618         };
1619
1620         $cache{cns}{$_->id} = $_ for (@$cn_list);
1621
1622         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1623 }
1624
1625 sub metarecord_hold_capture {
1626         my $self = shift;
1627         my $hold = shift;
1628
1629         my $titles;
1630         try {
1631                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1632         
1633         } catch Error with {
1634                 my $e = shift;
1635                 die "Could not retrieve initial title list:\n\n$e\n";
1636         };
1637
1638         try {
1639                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1640
1641                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1642         
1643         } catch Error with {
1644                 my $e = shift;
1645                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1646         };
1647
1648
1649         $cache{titles}{$_->id} = $_ for (@$titles);
1650         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1651 }
1652
1653 1;