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