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