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