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