]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Acq/Order.pm
LP1182519 Per-Hold Behind Desk Value
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Acq / Order.pm
1 package OpenILS::Application::Acq::BatchManager;
2 use OpenILS::Application::Acq::Financials;
3 use OpenSRF::AppSession;
4 use OpenSRF::EX qw/:try/;
5 use strict; use warnings;
6
7 sub new {
8     my($class, %args) = @_;
9     my $self = bless(\%args, $class);
10     $self->{args} = {
11         lid => 0,
12         li => 0,
13         vqbr => 0,
14         copies => 0,
15         bibs => 0,
16         progress => 0,
17         debits_accrued => 0,
18         purchase_order => undef,
19         picklist => undef,
20         complete => 0,
21         indexed => 0,
22         queue => undef,
23         total => 0
24     };
25     $self->{cache} = {};
26     $self->throttle(4) unless $self->throttle;
27     $self->{post_proc_queue} = [];
28     $self->{last_respond_progress} = 0;
29     return $self;
30 }
31
32 sub conn {
33     my($self, $val) = @_;
34     $self->{conn} = $val if $val;
35     return $self->{conn};
36 }
37 sub throttle {
38     my($self, $val) = @_;
39     $self->{throttle} = $val if $val;
40     return $self->{throttle};
41 }
42 sub respond {
43     my($self, %other_args) = @_;
44     if($self->throttle and not %other_args) {
45         return unless (
46             ($self->{args}->{progress} - $self->{last_respond_progress}) >= $self->throttle
47         );
48     }
49     $self->conn->respond({ %{$self->{args}}, %other_args });
50     $self->{last_respond_progress} = $self->{args}->{progress};
51     $self->throttle($self->throttle * 2) unless $self->throttle >= 256;
52 }
53 sub respond_complete {
54     my($self, %other_args) = @_;
55     $self->complete;
56     $self->conn->respond_complete({ %{$self->{args}}, %other_args });
57     $self->run_post_response_hooks;
58     return undef;
59 }
60
61 # run the post response hook subs, shifting them off as we go
62 sub run_post_response_hooks {
63     my($self) = @_;
64     (shift @{$self->{post_proc_queue}})->() while @{$self->{post_proc_queue}};
65 }
66
67 # any subs passed to this method will be run after the call to respond_complete
68 sub post_process {
69     my($self, $sub) = @_;
70     push(@{$self->{post_proc_queue}}, $sub);
71 }
72
73 sub total {
74     my($self, $val) = @_;
75     $self->{args}->{total} = $val if defined $val;
76     $self->{args}->{maximum} = $self->{args}->{total};
77     return $self->{args}->{total};
78 }
79 sub purchase_order {
80     my($self, $val) = @_;
81     $self->{args}->{purchase_order} = $val if $val;
82     return $self;
83 }
84 sub picklist {
85     my($self, $val) = @_;
86     $self->{args}->{picklist} = $val if $val;
87     return $self;
88 }
89 sub add_lid {
90     my $self = shift;
91     $self->{args}->{lid} += 1;
92     $self->{args}->{progress} += 1;
93     return $self;
94 }
95 sub add_li {
96     my $self = shift;
97     $self->{args}->{li} += 1;
98     $self->{args}->{progress} += 1;
99     return $self;
100 }
101 sub add_vqbr {
102     my $self = shift;
103     $self->{args}->{vqbr} += 1;
104     $self->{args}->{progress} += 1;
105     return $self;
106 }
107 sub add_copy {
108     my $self = shift;
109     $self->{args}->{copies} += 1;
110     $self->{args}->{progress} += 1;
111     return $self;
112 }
113 sub add_bib {
114     my $self = shift;
115     $self->{args}->{bibs} += 1;
116     $self->{args}->{progress} += 1;
117     return $self;
118 }
119 sub add_debit {
120     my($self, $amount) = @_;
121     $self->{args}->{debits_accrued} += $amount;
122     $self->{args}->{progress} += 1;
123     return $self;
124 }
125 sub editor {
126     my($self, $editor) = @_;
127     $self->{editor} = $editor if defined $editor;
128     return $self->{editor};
129 }
130 sub complete {
131     my $self = shift;
132     $self->{args}->{complete} = 1;
133     return $self;
134 }
135
136 sub cache {
137     my($self, $org, $key, $val) = @_;
138     $self->{cache}->{$org} = {} unless $self->{cache}->{org};
139     $self->{cache}->{$org}->{$key} = $val if defined $val;
140     return $self->{cache}->{$org}->{$key};
141 }
142
143
144 package OpenILS::Application::Acq::Order;
145 use base qw/OpenILS::Application/;
146 use strict; use warnings;
147 # ----------------------------------------------------------------------------
148 # Break up each component of the order process and pieces into managable
149 # actions that can be shared across different workflows
150 # ----------------------------------------------------------------------------
151 use OpenILS::Event;
152 use OpenSRF::Utils::Logger qw(:logger);
153 use OpenSRF::Utils::JSON;
154 use OpenSRF::AppSession;
155 use OpenILS::Utils::Fieldmapper;
156 use OpenILS::Utils::CStoreEditor q/:funcs/;
157 use OpenILS::Utils::Normalize qw/clean_marc/;
158 use OpenILS::Const qw/:const/;
159 use OpenSRF::EX q/:try/;
160 use OpenILS::Application::AppUtils;
161 use OpenILS::Application::Cat::BibCommon;
162 use OpenILS::Application::Cat::AssetCommon;
163 use MARC::Record;
164 use MARC::Batch;
165 use MARC::File::XML (BinaryEncoding => 'UTF-8');
166 use Digest::MD5 qw(md5_hex);
167 use Data::Dumper;
168 $Data::Dumper::Indent = 0;
169 my $U = 'OpenILS::Application::AppUtils';
170
171
172 # ----------------------------------------------------------------------------
173 # Lineitem
174 # ----------------------------------------------------------------------------
175 sub create_lineitem {
176     my($mgr, %args) = @_;
177     my $li = Fieldmapper::acq::lineitem->new;
178     $li->creator($mgr->editor->requestor->id);
179     $li->selector($li->creator);
180     $li->editor($li->creator);
181     $li->create_time('now');
182     $li->edit_time('now');
183     $li->state('new');
184     $li->$_($args{$_}) for keys %args;
185     $li->clear_id;
186     $mgr->add_li;
187     $mgr->editor->create_acq_lineitem($li) or return 0;
188     
189     unless($li->estimated_unit_price) {
190         # extract the price from the MARC data
191         my $price = get_li_price_from_attr($mgr->editor, $li) or return $li;
192         $li->estimated_unit_price($price);
193         return update_lineitem($mgr, $li);
194     }
195
196     return $li;
197 }
198
199 sub get_li_price_from_attr {
200     my($e, $li) = @_;
201     my $attrs = $li->attributes || $e->search_acq_lineitem_attr({lineitem => $li->id});
202
203     for my $attr_type (qw/    
204             lineitem_local_attr_definition 
205             lineitem_prov_attr_definition 
206             lineitem_marc_attr_definition/) {
207
208         my ($attr) = grep {
209             $_->attr_name eq 'estimated_price' and 
210             $_->attr_type eq $attr_type } @$attrs;
211
212         return $attr->attr_value if $attr;
213     }
214
215     return undef;
216 }
217
218
219 sub update_lineitem {
220     my($mgr, $li) = @_;
221     $li->edit_time('now');
222     $li->editor($mgr->editor->requestor->id);
223     $mgr->add_li;
224     return $mgr->editor->retrieve_acq_lineitem($mgr->editor->data) if
225         $mgr->editor->update_acq_lineitem($li);
226     return undef;
227 }
228
229
230 # ----------------------------------------------------------------------------
231 # Create real holds from patron requests for a given lineitem
232 # ----------------------------------------------------------------------------
233 sub promote_lineitem_holds {
234     my($mgr, $li) = @_;
235
236     my $requests = $mgr->editor->search_acq_user_request(
237         { lineitem => $li->id,
238           '-or' =>
239             [ { need_before => {'>' => 'now'} },
240               { need_before => undef }
241             ]
242         }
243     );
244
245     for my $request ( @$requests ) {
246
247         $request->eg_bib( $li->eg_bib_id );
248         $mgr->editor->update_acq_user_request( $request ) or return 0;
249
250         next unless ($U->is_true( $request->hold ));
251
252         my $hold = Fieldmapper::action::hold_request->new;
253         $hold->usr( $request->usr );
254         $hold->requestor( $request->usr );
255         $hold->request_time( $request->request_date );
256         $hold->pickup_lib( $request->pickup_lib );
257         $hold->request_lib( $request->pickup_lib );
258         $hold->selection_ou( $request->pickup_lib );
259         $hold->phone_notify( $request->phone_notify );
260         $hold->email_notify( $request->email_notify );
261         $hold->expire_time( $request->need_before );
262
263         if ($request->holdable_formats) {
264             my $mrm = $mgr->editor->search_metabib_metarecord_source_map( { source => $li->eg_bib_id } )->[0];
265             if ($mrm) {
266                 $hold->hold_type( 'M' );
267                 $hold->holdable_formats( $request->holdable_formats );
268                 $hold->target( $mrm->metarecord );
269             }
270         }
271
272         if (!$hold->target) {
273             $hold->hold_type( 'T' );
274             $hold->target( $li->eg_bib_id );
275         }
276
277         # if behind-the-desk holds are supported at the 
278         # pickup library, apply the patron default
279         my $bdous = $U->ou_ancestor_setting_value(
280             $hold->pickup_lib, 
281             'circ.holds.behind_desk_pickup_supported', 
282             $mgr->editor
283         );
284
285         if ($bdous) {
286             my $set = $mgr->editor->search_actor_user_setting(
287                 {usr => $hold->usr, name => 'circ.holds_behind_desk'})->[0];
288     
289             $hold->behind_desk('t') if $set and 
290                 OpenSRF::Utils::JSON->JSON2perl($set->value);
291         }
292
293         $mgr->editor->create_action_hold_request( $hold ) or return 0;
294     }
295
296     return $li;
297 }
298
299 sub delete_lineitem {
300     my($mgr, $li) = @_;
301     $li = $mgr->editor->retrieve_acq_lineitem($li) unless ref $li;
302
303     # delete the attached lineitem_details
304     my $lid_ids = $mgr->editor->search_acq_lineitem_detail({lineitem => $li->id}, {idlist=>1});
305     for my $lid_id (@$lid_ids) {
306         return 0 unless delete_lineitem_detail($mgr, $lid_id);
307     }
308
309     $mgr->add_li;
310     return $mgr->editor->delete_acq_lineitem($li);
311 }
312
313 # begins and commit transactions as it goes
314 # bib_only exits before creation of copies and callnumbers
315 sub create_lineitem_list_assets {
316     my($mgr, $li_ids, $vandelay, $bib_only) = @_;
317
318     # Do not create line items if none are specified
319     return {} unless (scalar(@$li_ids));
320
321     if (check_import_li_marc_perms($mgr, $li_ids)) { # event on error
322         $logger->error("acq-vl: user does not have permission to import acq records");
323         return undef;
324     }
325
326     my $res = import_li_bibs_via_vandelay($mgr, $li_ids, $vandelay);
327     return undef unless $res;
328     return $res if $bib_only;
329
330     # create the bibs/volumes/copies for the successfully imported records
331     for my $li_id (@{$res->{li_ids}}) {
332         $mgr->editor->xact_begin;
333         my $data = create_lineitem_assets($mgr, $li_id) or return undef;
334         $mgr->editor->xact_commit;
335         $mgr->respond;
336     }
337
338     return $res;
339 }
340
341 sub test_vandelay_import_args {
342     my $vandelay = shift;
343     my $q_needed = shift;
344
345     # we need valid args and (sometimes) a queue
346     return 0 unless $vandelay and (
347         !$q_needed or
348         $vandelay->{queue_name} or 
349         $vandelay->{existing_queue}
350     );
351
352     # match-based merge/overlay import
353     return 2 if $vandelay->{merge_profile} and (
354         $vandelay->{auto_overlay_exact} or
355         $vandelay->{auto_overlay_1match} or
356         $vandelay->{auto_overlay_best_match}
357     );
358
359     # no-match import
360     return 2 if $vandelay->{import_no_match};
361
362     return 1; # queue only
363 }
364
365 sub find_or_create_vandelay_queue {
366     my ($e, $vandelay) = @_;
367
368     my $queue;
369     if (my $name = $vandelay->{queue_name}) {
370
371         # first, see if a queue w/ this name already exists
372         # for this user.  If so, use that instead.
373
374         $queue = $e->search_vandelay_bib_queue(
375             {name => $name, owner => $e->requestor->id})->[0];
376
377         if ($queue) {
378
379             $logger->info("acq-vl: using existing queue $name");
380
381         } else {
382
383             $logger->info("acq-vl: creating new vandelay queue $name");
384
385             $queue = new Fieldmapper::vandelay::bib_queue;
386             $queue->name($name); 
387             $queue->queue_type('acq');
388             $queue->owner($e->requestor->id);
389             $queue->match_set($vandelay->{match_set} || undef); # avoid ''
390             $queue = $e->create_vandelay_bib_queue($queue) or return undef;
391         }
392
393     } else {
394         $queue = $e->retrieve_vandelay_bib_queue($vandelay->{existing_queue})
395             or return undef;
396     }
397     
398     return $queue;
399 }
400
401
402 sub import_li_bibs_via_vandelay {
403     my ($mgr, $li_ids, $vandelay) = @_;
404     my $res = {li_ids => []};
405     my $e = $mgr->editor;
406     $e->xact_begin;
407
408     my $needs_importing = $e->search_acq_lineitem(
409         {id => $li_ids, eg_bib_id => undef}, 
410         {idlist => 1}
411     );
412
413     if (!@$needs_importing) {
414         $logger->info("acq-vl: all records already imported.  no Vandelay work to do");
415         return {li_ids => $li_ids};
416     }
417
418     # see if we have any records that are not yet linked to VL records (i.e. 
419     # not in a queue).  This will tell us if lack of a queue name is an error.
420     my $non_queued = $e->search_acq_lineitem(
421         {id => $needs_importing, queued_record => undef},
422         {idlist => 1}
423     );
424
425     # add the already-imported records to the response list
426     push(@{$res->{li_ids}}, grep { $_ != @$needs_importing } @$li_ids);
427
428     $logger->info("acq-vl: processing recs via Vandelay with args: ".Dumper($vandelay));
429
430     my $vl_stat = test_vandelay_import_args($vandelay, scalar(@$non_queued));
431     if ($vl_stat == 0) {
432         $logger->error("acq-vl: invalid vandelay arguments for acq import (queue needed)");
433         return $res;
434     }
435
436     my $queue;
437     if (@$non_queued) {
438         # when any non-queued lineitems exist, their vandelay counterparts 
439         # require a place to live.
440         $queue = find_or_create_vandelay_queue($e, $vandelay) or return $res;
441
442     } else {
443         # if all lineitems are already queued, the queue reported to the user
444         # is purely for information / convenience.  pick a random queue.
445         $queue = $e->retrieve_acq_lineitem([
446             $needs_importing->[0], {   
447                 flesh => 2, 
448                 flesh_fields => {
449                     jub => ['queued_record'], 
450                     vqbr => ['queue']
451                 }
452             }
453         ])->queued_record->queue;
454     }
455
456     $mgr->{args}->{queue} = $queue;
457
458     # load the lineitems into the queue for merge processing
459     my @vqbr_ids;
460     my @lis;
461     for my $li_id (@$needs_importing) {
462
463         my $li = $e->retrieve_acq_lineitem($li_id) or return $res;
464
465         if ($li->queued_record) {
466             $logger->info("acq-vl: $li_id already linked to a vandelay record");
467             push(@vqbr_ids, $li->queued_record);
468
469         } else {
470             $logger->info("acq-vl: creating new vandelay record for lineitem $li_id");
471
472             # create a new VL queued record and link it up
473             my $vqbr = Fieldmapper::vandelay::queued_bib_record->new;
474             $vqbr->marc($li->marc);
475             $vqbr->queue($queue->id);
476             $vqbr->bib_source($vandelay->{bib_source} || undef); # avoid ''
477             $vqbr = $e->create_vandelay_queued_bib_record($vqbr) or return $res;
478             push(@vqbr_ids, $vqbr->id);
479
480             # tell the acq record which vandelay record it's linked to
481             $li->queued_record($vqbr->id);
482             $e->update_acq_lineitem($li) or return $res;
483         }
484
485         $mgr->add_vqbr;
486         $mgr->respond;
487         push(@lis, $li);
488     }
489
490     $logger->info("acq-vl: created vandelay records [@vqbr_ids]");
491
492     # we have to commit the transaction now since 
493     # vandelay uses its own transactions.
494     $e->commit;
495
496     return $res if $vl_stat == 1; # queue only
497
498     # Import the bibs via vandelay.  Note: Vandely will 
499     # update acq.lineitem.eg_bib_id on successful import.
500
501     $vandelay->{report_all} = 1;
502     my $ses = OpenSRF::AppSession->create('open-ils.vandelay');
503     my $req = $ses->request(
504         'open-ils.vandelay.bib_record.list.import',
505         $e->authtoken, \@vqbr_ids, $vandelay);
506
507     # pull the responses, noting all that were successfully imported
508     my @success_lis;
509     while (my $resp = $req->recv(timeout => 600)) {
510         my $stat = $resp->content;
511
512         if(!$stat or $U->event_code($stat)) { # import failure
513             $logger->error("acq-vl: error importing vandelay record " . Dumper($stat));
514             next;
515         }
516
517         # "imported" refers to the vqbr id, not the 
518         # success/failure of the vqbr merge attempt
519         next unless $stat->{imported};
520
521         my ($imported) = grep {$_->queued_record eq $stat->{imported}} @lis;
522         my $li_id = $imported->id;
523
524         if ($stat->{no_import}) {
525             $logger->info("acq-vl: acq lineitem $li_id did not import"); 
526
527         } else { # successful import
528
529             push(@success_lis, $li_id);
530             $mgr->add_bib;
531             $mgr->respond;
532             $logger->info("acq-vl: acq lineitem $li_id successfully merged/imported");
533         } 
534     }
535
536     $ses->kill_me;
537     $logger->info("acq-vl: successfully imported lineitems [@success_lis]");
538
539     # add the successfully imported lineitems to the already-imported lineitems
540     push (@{$res->{li_ids}}, @success_lis);
541
542     return $res;
543 }
544
545 # returns event on error, undef on success
546 sub check_import_li_marc_perms {
547     my($mgr, $li_ids) = @_;
548
549     # if there are any order records that are not linked to 
550     # in-db bib records, verify staff has perms to import order records
551     my $order_li = $mgr->editor->search_acq_lineitem(
552         [{id => $li_ids, eg_bib_id => undef}, {limit => 1}], {idlist => 1})->[0];
553
554     if($order_li) {
555         return $mgr->editor->die_event unless 
556             $mgr->editor->allowed('IMPORT_ACQ_LINEITEM_BIB_RECORD');
557     }
558
559     return undef;
560 }
561
562
563 # ----------------------------------------------------------------------------
564 # if all of the lineitem details for this lineitem have 
565 # been received, mark the lineitem as received
566 # returns 1 on non-received, li on received, 0 on error
567 # ----------------------------------------------------------------------------
568
569 sub describe_affected_po {
570     my ($e, $po) = @_;
571
572     my ($enc, $spent) =
573         OpenILS::Application::Acq::Financials::build_price_summary(
574             $e, $po->id
575         );
576
577     +{$po->id => {
578             "state" => $po->state,
579             "amount_encumbered" => $enc,
580             "amount_spent" => $spent
581         }
582     };
583 }
584
585 sub check_lineitem_received {
586     my($mgr, $li_id) = @_;
587
588     my $non_recv = $mgr->editor->search_acq_lineitem_detail(
589         {recv_time => undef, lineitem => $li_id}, {idlist=>1});
590
591     return 1 if @$non_recv;
592
593     my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
594     $li->state('received');
595     return update_lineitem($mgr, $li);
596 }
597
598 sub receive_lineitem {
599     my($mgr, $li_id, $skip_complete_check) = @_;
600     my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
601
602     return 0 unless $li->state eq 'on-order' or $li->state eq 'cancelled'; # sic
603
604     my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
605         {lineitem => $li_id, recv_time => undef}, {idlist => 1});
606
607     for my $lid_id (@$lid_ids) {
608        receive_lineitem_detail($mgr, $lid_id, 1) or return 0; 
609     }
610
611     $mgr->add_li;
612     $li->state('received');
613
614     $li = update_lineitem($mgr, $li) or return 0;
615     $mgr->post_process( sub { create_lineitem_status_events($mgr, $li_id, 'aur.received'); });
616
617     my $po;
618     return 0 unless
619         $skip_complete_check or (
620             $po = check_purchase_order_received($mgr, $li->purchase_order)
621         );
622
623     my $result = {"li" => {$li->id => {"state" => $li->state}}};
624     $result->{"po"} = describe_affected_po($mgr->editor, $po) if ref $po;
625     return $result;
626 }
627
628 sub rollback_receive_lineitem {
629     my($mgr, $li_id) = @_;
630     my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
631
632     my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
633         {lineitem => $li_id, recv_time => {'!=' => undef}}, {idlist => 1});
634
635     for my $lid_id (@$lid_ids) {
636        rollback_receive_lineitem_detail($mgr, $lid_id, 1) or return 0; 
637     }
638
639     $mgr->add_li;
640     $li->state('on-order');
641     return update_lineitem($mgr, $li);
642 }
643
644
645 sub create_lineitem_status_events {
646     my($mgr, $li_id, $hook) = @_;
647
648     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
649     $ses->connect;
650     my $user_reqs = $mgr->editor->search_acq_user_request([
651         {lineitem => $li_id}, 
652         {flesh => 1, flesh_fields => {aur => ['usr']}}
653     ]);
654
655     for my $user_req (@$user_reqs) {
656         my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $user_req->usr->home_ou);
657         $req->recv; 
658     }
659
660     $ses->disconnect;
661     return undef;
662 }
663
664 # ----------------------------------------------------------------------------
665 # Lineitem Detail
666 # ----------------------------------------------------------------------------
667 sub create_lineitem_detail {
668     my($mgr, %args) = @_;
669     my $lid = Fieldmapper::acq::lineitem_detail->new;
670     $lid->$_($args{$_}) for keys %args;
671     $lid->clear_id;
672     $mgr->add_lid;
673     return $mgr->editor->create_acq_lineitem_detail($lid);
674 }
675
676
677 # flesh out any required data with default values where appropriate
678 sub complete_lineitem_detail {
679     my($mgr, $lid) = @_;
680     unless($lid->barcode) {
681         my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_barcode_prefix') || 'ACQ';
682         $lid->barcode($pfx.$lid->id);
683     }
684
685     unless($lid->cn_label) {
686         my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_callnumber_prefix') || 'ACQ';
687         $lid->cn_label($pfx.$lid->id);
688     }
689
690     if(!$lid->location and my $loc = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.default_copy_location')) {
691         $lid->location($loc);
692     }
693
694     $lid->circ_modifier(get_default_circ_modifier($mgr, $lid->owning_lib))
695         unless defined $lid->circ_modifier;
696
697     $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
698     return $lid;
699 }
700
701 sub get_default_circ_modifier {
702     my($mgr, $org) = @_;
703     my $code = $mgr->cache($org, 'def_circ_mod');
704     $code = $U->ou_ancestor_setting_value($org, 'acq.default_circ_modifier') unless defined $code;
705     return $mgr->cache($org, 'def_circ_mod', $code) if defined $code;
706     return undef;
707 }
708
709 sub delete_lineitem_detail {
710     my($mgr, $lid) = @_;
711     $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid) unless ref $lid;
712     return $mgr->editor->delete_acq_lineitem_detail($lid);
713 }
714
715
716 sub receive_lineitem_detail {
717     my($mgr, $lid_id, $skip_complete_check) = @_;
718     my $e = $mgr->editor;
719
720     my $lid = $e->retrieve_acq_lineitem_detail([
721         $lid_id,
722         {   flesh => 1,
723             flesh_fields => {
724                 acqlid => ['fund_debit']
725             }
726         }
727     ]) or return 0;
728
729     return 1 if $lid->recv_time;
730
731     $lid->receiver($e->requestor->id);
732     $lid->recv_time('now');
733     $e->update_acq_lineitem_detail($lid) or return 0;
734
735     if ($lid->eg_copy_id) {
736         my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
737         # only update status if it hasn't already been updated
738         $copy->status(OILS_COPY_STATUS_IN_PROCESS) if $copy->status == OILS_COPY_STATUS_ON_ORDER;
739         $copy->edit_date('now');
740         $copy->editor($e->requestor->id);
741         $copy->creator($e->requestor->id) if $U->ou_ancestor_setting_value(
742             $e->requestor->ws_ou, 'acq.copy_creator_uses_receiver', $e);
743         $e->update_asset_copy($copy) or return 0;
744     }
745
746     $mgr->add_lid;
747
748     return 1 if $skip_complete_check;
749
750     my $li = check_lineitem_received($mgr, $lid->lineitem) or return 0;
751     return 1 if $li == 1; # li not received
752
753     return check_purchase_order_received($mgr, $li->purchase_order) or return 0;
754 }
755
756
757 sub rollback_receive_lineitem_detail {
758     my($mgr, $lid_id) = @_;
759     my $e = $mgr->editor;
760
761     my $lid = $e->retrieve_acq_lineitem_detail([
762         $lid_id,
763         {   flesh => 1,
764             flesh_fields => {
765                 acqlid => ['fund_debit']
766             }
767         }
768     ]) or return 0;
769
770     return 1 unless $lid->recv_time;
771
772     $lid->clear_receiver;
773     $lid->clear_recv_time;
774     $e->update_acq_lineitem_detail($lid) or return 0;
775
776     if ($lid->eg_copy_id) {
777         my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
778         $copy->status(OILS_COPY_STATUS_ON_ORDER);
779         $copy->edit_date('now');
780         $copy->editor($e->requestor->id);
781         $e->update_asset_copy($copy) or return 0;
782     }
783
784     $mgr->add_lid;
785     return $lid;
786 }
787
788 # ----------------------------------------------------------------------------
789 # Lineitem Attr
790 # ----------------------------------------------------------------------------
791 sub set_lineitem_attr {
792     my($mgr, %args) = @_;
793     my $attr_type = $args{attr_type};
794
795     # first, see if it's already set.  May just need to overwrite it
796     my $attr = $mgr->editor->search_acq_lineitem_attr({
797         lineitem => $args{lineitem},
798         attr_type => $args{attr_type},
799         attr_name => $args{attr_name}
800     })->[0];
801
802     if($attr) {
803         $attr->attr_value($args{attr_value});
804         return $attr if $mgr->editor->update_acq_lineitem_attr($attr);
805         return undef;
806
807     } else {
808
809         $attr = Fieldmapper::acq::lineitem_attr->new;
810         $attr->$_($args{$_}) for keys %args;
811         
812         unless($attr->definition) {
813             my $find = "search_acq_$attr_type";
814             my $attr_def_id = $mgr->editor->$find({code => $attr->attr_name}, {idlist=>1})->[0] or return 0;
815             $attr->definition($attr_def_id);
816         }
817         return $mgr->editor->create_acq_lineitem_attr($attr);
818     }
819 }
820
821 # ----------------------------------------------------------------------------
822 # Lineitem Debits
823 # ----------------------------------------------------------------------------
824 sub create_lineitem_debits {
825     my ($mgr, $li, $options) = @_;
826     $options ||= {};
827     my $dry_run = $options->{dry_run};
828
829     unless($li->estimated_unit_price) {
830         $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
831         $mgr->editor->rollback;
832         return 0;
833     }
834
835     unless($li->provider) {
836         $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
837         $mgr->editor->rollback;
838         return 0;
839     }
840
841     my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
842         {lineitem => $li->id}, 
843         {idlist=>1}
844     );
845
846     if (@$lid_ids == 0 and !$options->{zero_copy_activate}) {
847         $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_COPIES', payload => $li->id));
848         $mgr->editor->rollback;
849         return 0;
850     }
851
852     for my $lid_id (@$lid_ids) {
853
854         my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
855             $lid_id,
856             {   flesh => 1, 
857                 flesh_fields => {acqlid => ['fund']}
858             }
859         ]);
860
861         create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
862     }
863
864     return 1;
865 }
866
867
868 # flesh li->provider
869 # flesh lid->fund
870 sub create_lineitem_detail_debit {
871     my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
872
873     # don't create the debit if one already exists
874     return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
875
876     my $li_id = ref($li) ? $li->id : $li;
877
878     unless(ref $li and ref $li->provider) {
879        $li = $mgr->editor->retrieve_acq_lineitem([
880             $li_id,
881             {   flesh => 1,
882                 flesh_fields => {jub => ['provider']},
883             }
884         ]);
885     }
886
887     if(ref $lid) {
888         $lid->fund($mgr->editor->retrieve_acq_fund($lid->fund)) unless(ref $lid->fund);
889     } else {
890         $lid = $mgr->editor->retrieve_acq_lineitem_detail([
891             $lid,
892             {   flesh => 1, 
893                 flesh_fields => {acqlid => ['fund']}
894             }
895         ]);
896     }
897
898     unless ($lid->fund) {
899         $mgr->editor->event(
900             new OpenILS::Event("ACQ_FUND_NOT_FOUND") # close enough
901         );
902         return 0;
903     }
904
905     my $amount = $li->estimated_unit_price;
906     if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
907
908         # At Fund debit creation time, translate into the currency of the fund
909         # TODO: org setting to disable automatic currency conversion at debit create time?
910
911         $amount = $mgr->editor->json_query({
912             from => [
913                 'acq.exchange_ratio', 
914                 $li->provider->currency_type, # source currency
915                 $lid->fund->currency_type, # destination currency
916                 $li->estimated_unit_price # source amount
917             ]
918         })->[0]->{'acq.exchange_ratio'};
919     }
920
921     my $debit = create_fund_debit(
922         $mgr, 
923         $dry_run,
924         fund => $lid->fund->id,
925         origin_amount => $li->estimated_unit_price,
926         origin_currency_type => $li->provider->currency_type,
927         amount => $amount
928     ) or return 0;
929
930     $lid->fund_debit($debit->id);
931     $lid->fund($lid->fund->id);
932     $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
933     return $debit;
934 }
935
936
937 __PACKAGE__->register_method(
938     "method" => "fund_exceeds_balance_percent_api",
939     "api_name" => "open-ils.acq.fund.check_balance_percentages",
940     "signature" => {
941         "desc" => q/Determine whether a given fund exceeds its defined
942             "balance stop and warning percentages"/,
943         "params" => [
944             {"desc" => "Authentication token", "type" => "string"},
945             {"desc" => "Fund ID", "type" => "number"},
946             {"desc" => "Theoretical debit amount (optional)",
947                 "type" => "number"}
948         ],
949         "return" => {"desc" => q/An array of two values, for stop and warning,
950             in that order: 1 if fund exceeds that balance percentage, else 0/}
951     }
952 );
953
954 sub fund_exceeds_balance_percent_api {
955     my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
956
957     $debit_amount ||= 0;
958
959     my $e = new_editor("authtoken" => $auth);
960     return $e->die_event unless $e->checkauth;
961
962     my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
963     return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
964
965     my $result = [
966         fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
967         fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
968     ];
969
970     $e->disconnect;
971     return $result;
972 }
973
974 sub fund_exceeds_balance_percent {
975     my ($fund, $debit_amount, $e, $which) = @_;
976
977     my ($method_name, $event_name) = @{{
978         "warning" => [
979             "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
980         ],
981         "stop" => [
982             "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
983         ]
984     }->{$which}};
985
986     if ($fund->$method_name) {
987         my $balance =
988             $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
989         my $allocations =
990             $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
991
992         $balance = ($balance) ? $balance->amount : 0;
993         $allocations = ($allocations) ? $allocations->amount : 0;
994
995         if ( 
996             $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
997             ((($allocations - $balance + $debit_amount) / $allocations) * 100) > $fund->$method_name
998         ) {
999             $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
1000             $e->event(
1001                 new OpenILS::Event(
1002                     $event_name,
1003                     "payload" => {
1004                         "fund" => $fund, "debit_amount" => $debit_amount
1005                     }
1006                 )
1007             );
1008             return 1;
1009         }
1010     }
1011     return 0;
1012 }
1013
1014 # ----------------------------------------------------------------------------
1015 # Fund Debit
1016 # ----------------------------------------------------------------------------
1017 sub create_fund_debit {
1018     my($mgr, $dry_run, %args) = @_;
1019
1020     # Verify the fund is not being spent beyond the hard stop amount
1021     my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
1022
1023     return 0 if
1024         fund_exceeds_balance_percent(
1025             $fund, $args{"amount"}, $mgr->editor, "stop"
1026         );
1027     return 0 if
1028         $dry_run and fund_exceeds_balance_percent(
1029             $fund, $args{"amount"}, $mgr->editor, "warning"
1030         );
1031
1032     my $debit = Fieldmapper::acq::fund_debit->new;
1033     $debit->debit_type('purchase');
1034     $debit->encumbrance('t');
1035     $debit->$_($args{$_}) for keys %args;
1036     $debit->clear_id;
1037     $mgr->add_debit($debit->amount);
1038     return $mgr->editor->create_acq_fund_debit($debit);
1039 }
1040
1041
1042 # ----------------------------------------------------------------------------
1043 # Picklist
1044 # ----------------------------------------------------------------------------
1045 sub create_picklist {
1046     my($mgr, %args) = @_;
1047     my $picklist = Fieldmapper::acq::picklist->new;
1048     $picklist->creator($mgr->editor->requestor->id);
1049     $picklist->owner($picklist->creator);
1050     $picklist->editor($picklist->creator);
1051     $picklist->create_time('now');
1052     $picklist->edit_time('now');
1053     $picklist->org_unit($mgr->editor->requestor->ws_ou);
1054     $picklist->owner($mgr->editor->requestor->id);
1055     $picklist->$_($args{$_}) for keys %args;
1056     $picklist->clear_id;
1057     $mgr->picklist($picklist);
1058     return $mgr->editor->create_acq_picklist($picklist);
1059 }
1060
1061 sub update_picklist {
1062     my($mgr, $picklist) = @_;
1063     $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1064     $picklist->edit_time('now');
1065     $picklist->editor($mgr->editor->requestor->id);
1066     if ($mgr->editor->update_acq_picklist($picklist)) {
1067         $picklist = $mgr->editor->retrieve_acq_picklist($mgr->editor->data);
1068         $mgr->picklist($picklist);
1069         return $picklist;
1070     } else {
1071         return undef;
1072     }
1073 }
1074
1075 sub delete_picklist {
1076     my($mgr, $picklist) = @_;
1077     $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1078
1079     # delete all 'new' lineitems
1080     my $li_ids = $mgr->editor->search_acq_lineitem(
1081         {
1082             picklist => $picklist->id,
1083             "-or" => {state => "new", purchase_order => undef}
1084         },
1085         {idlist => 1}
1086     );
1087     for my $li_id (@$li_ids) {
1088         my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1089         return 0 unless delete_lineitem($mgr, $li);
1090         $mgr->respond;
1091     }
1092
1093     # detach all non-'new' lineitems
1094     $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
1095     for my $li_id (@$li_ids) {
1096         my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1097         $li->clear_picklist;
1098         return 0 unless update_lineitem($mgr, $li);
1099         $mgr->respond;
1100     }
1101
1102     # remove any picklist-specific object perms
1103     my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
1104     for my $op (@$ops) {
1105         return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
1106     }
1107
1108     return $mgr->editor->delete_acq_picklist($picklist);
1109 }
1110
1111 # ----------------------------------------------------------------------------
1112 # Purchase Order
1113 # ----------------------------------------------------------------------------
1114 sub update_purchase_order {
1115     my($mgr, $po) = @_;
1116     $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
1117     $po->editor($mgr->editor->requestor->id);
1118     $po->edit_time('now');
1119     $mgr->purchase_order($po);
1120     return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
1121         if $mgr->editor->update_acq_purchase_order($po);
1122     return undef;
1123 }
1124
1125 sub create_purchase_order {
1126     my($mgr, %args) = @_;
1127
1128     # verify the chosen provider is still active
1129     my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
1130     unless($U->is_true($provider->active)) {
1131         $logger->error("provider is not active.  cannot create PO");
1132         $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
1133         return 0;
1134     }
1135
1136     my $po = Fieldmapper::acq::purchase_order->new;
1137     $po->creator($mgr->editor->requestor->id);
1138     $po->editor($mgr->editor->requestor->id);
1139     $po->owner($mgr->editor->requestor->id);
1140     $po->edit_time('now');
1141     $po->create_time('now');
1142     $po->state('pending');
1143     $po->ordering_agency($mgr->editor->requestor->ws_ou);
1144     $po->$_($args{$_}) for keys %args;
1145     $po->clear_id;
1146     $mgr->purchase_order($po);
1147     return $mgr->editor->create_acq_purchase_order($po);
1148 }
1149
1150 # ----------------------------------------------------------------------------
1151 # if all of the lineitems for this PO are received,
1152 # mark the PO as received
1153 # ----------------------------------------------------------------------------
1154 sub check_purchase_order_received {
1155     my($mgr, $po_id) = @_;
1156
1157     my $non_recv_li = $mgr->editor->search_acq_lineitem(
1158         {   purchase_order => $po_id,
1159             state => {'!=' => 'received'}
1160         }, {idlist=>1});
1161
1162     my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
1163     return $po if @$non_recv_li;
1164
1165     $po->state('received');
1166     return update_purchase_order($mgr, $po);
1167 }
1168
1169
1170 # ----------------------------------------------------------------------------
1171 # Bib, Callnumber, and Copy data
1172 # ----------------------------------------------------------------------------
1173
1174 sub create_lineitem_assets {
1175     my($mgr, $li_id) = @_;
1176     my $evt;
1177
1178     my $li = $mgr->editor->retrieve_acq_lineitem([
1179         $li_id,
1180         {   flesh => 1,
1181             flesh_fields => {jub => ['purchase_order', 'attributes']}
1182         }
1183     ]) or return 0;
1184
1185     # note: at this point, the bib record this LI links to should already be created
1186
1187     # -----------------------------------------------------------------
1188     # The lineitem is going live, promote user request holds to real holds
1189     # -----------------------------------------------------------------
1190     promote_lineitem_holds($mgr, $li) or return 0;
1191
1192     my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
1193
1194     # -----------------------------------------------------------------
1195     # for each lineitem_detail, create the volume if necessary, create 
1196     # a copy, and link them all together.
1197     # -----------------------------------------------------------------
1198     my $first_cn;
1199     for my $lid_id (@{$li_details}) {
1200
1201         my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
1202         next if $lid->eg_copy_id;
1203
1204         # use the same callnumber label for all items within this lineitem
1205         $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
1206
1207         # apply defaults if necessary
1208         return 0 unless complete_lineitem_detail($mgr, $lid);
1209
1210         $first_cn = $lid->cn_label unless $first_cn;
1211
1212         my $org = $lid->owning_lib;
1213         my $label = $lid->cn_label;
1214         my $bibid = $li->eg_bib_id;
1215
1216         my $volume = $mgr->cache($org, "cn.$bibid.$label");
1217         unless($volume) {
1218             $volume = create_volume($mgr, $li, $lid) or return 0;
1219             $mgr->cache($org, "cn.$bibid.$label", $volume);
1220         }
1221         create_copy($mgr, $volume, $lid, $li) or return 0;
1222     }
1223
1224     return { li => $li };
1225 }
1226
1227 sub create_volume {
1228     my($mgr, $li, $lid) = @_;
1229
1230     my ($volume, $evt) = 
1231         OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1232             $mgr->editor, 
1233             $lid->cn_label, 
1234             $li->eg_bib_id, 
1235             $lid->owning_lib
1236         );
1237
1238     if($evt) {
1239         $mgr->editor->event($evt);
1240         return 0;
1241     }
1242
1243     return $volume;
1244 }
1245
1246 sub create_copy {
1247     my($mgr, $volume, $lid, $li) = @_;
1248     my $copy = Fieldmapper::asset::copy->new;
1249     $copy->isnew(1);
1250     $copy->loan_duration(2);
1251     $copy->fine_level(2);
1252     $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1253     $copy->barcode($lid->barcode);
1254     $copy->location($lid->location);
1255     $copy->call_number($volume->id);
1256     $copy->circ_lib($volume->owning_lib);
1257     $copy->circ_modifier($lid->circ_modifier);
1258
1259     # AKA list price.  We might need a $li->list_price field since 
1260     # estimated price is not necessarily the same as list price
1261     $copy->price($li->estimated_unit_price); 
1262
1263     my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1264     if($evt) {
1265         $mgr->editor->event($evt);
1266         return 0;
1267     }
1268
1269     $mgr->add_copy;
1270     $lid->eg_copy_id($copy->id);
1271     $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1272 }
1273
1274
1275
1276
1277
1278
1279 # ----------------------------------------------------------------------------
1280 # Workflow: Build a selection list from a Z39.50 search
1281 # ----------------------------------------------------------------------------
1282
1283 __PACKAGE__->register_method(
1284     method => 'zsearch',
1285     api_name => 'open-ils.acq.picklist.search.z3950',
1286     stream => 1,
1287     signature => {
1288         desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1289         params => [
1290             {desc => 'Authentication token', type => 'string'},
1291             {desc => 'Search definition', type => 'object'},
1292             {desc => 'Picklist name, optional', type => 'string'},
1293         ]
1294     }
1295 );
1296
1297 sub zsearch {
1298     my($self, $conn, $auth, $search, $name, $options) = @_;
1299     my $e = new_editor(authtoken=>$auth);
1300     return $e->event unless $e->checkauth;
1301     return $e->event unless $e->allowed('CREATE_PICKLIST');
1302
1303     $search->{limit} ||= 10;
1304     $options ||= {};
1305
1306     my $ses = OpenSRF::AppSession->create('open-ils.search');
1307     my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1308
1309     my $first = 1;
1310     my $picklist;
1311     my $mgr;
1312     while(my $resp = $req->recv(timeout=>60)) {
1313
1314         if($first) {
1315             my $e = new_editor(requestor=>$e->requestor, xact=>1);
1316             $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1317             $picklist = zsearch_build_pl($mgr, $name);
1318             $first = 0;
1319         }
1320
1321         my $result = $resp->content;
1322         my $count = $result->{count} || 0;
1323         $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1324
1325         for my $rec (@{$result->{records}}) {
1326
1327             my $li = create_lineitem($mgr, 
1328                 picklist => $picklist->id,
1329                 source_label => $result->{service},
1330                 marc => $rec->{marcxml},
1331                 eg_bib_id => $rec->{bibid}
1332             );
1333
1334             if($$options{respond_li}) {
1335                 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1336                     if $$options{flesh_attrs};
1337                 $li->clear_marc if $$options{clear_marc};
1338                 $mgr->respond(lineitem => $li);
1339             } else {
1340                 $mgr->respond;
1341             }
1342         }
1343     }
1344
1345     $mgr->editor->commit;
1346     return $mgr->respond_complete;
1347 }
1348
1349 sub zsearch_build_pl {
1350     my($mgr, $name) = @_;
1351     $name ||= '';
1352
1353     my $picklist = $mgr->editor->search_acq_picklist({
1354         owner => $mgr->editor->requestor->id, 
1355         name => $name
1356     })->[0];
1357
1358     if($name eq '' and $picklist) {
1359         return 0 unless delete_picklist($mgr, $picklist);
1360         $picklist = undef;
1361     }
1362
1363     return update_picklist($mgr, $picklist) if $picklist;
1364     return create_picklist($mgr, name => $name);
1365 }
1366
1367
1368 # ----------------------------------------------------------------------------
1369 # Workflow: Build a selection list / PO by importing a batch of MARC records
1370 # ----------------------------------------------------------------------------
1371
1372 __PACKAGE__->register_method(
1373     method   => 'upload_records',
1374     api_name => 'open-ils.acq.process_upload_records',
1375     stream   => 1,
1376     max_chunk_count => 1
1377 );
1378
1379 sub upload_records {
1380     my($self, $conn, $auth, $key, $args) = @_;
1381     $args ||= {};
1382
1383     my $e = new_editor(authtoken => $auth, xact => 1);
1384     return $e->die_event unless $e->checkauth;
1385     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1386
1387     my $cache = OpenSRF::Utils::Cache->new;
1388
1389     my $data = $cache->get_cache("vandelay_import_spool_$key");
1390     my $filename        = $data->{path};
1391     my $provider        = $args->{provider};
1392     my $picklist        = $args->{picklist};
1393     my $create_po       = $args->{create_po};
1394     my $activate_po     = $args->{activate_po};
1395     my $vandelay        = $args->{vandelay};
1396     my $ordering_agency = $args->{ordering_agency} || $e->requestor->ws_ou;
1397     my $fiscal_year     = $args->{fiscal_year};
1398
1399     # if the user provides no fiscal year, find the
1400     # current fiscal year for the ordering agency.
1401     $fiscal_year ||= $U->simplereq(
1402         'open-ils.acq',
1403         'open-ils.acq.org_unit.current_fiscal_year',
1404         $auth,
1405         $ordering_agency
1406     );
1407
1408     my $po;
1409     my $evt;
1410
1411     unless(-r $filename) {
1412         $logger->error("unable to read MARC file $filename");
1413         $e->rollback;
1414         return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1415     }
1416
1417     $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1418
1419     if($picklist) {
1420         $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1421         if($picklist->owner != $e->requestor->id) {
1422             return $e->die_event unless 
1423                 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1424         }
1425         $mgr->picklist($picklist);
1426     }
1427
1428     if($create_po) {
1429         return $e->die_event unless 
1430             $e->allowed('CREATE_PURCHASE_ORDER', $ordering_agency);
1431
1432         $po = create_purchase_order($mgr, 
1433             ordering_agency => $ordering_agency,
1434             provider => $provider->id,
1435             state => 'pending' # will be updated later if activated
1436         ) or return $mgr->editor->die_event;
1437     }
1438
1439     $logger->info("acq processing MARC file=$filename");
1440
1441     my $batch = new MARC::Batch ('USMARC', $filename);
1442     $batch->strict_off;
1443
1444     my $count = 0;
1445     my @li_list;
1446
1447     while(1) {
1448
1449         my ($err, $xml, $r);
1450         $count++;
1451
1452         try {
1453             $r = $batch->next;
1454         } catch Error with {
1455             $err = shift;
1456             $logger->warn("Proccessing of record $count in set $key failed with error $err.  Skipping this record");
1457         };
1458
1459         next if $err;
1460         last unless $r;
1461
1462         try {
1463             $xml = clean_marc($r);
1464         } catch Error with {
1465             $err = shift;
1466             $logger->warn("Proccessing XML of record $count in set $key failed with error $err.  Skipping this record");
1467         };
1468
1469         next if $err or not $xml;
1470
1471         my %args = (
1472             source_label => $provider->code,
1473             provider => $provider->id,
1474             marc => $xml,
1475         );
1476
1477         $args{picklist} = $picklist->id if $picklist;
1478         if($po) {
1479             $args{purchase_order} = $po->id;
1480             $args{state} = 'pending-order';
1481         }
1482
1483         my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1484         $mgr->respond;
1485         $li->provider($provider); # flesh it, we'll need it later
1486
1487         import_lineitem_details($mgr, $ordering_agency, $li, $fiscal_year) 
1488             or return $mgr->editor->die_event;
1489         $mgr->respond;
1490
1491         push(@li_list, $li->id);
1492         $mgr->respond;
1493     }
1494
1495     if ($po) {
1496         $evt = extract_po_name($mgr, $po, \@li_list);
1497         return $evt if $evt;
1498     }
1499
1500     $e->commit;
1501     unlink($filename);
1502     $cache->delete_cache('vandelay_import_spool_' . $key);
1503
1504     if ($po and $activate_po) {
1505         my $die_event = activate_purchase_order_impl($mgr, $po->id, $vandelay);
1506         return $die_event if $die_event;
1507
1508     } elsif ($vandelay) {
1509         $vandelay->{new_rec_perm} = 'IMPORT_ACQ_LINEITEM_BIB_RECORD_UPLOAD';
1510         create_lineitem_list_assets($mgr, \@li_list, $vandelay, 
1511             !$vandelay->{create_assets}) or return $e->die_event;
1512     }
1513
1514     return $mgr->respond_complete;
1515 }
1516
1517 # see if the PO name is encoded in the newly imported records
1518 sub extract_po_name {
1519     my ($mgr, $po, $li_ids) = @_;
1520     my $e = $mgr->editor;
1521
1522     # find the first instance of the name
1523     my $attr = $e->search_acq_lineitem_attr([
1524         {   lineitem => $li_ids,
1525             attr_type => 'lineitem_provider_attr_definition',
1526             attr_name => 'purchase_order'
1527         }, {
1528             order_by => {aqlia => 'id'},
1529             limit => 1
1530         }
1531     ])->[0] or return undef;
1532
1533     my $name = $attr->attr_value;
1534
1535     # see if another PO already has the name, provider, and org
1536     my $existing = $e->search_acq_purchase_order(
1537         {   name => $name,
1538             ordering_agency => $po->ordering_agency,
1539             provider => $po->provider
1540         },
1541         {idlist => 1}
1542     )->[0];
1543
1544     # if a PO exists with the same name (and provider/org)
1545     # tack the po ID into the name to differentiate
1546     $name = sprintf("$name (%s)", $po->id) if $existing;
1547
1548     $logger->info("Extracted PO name: $name");
1549
1550     $po->name($name);
1551     update_purchase_order($mgr, $po) or return $e->die_event;
1552     return undef;
1553 }
1554
1555 sub import_lineitem_details {
1556     my($mgr, $ordering_agency, $li, $fiscal_year) = @_;
1557
1558     my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1559     return 1 unless @$holdings;
1560     my $org_path = $U->get_org_ancestors($ordering_agency);
1561     $org_path = [ reverse (@$org_path) ];
1562     my $price;
1563
1564
1565     my $idx = 1;
1566     while(1) {
1567         # create a lineitem detail for each copy in the data
1568
1569         my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx, $fiscal_year);
1570         last unless defined $compiled;
1571         return 0 unless $compiled;
1572
1573         # this takes the price of the last copy and uses it as the lineitem price
1574         # need to determine if a given record would include different prices for the same item
1575         $price = $$compiled{estimated_price};
1576
1577         last unless $$compiled{quantity};
1578
1579         for(1..$$compiled{quantity}) {
1580             my $lid = create_lineitem_detail(
1581                 $mgr, 
1582                 lineitem        => $li->id,
1583                 owning_lib      => $$compiled{owning_lib},
1584                 cn_label        => $$compiled{call_number},
1585                 fund            => $$compiled{fund},
1586                 circ_modifier   => $$compiled{circ_modifier},
1587                 note            => $$compiled{note},
1588                 location        => $$compiled{copy_location},
1589                 collection_code => $$compiled{collection_code},
1590                 barcode         => $$compiled{barcode}
1591             ) or return 0;
1592         }
1593
1594         $mgr->respond;
1595         $idx++;
1596     }
1597
1598     $li->estimated_unit_price($price);
1599     update_lineitem($mgr, $li) or return 0;
1600     return 1;
1601 }
1602
1603 # return hash on success, 0 on error, undef on no more holdings
1604 sub extract_lineitem_detail_data {
1605     my($mgr, $org_path, $holdings, $index, $fiscal_year) = @_;
1606
1607     my @data_list = grep { $_->{holding} eq $index } @$holdings;
1608     return undef unless @data_list;
1609
1610     my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1611     my $base_org = $$org_path[0];
1612
1613     my $killme = sub {
1614         my $msg = shift;
1615         $logger->error("Item import extraction error: $msg");
1616         $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1617         $mgr->editor->rollback;
1618         $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1619         return 0;
1620     };
1621
1622     # ---------------------------------------------------------------------
1623     # Fund
1624     if(my $code = $compiled{fund_code}) {
1625
1626         my $fund = $mgr->cache($base_org, "fund.$code");
1627         unless($fund) {
1628             # search up the org tree for the most appropriate fund
1629             for my $org (@$org_path) {
1630                 $fund = $mgr->editor->search_acq_fund(
1631                     {org => $org, code => $code, year => $fiscal_year}, {idlist => 1})->[0];
1632                 last if $fund;
1633             }
1634         }
1635         return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1636         $compiled{fund} = $fund;
1637         $mgr->cache($base_org, "fund.$code", $fund);
1638     }
1639
1640
1641     # ---------------------------------------------------------------------
1642     # Owning lib
1643     if(my $sn = $compiled{owning_lib}) {
1644         my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1645             $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1646         return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1647         $compiled{owning_lib} = $org_id;
1648         $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1649     }
1650
1651
1652     # ---------------------------------------------------------------------
1653     # Circ Modifier
1654     my $code = $compiled{circ_modifier};
1655
1656     if(defined $code) {
1657
1658         # verify this is a valid circ modifier
1659         return $killme->("invlalid circ_modifier $code") unless 
1660             defined $mgr->cache($base_org, "mod.$code") or 
1661             $mgr->editor->retrieve_config_circ_modifier($code);
1662
1663             # if valid, cache for future tests
1664             $mgr->cache($base_org, "mod.$code", $code);
1665
1666     } else {
1667         $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1668     }
1669
1670
1671     # ---------------------------------------------------------------------
1672     # Shelving Location
1673     if( my $name = $compiled{copy_location}) {
1674
1675         my $cp_base_org = $base_org;
1676
1677         if ($compiled{owning_lib}) {
1678             # start looking for copy locations at the copy 
1679             # owning lib instaed of the upload context org
1680             $cp_base_org = $compiled{owning_lib};
1681         }
1682
1683         my $loc = $mgr->cache($cp_base_org, "copy_loc.$name");
1684         unless($loc) {
1685             my $org = $cp_base_org;
1686             while ($org) {
1687                 $loc = $mgr->editor->search_asset_copy_location(
1688                     {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1689                 last if $loc;
1690                 $org = $mgr->editor->retrieve_actor_org_unit($org)->parent_ou;
1691             }
1692         }
1693         return $killme->("Invalid copy location $name") unless $loc;
1694         $compiled{copy_location} = $loc;
1695         $mgr->cache($cp_base_org, "copy_loc.$name", $loc);
1696     }
1697
1698     return \%compiled;
1699 }
1700
1701
1702
1703 # ----------------------------------------------------------------------------
1704 # Workflow: Given an existing purchase order, import/create the bibs, 
1705 # callnumber and copy objects
1706 # ----------------------------------------------------------------------------
1707
1708 __PACKAGE__->register_method(
1709     method => 'create_po_assets',
1710     api_name    => 'open-ils.acq.purchase_order.assets.create',
1711     signature => {
1712         desc => q/Creates assets for each lineitem in the purchase order/,
1713         params => [
1714             {desc => 'Authentication token', type => 'string'},
1715             {desc => 'The purchase order id', type => 'number'},
1716         ],
1717         return => {desc => 'Streams a total versus completed counts object, event on error'}
1718     },
1719     max_chunk_count => 1
1720 );
1721
1722 sub create_po_assets {
1723     my($self, $conn, $auth, $po_id, $args) = @_;
1724     $args ||= {};
1725
1726     my $e = new_editor(authtoken=>$auth, xact=>1);
1727     return $e->die_event unless $e->checkauth;
1728     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1729
1730     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1731
1732     my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1733
1734     # it's ugly, but it's fast.  Get the total count of lineitem detail objects to process
1735     my $lid_total = $e->json_query({
1736         select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] }, 
1737         from => {
1738             acqlid => {
1739                 jub => {
1740                     fkey => 'lineitem', 
1741                     field => 'id', 
1742                     join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1743                 }
1744             }
1745         }, 
1746         where => {'+acqpo' => {id => $po_id}}
1747     })->[0]->{id};
1748
1749     $mgr->total(scalar(@$li_ids) + $lid_total);
1750
1751     create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay}) 
1752         or return $e->die_event;
1753
1754     $e->xact_begin;
1755     update_purchase_order($mgr, $po) or return $e->die_event;
1756     $e->commit;
1757
1758     return $mgr->respond_complete;
1759 }
1760
1761
1762
1763 __PACKAGE__->register_method(
1764     method    => 'create_purchase_order_api',
1765     api_name  => 'open-ils.acq.purchase_order.create',
1766     signature => {
1767         desc   => 'Creates a new purchase order',
1768         params => [
1769             {desc => 'Authentication token', type => 'string'},
1770             {desc => 'purchase_order to create', type => 'object'}
1771         ],
1772         return => {desc => 'The purchase order id, Event on failure'}
1773     },
1774     max_chunk_count => 1
1775 );
1776
1777 sub create_purchase_order_api {
1778     my($self, $conn, $auth, $po, $args) = @_;
1779     $args ||= {};
1780
1781     my $e = new_editor(xact=>1, authtoken=>$auth);
1782     return $e->die_event unless $e->checkauth;
1783     return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1784     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1785
1786     # create the PO
1787     my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1788     $pargs{provider}            = $po->provider            if $po->provider;
1789     $pargs{ordering_agency}     = $po->ordering_agency     if $po->ordering_agency;
1790     $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1791     my $vandelay = $args->{vandelay};
1792         
1793     $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1794
1795     my $li_ids = $$args{lineitems};
1796
1797     if($li_ids) {
1798
1799         for my $li_id (@$li_ids) { 
1800
1801             my $li = $e->retrieve_acq_lineitem([
1802                 $li_id,
1803                 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1804             ]) or return $e->die_event;
1805
1806             return $e->die_event(
1807                 new OpenILS::Event(
1808                     "BAD_PARAMS", payload => $li,
1809                         note => "acq.lineitem #" . $li->id .
1810                         ": purchase_order #" . $li->purchase_order
1811                 )
1812             ) if $li->purchase_order;
1813
1814             $li->provider($po->provider);
1815             $li->purchase_order($po->id);
1816             $li->state('pending-order');
1817             update_lineitem($mgr, $li) or return $e->die_event;
1818             $mgr->respond;
1819         }
1820     }
1821
1822     # see if we have a PO name encoded in any of our lineitems
1823     my $evt = extract_po_name($mgr, $po, $li_ids);
1824     return $evt if $evt;
1825
1826     # commit before starting the asset creation
1827     $e->xact_commit;
1828
1829     if($li_ids) {
1830
1831         if ($vandelay) {
1832             create_lineitem_list_assets(
1833                 $mgr, $li_ids, $vandelay, !$$args{create_assets}) 
1834                 or return $e->die_event;
1835         }
1836
1837         $e->xact_begin;
1838         apply_default_copies($mgr, $po) or return $e->die_event;
1839         $e->xact_commit;
1840     }
1841
1842     return $mgr->respond_complete;
1843 }
1844
1845 # !transaction must be managed by the caller
1846 # creates the default number of copies for each lineitem on the PO.
1847 # when a LI already has copies attached, no default copies are added.
1848 # without li_id, all lineitems are checked/applied
1849 # returns 1 on success, 0 on error
1850 sub apply_default_copies {
1851     my ($mgr, $po, $li_id) = @_;
1852
1853     my $e = $mgr->editor;
1854
1855     my $provider = ref($po->provider) ? $po->provider :
1856         $e->retrieve_acq_provider($po->provider);
1857
1858     my $copy_count = $provider->default_copy_count || return 1;
1859     
1860     $logger->info("Applying $copy_count default copies for PO ".$po->id);
1861
1862     my $li_ids = $li_id ? [$li_id] : 
1863         $e->search_acq_lineitem({
1864             purchase_order => $po->id,
1865             cancel_reason => undef
1866         }, 
1867         {idlist => 1}
1868     );
1869     
1870     for my $li_id (@$li_ids) {
1871
1872         my $lid_ids = $e->search_acq_lineitem_detail(
1873             {lineitem => $li_id}, {idlist => 1});
1874
1875         # do not apply default copies when copies already exist
1876         next if @$lid_ids;
1877
1878         for (1 .. $copy_count) {
1879             create_lineitem_detail($mgr, 
1880                 lineitem => $li_id,
1881                 owning_lib => $e->requestor->ws_ou
1882             ) or return 0;
1883         }
1884     }
1885
1886     return 1;
1887 }
1888
1889
1890
1891 __PACKAGE__->register_method(
1892     method   => 'update_lineitem_fund_batch',
1893     api_name => 'open-ils.acq.lineitem.fund.update.batch',
1894     stream   => 1,
1895     signature => { 
1896         desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1897     }
1898 );
1899
1900 sub update_lineitem_fund_batch {
1901     my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1902     my $e = new_editor(xact=>1, authtoken=>$auth);
1903     return $e->die_event unless $e->checkauth;
1904     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1905     for my $li_id (@$li_ids) {
1906         my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1907         return $evt if $evt;
1908         my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1909         $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1910         $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1911         return $evt if $evt;
1912         $mgr->add_li;
1913         $mgr->respond;
1914     }
1915     $e->commit;
1916     return $mgr->respond_complete;
1917 }
1918
1919
1920
1921 __PACKAGE__->register_method(
1922     method    => 'lineitem_detail_CUD_batch_api',
1923     api_name  => 'open-ils.acq.lineitem_detail.cud.batch',
1924     stream    => 1,
1925     signature => {
1926         desc   => q/Creates a new purchase order line item detail. / .
1927                   q/Additionally creates the associated fund_debit/,
1928         params => [
1929             {desc => 'Authentication token', type => 'string'},
1930             {desc => 'List of lineitem_details to create', type => 'array'},
1931             {desc => 'Create Debits.  Used for creating post-po-asset-creation debits', type => 'bool'},
1932         ],
1933         return => {desc => 'Streaming response of current position in the array'}
1934     }
1935 );
1936
1937 __PACKAGE__->register_method(
1938     method    => 'lineitem_detail_CUD_batch_api',
1939     api_name  => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1940     stream    => 1,
1941     signature => { 
1942         desc => q/
1943             Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1944             In dry_run mode, updated fund_debit's the exceed the warning
1945             percent return an event.  
1946         /
1947     }
1948 );
1949
1950
1951 sub lineitem_detail_CUD_batch_api {
1952     my($self, $conn, $auth, $li_details, $create_debits) = @_;
1953     my $e = new_editor(xact=>1, authtoken=>$auth);
1954     return $e->die_event unless $e->checkauth;
1955     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1956     my $dry_run = ($self->api_name =~ /dry_run/o);
1957     my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1958     return $evt if $evt;
1959     $e->commit;
1960     return $mgr->respond_complete;
1961 }
1962
1963
1964 sub lineitem_detail_CUD_batch {
1965     my($mgr, $li_details, $create_debits, $dry_run) = @_;
1966
1967     $mgr->total(scalar(@$li_details));
1968     my $e = $mgr->editor;
1969     
1970     my $li;
1971     my %li_cache;
1972     my $fund_cache = {};
1973     my $evt;
1974
1975     for my $lid (@$li_details) {
1976
1977         unless($li = $li_cache{$lid->lineitem}) {
1978             ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1979             return $evt if $evt;
1980         }
1981
1982         if($lid->isnew) {
1983             $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1984             if($create_debits) {
1985                 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1986                 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1987                 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1988             }
1989
1990         } elsif($lid->ischanged) {
1991             return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1992
1993         } elsif($lid->isdeleted) {
1994             delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1995         }
1996
1997         $mgr->respond(li => $li);
1998         $li_cache{$lid->lineitem} = $li;
1999     }
2000
2001     return undef;
2002 }
2003
2004 sub handle_changed_lid {
2005     my($e, $lid, $dry_run, $fund_cache) = @_;
2006
2007     my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
2008
2009     # updating the fund, so update the debit
2010     if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
2011
2012         my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
2013         my $new_fund = $$fund_cache{$lid->fund} = 
2014             $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
2015
2016         # check the thresholds
2017         return $e->die_event if
2018             fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
2019         return $e->die_event if $dry_run and 
2020             fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
2021
2022         $debit->fund($new_fund->id);
2023         $e->update_acq_fund_debit($debit) or return $e->die_event;
2024     }
2025
2026     $e->update_acq_lineitem_detail($lid) or return $e->die_event;
2027     return undef;
2028 }
2029
2030
2031 __PACKAGE__->register_method(
2032     method   => 'receive_po_api',
2033     api_name => 'open-ils.acq.purchase_order.receive'
2034 );
2035
2036 sub receive_po_api {
2037     my($self, $conn, $auth, $po_id) = @_;
2038     my $e = new_editor(xact => 1, authtoken => $auth);
2039     return $e->die_event unless $e->checkauth;
2040     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2041
2042     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2043     return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2044
2045     my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
2046
2047     for my $li_id (@$li_ids) {
2048         receive_lineitem($mgr, $li_id) or return $e->die_event;
2049         $mgr->respond;
2050     }
2051
2052     $po->state('received');
2053     update_purchase_order($mgr, $po) or return $e->die_event;
2054
2055     $e->commit;
2056     return $mgr->respond_complete;
2057 }
2058
2059
2060 # At the moment there's a lack of parallelism between the receive and unreceive
2061 # API methods for POs and the API methods for LIs and LIDs.  The methods for
2062 # POs stream back objects as they act, whereas the methods for LIs and LIDs
2063 # atomically return an object that describes only what changed (in LIs and LIDs
2064 # themselves or in the objects to which to LIs and LIDs belong).
2065 #
2066 # The methods for LIs and LIDs work the way they do to faciliate the UI's
2067 # maintaining correct information about the state of these things when a user
2068 # wants to receive or unreceive these objects without refreshing their whole
2069 # display.  The UI feature for receiving and un-receiving a whole PO just
2070 # refreshes the whole display, so this absence of parallelism in the UI is also
2071 # relected in this module.
2072 #
2073 # This could be neatened in the future by making POs receive and unreceive in
2074 # the same way the LIs and LIDs do.
2075
2076 __PACKAGE__->register_method(
2077     method => 'receive_lineitem_detail_api',
2078     api_name    => 'open-ils.acq.lineitem_detail.receive',
2079     signature => {
2080         desc => 'Mark a lineitem_detail as received',
2081         params => [
2082             {desc => 'Authentication token', type => 'string'},
2083             {desc => 'lineitem detail ID', type => 'number'}
2084         ],
2085         return => {desc =>
2086             "on success, object describing changes to LID and possibly " .
2087             "to LI and PO; on error, Event"
2088         }
2089     }
2090 );
2091
2092 sub receive_lineitem_detail_api {
2093     my($self, $conn, $auth, $lid_id) = @_;
2094
2095     my $e = new_editor(xact=>1, authtoken=>$auth);
2096     return $e->die_event unless $e->checkauth;
2097     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2098
2099     my $fleshing = {
2100         "flesh" => 2, "flesh_fields" => {
2101             "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2102         }
2103     };
2104
2105     my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
2106
2107     return $e->die_event unless $e->allowed(
2108         'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
2109
2110     # update ...
2111     my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
2112
2113     # .. and re-retrieve
2114     $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
2115
2116     # Now build result data structure.
2117     my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
2118
2119     if (ref $recvd) {
2120         if ($recvd->class_name =~ /::purchase_order/) {
2121             $result->{"po"} = describe_affected_po($e, $recvd);
2122             $result->{"li"} = {
2123                 $lid->lineitem->id => {"state" => $lid->lineitem->state}
2124             };
2125         } elsif ($recvd->class_name =~ /::lineitem/) {
2126             $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
2127         }
2128     }
2129     $result->{"po"} ||=
2130         describe_affected_po($e, $lid->lineitem->purchase_order);
2131
2132     $e->commit;
2133     return $result;
2134 }
2135
2136 __PACKAGE__->register_method(
2137     method => 'receive_lineitem_api',
2138     api_name    => 'open-ils.acq.lineitem.receive',
2139     signature => {
2140         desc => 'Mark a lineitem as received',
2141         params => [
2142             {desc => 'Authentication token', type => 'string'},
2143             {desc => 'lineitem ID', type => 'number'}
2144         ],
2145         return => {desc =>
2146             "on success, object describing changes to LI and possibly PO; " .
2147             "on error, Event"
2148         }
2149     }
2150 );
2151
2152 sub receive_lineitem_api {
2153     my($self, $conn, $auth, $li_id) = @_;
2154
2155     my $e = new_editor(xact=>1, authtoken=>$auth);
2156     return $e->die_event unless $e->checkauth;
2157     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2158
2159     my $li = $e->retrieve_acq_lineitem([
2160         $li_id, {
2161             flesh => 1,
2162             flesh_fields => {
2163                 jub => ['purchase_order']
2164             }
2165         }
2166     ]) or return $e->die_event;
2167
2168     return $e->die_event unless $e->allowed(
2169         'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
2170
2171     my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
2172     $e->commit;
2173     $conn->respond_complete($res);
2174     $mgr->run_post_response_hooks
2175 }
2176
2177
2178 __PACKAGE__->register_method(
2179     method => 'receive_lineitem_batch_api',
2180     api_name    => 'open-ils.acq.lineitem.receive.batch',
2181     stream => 1,
2182     signature => {
2183         desc => 'Mark lineitems as received',
2184         params => [
2185             {desc => 'Authentication token', type => 'string'},
2186             {desc => 'lineitem ID list', type => 'array'}
2187         ],
2188         return => {desc =>
2189             q/On success, stream of objects describing changes to LIs and
2190             possibly PO; onerror, Event.  Any event, even after lots of other
2191             objects, should mean general failure of whole batch operation./
2192         }
2193     }
2194 );
2195
2196 sub receive_lineitem_batch_api {
2197     my ($self, $conn, $auth, $li_idlist) = @_;
2198
2199     return unless ref $li_idlist eq 'ARRAY' and @$li_idlist;
2200
2201     my $e = new_editor(xact => 1, authtoken => $auth);
2202     return $e->die_event unless $e->checkauth;
2203
2204     my $mgr = new OpenILS::Application::Acq::BatchManager(
2205         editor => $e, conn => $conn
2206     );
2207
2208     for my $li_id (map { int $_ } @$li_idlist) {
2209         my $li = $e->retrieve_acq_lineitem([
2210             $li_id, {
2211                 flesh => 1,
2212                 flesh_fields => { jub => ['purchase_order'] }
2213             }
2214         ]) or return $e->die_event;
2215
2216         return $e->die_event unless $e->allowed(
2217             'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency
2218         );
2219
2220         receive_lineitem($mgr, $li_id) or return $e->die_event;
2221         $mgr->respond;
2222     }
2223
2224     $e->commit or return $e->die_event;
2225     $mgr->respond_complete;
2226     $mgr->run_post_response_hooks;
2227 }
2228
2229 __PACKAGE__->register_method(
2230     method   => 'rollback_receive_po_api',
2231     api_name => 'open-ils.acq.purchase_order.receive.rollback'
2232 );
2233
2234 sub rollback_receive_po_api {
2235     my($self, $conn, $auth, $po_id) = @_;
2236     my $e = new_editor(xact => 1, authtoken => $auth);
2237     return $e->die_event unless $e->checkauth;
2238     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2239
2240     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2241     return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2242
2243     my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
2244
2245     for my $li_id (@$li_ids) {
2246         rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2247         $mgr->respond;
2248     }
2249
2250     $po->state('on-order');
2251     update_purchase_order($mgr, $po) or return $e->die_event;
2252
2253     $e->commit;
2254     return $mgr->respond_complete;
2255 }
2256
2257
2258 __PACKAGE__->register_method(
2259     method    => 'rollback_receive_lineitem_detail_api',
2260     api_name  => 'open-ils.acq.lineitem_detail.receive.rollback',
2261     signature => {
2262         desc   => 'Mark a lineitem_detail as Un-received',
2263         params => [
2264             {desc => 'Authentication token', type => 'string'},
2265             {desc => 'lineitem detail ID', type => 'number'}
2266         ],
2267         return => {desc =>
2268             "on success, object describing changes to LID and possibly " .
2269             "to LI and PO; on error, Event"
2270         }
2271     }
2272 );
2273
2274 sub rollback_receive_lineitem_detail_api {
2275     my($self, $conn, $auth, $lid_id) = @_;
2276
2277     my $e = new_editor(xact=>1, authtoken=>$auth);
2278     return $e->die_event unless $e->checkauth;
2279     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2280
2281     my $lid = $e->retrieve_acq_lineitem_detail([
2282         $lid_id, {
2283             flesh => 2,
2284             flesh_fields => {
2285                 acqlid => ['lineitem'],
2286                 jub => ['purchase_order']
2287             }
2288         }
2289     ]);
2290     my $li = $lid->lineitem;
2291     my $po = $li->purchase_order;
2292
2293     return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2294
2295     my $result = {};
2296
2297     my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2298         or return $e->die_event;
2299
2300     if (ref $recvd) {
2301         $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2302     } else {
2303         $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2304     }
2305
2306     if ($li->state eq "received") {
2307         $li->state("on-order");
2308         $li = update_lineitem($mgr, $li) or return $e->die_event;
2309         $result->{"li"} = {$li->id => {"state" => $li->state}};
2310     }
2311
2312     if ($po->state eq "received") {
2313         $po->state("on-order");
2314         $po = update_purchase_order($mgr, $po) or return $e->die_event;
2315     }
2316     $result->{"po"} = describe_affected_po($e, $po);
2317
2318     $e->commit and return $result or return $e->die_event;
2319 }
2320
2321 __PACKAGE__->register_method(
2322     method    => 'rollback_receive_lineitem_api',
2323     api_name  => 'open-ils.acq.lineitem.receive.rollback',
2324     signature => {
2325         desc   => 'Mark a lineitem as Un-received',
2326         params => [
2327             {desc => 'Authentication token', type => 'string'},
2328             {desc => 'lineitem ID',          type => 'number'}
2329         ],
2330         return => {desc =>
2331             "on success, object describing changes to LI and possibly PO; " .
2332             "on error, Event"
2333         }
2334     }
2335 );
2336
2337 sub rollback_receive_lineitem_api {
2338     my($self, $conn, $auth, $li_id) = @_;
2339
2340     my $e = new_editor(xact=>1, authtoken=>$auth);
2341     return $e->die_event unless $e->checkauth;
2342     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2343
2344     my $li = $e->retrieve_acq_lineitem([
2345         $li_id, {
2346             "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2347         }
2348     ]);
2349     my $po = $li->purchase_order;
2350
2351     return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2352
2353     $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2354
2355     my $result = {"li" => {$li->id => {"state" => $li->state}}};
2356     if ($po->state eq "received") {
2357         $po->state("on-order");
2358         $po = update_purchase_order($mgr, $po) or return $e->die_event;
2359     }
2360     $result->{"po"} = describe_affected_po($e, $po);
2361
2362     $e->commit and return $result or return $e->die_event;
2363 }
2364
2365 __PACKAGE__->register_method(
2366     method    => 'rollback_receive_lineitem_batch_api',
2367     api_name  => 'open-ils.acq.lineitem.receive.rollback.batch',
2368     stream => 1,
2369     signature => {
2370         desc   => 'Mark a list of lineitems as Un-received',
2371         params => [
2372             {desc => 'Authentication token', type => 'string'},
2373             {desc => 'lineitem ID list',     type => 'array'}
2374         ],
2375         return => {desc =>
2376             q/on success, a stream of objects describing changes to LI and
2377             possibly PO; on error, Event. Any event means all previously
2378             returned objects indicate changes that didn't really happen./
2379         }
2380     }
2381 );
2382
2383 sub rollback_receive_lineitem_batch_api {
2384     my ($self, $conn, $auth, $li_idlist) = @_;
2385
2386     return unless ref $li_idlist eq 'ARRAY' and @$li_idlist;
2387
2388     my $e = new_editor(xact => 1, authtoken => $auth);
2389     return $e->die_event unless $e->checkauth;
2390
2391     my $mgr = new OpenILS::Application::Acq::BatchManager(
2392         editor => $e, conn => $conn
2393     );
2394
2395     for my $li_id (map { int $_ } @$li_idlist) {
2396         my $li = $e->retrieve_acq_lineitem([
2397             $li_id, {
2398                 "flesh" => 1,
2399                 "flesh_fields" => {"jub" => ["purchase_order"]}
2400             }
2401         ]);
2402
2403         my $po = $li->purchase_order;
2404
2405         return $e->die_event unless
2406             $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2407
2408         $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2409
2410         my $result = {"li" => {$li->id => {"state" => $li->state}}};
2411         if ($po->state eq "received") { # should happen first time, not after
2412             $po->state("on-order");
2413             $po = update_purchase_order($mgr, $po) or return $e->die_event;
2414         }
2415         $result->{"po"} = describe_affected_po($e, $po);
2416
2417         $mgr->respond(%$result);
2418     }
2419
2420     $e->commit or return $e->die_event;
2421     $mgr->respond_complete;
2422     $mgr->run_post_response_hooks;
2423 }
2424
2425
2426 __PACKAGE__->register_method(
2427     method    => 'set_lineitem_price_api',
2428     api_name  => 'open-ils.acq.lineitem.price.set',
2429     signature => {
2430         desc   => 'Set lineitem price.  If debits already exist, update them as well',
2431         params => [
2432             {desc => 'Authentication token', type => 'string'},
2433             {desc => 'lineitem ID',          type => 'number'}
2434         ],
2435         return => {desc => 'status blob, Event on error'}
2436     }
2437 );
2438
2439 sub set_lineitem_price_api {
2440     my($self, $conn, $auth, $li_id, $price) = @_;
2441
2442     my $e = new_editor(xact=>1, authtoken=>$auth);
2443     return $e->die_event unless $e->checkauth;
2444     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2445
2446     my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2447     return $evt if $evt;
2448
2449     $li->estimated_unit_price($price);
2450     update_lineitem($mgr, $li) or return $e->die_event;
2451
2452     my $lid_ids = $e->search_acq_lineitem_detail(
2453         {lineitem => $li_id, fund_debit => {'!=' => undef}}, 
2454         {idlist => 1}
2455     );
2456
2457     for my $lid_id (@$lid_ids) {
2458
2459         my $lid = $e->retrieve_acq_lineitem_detail([
2460             $lid_id, {
2461             flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2462         ]);
2463
2464         $lid->fund_debit->amount($price);
2465         $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2466         $mgr->add_lid;
2467         $mgr->respond;
2468     }
2469
2470     $e->commit;
2471     return $mgr->respond_complete;
2472 }
2473
2474
2475 __PACKAGE__->register_method(
2476     method    => 'clone_picklist_api',
2477     api_name  => 'open-ils.acq.picklist.clone',
2478     signature => {
2479         desc   => 'Clones a picklist, including lineitem and lineitem details',
2480         params => [
2481             {desc => 'Authentication token', type => 'string'},
2482             {desc => 'Picklist ID', type => 'number'},
2483             {desc => 'New Picklist Name', type => 'string'}
2484         ],
2485         return => {desc => 'status blob, Event on error'}
2486     }
2487 );
2488
2489 sub clone_picklist_api {
2490     my($self, $conn, $auth, $pl_id, $name) = @_;
2491
2492     my $e = new_editor(xact=>1, authtoken=>$auth);
2493     return $e->die_event unless $e->checkauth;
2494     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2495
2496     my $old_pl = $e->retrieve_acq_picklist($pl_id);
2497     my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2498
2499     my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2500
2501     # get the current user
2502     my $cloner = $mgr->editor->requestor->id;
2503
2504     for my $li_id (@$li_ids) {
2505
2506         # copy the lineitems' MARC
2507         my $marc = ($e->retrieve_acq_lineitem($li_id))->marc;
2508
2509         # create a skeletal clone of the item
2510         my $li = Fieldmapper::acq::lineitem->new;
2511         $li->creator($cloner);
2512         $li->selector($cloner);
2513         $li->editor($cloner);
2514         $li->marc($marc);
2515
2516         my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2517
2518         $mgr->respond;
2519     }
2520
2521     $e->commit;
2522     return $mgr->respond_complete;
2523 }
2524
2525
2526 __PACKAGE__->register_method(
2527     method    => 'merge_picklist_api',
2528     api_name  => 'open-ils.acq.picklist.merge',
2529     signature => {
2530         desc   => 'Merges 2 or more picklists into a single list',
2531         params => [
2532             {desc => 'Authentication token', type => 'string'},
2533             {desc => 'Lead Picklist ID', type => 'number'},
2534             {desc => 'List of subordinate picklist IDs', type => 'array'}
2535         ],
2536         return => {desc => 'status blob, Event on error'}
2537     }
2538 );
2539
2540 sub merge_picklist_api {
2541     my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2542
2543     my $e = new_editor(xact=>1, authtoken=>$auth);
2544     return $e->die_event unless $e->checkauth;
2545     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2546
2547     # XXX perms on each picklist modified
2548
2549     $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2550     # point all of the lineitems at the lead picklist
2551     my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2552
2553     for my $li_id (@$li_ids) {
2554         my $li = $e->retrieve_acq_lineitem($li_id);
2555         $li->picklist($lead_pl);
2556         update_lineitem($mgr, $li) or return $e->die_event;
2557         $mgr->respond;
2558     }
2559
2560     # now delete the subordinate lists
2561     for my $pl_id (@$pl_list) {
2562         my $pl = $e->retrieve_acq_picklist($pl_id);
2563         $e->delete_acq_picklist($pl) or return $e->die_event;
2564     }
2565
2566     update_picklist($mgr, $lead_pl) or return $e->die_event;
2567
2568     $e->commit;
2569     return $mgr->respond_complete;
2570 }
2571
2572
2573 __PACKAGE__->register_method(
2574     method    => 'delete_picklist_api',
2575     api_name  => 'open-ils.acq.picklist.delete',
2576     signature => {
2577         desc   => q/Deletes a picklist.  It also deletes any lineitems in the "new" state. / .
2578                   q/Other attached lineitems are detached/,
2579         params => [
2580             {desc => 'Authentication token',  type => 'string'},
2581             {desc => 'Picklist ID to delete', type => 'number'}
2582         ],
2583         return => {desc => '1 on success, Event on error'}
2584     }
2585 );
2586
2587 sub delete_picklist_api {
2588     my($self, $conn, $auth, $picklist_id) = @_;
2589     my $e = new_editor(xact=>1, authtoken=>$auth);
2590     return $e->die_event unless $e->checkauth;
2591     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2592     my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2593     delete_picklist($mgr, $pl) or return $e->die_event;
2594     $e->commit;
2595     return $mgr->respond_complete;
2596 }
2597
2598
2599
2600 __PACKAGE__->register_method(
2601     method   => 'activate_purchase_order',
2602     api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2603 );
2604
2605 __PACKAGE__->register_method(
2606     method    => 'activate_purchase_order',
2607     api_name  => 'open-ils.acq.purchase_order.activate',
2608     signature => {
2609         desc => q/Activates a purchase order.  This updates the status of the PO / .
2610                 q/and Lineitems to 'on-order'.  Activated PO's are ready for EDI delivery if appropriate./,
2611         params => [
2612             {desc => 'Authentication token', type => 'string'},
2613             {desc => 'Purchase ID', type => 'number'}
2614         ],
2615         return => {desc => '1 on success, Event on error'}
2616     }
2617 );
2618
2619 sub activate_purchase_order {
2620     my($self, $conn, $auth, $po_id, $vandelay, $options) = @_;
2621     $options ||= {};
2622     $$options{dry_run} = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2623
2624     my $e = new_editor(authtoken=>$auth);
2625     return $e->die_event unless $e->checkauth;
2626     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2627     my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $options);
2628     return $e->die_event if $die_event;
2629     $conn->respond_complete(1);
2630     $mgr->run_post_response_hooks unless $$options{dry_run};
2631     return undef;
2632 }
2633
2634 # xacts managed within
2635 sub activate_purchase_order_impl {
2636     my ($mgr, $po_id, $vandelay, $options) = @_;
2637     $options ||= {};
2638     my $dry_run = $$options{dry_run};
2639     my $no_assets = $$options{no_assets};
2640
2641     # read-only until lineitem asset creation
2642     my $e = $mgr->editor;
2643     $e->xact_begin;
2644
2645     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2646     return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2647
2648     return $e->die_event(OpenILS::Event->new('PO_ALREADY_ACTIVATED'))
2649         if $po->order_date; # PO cannot be re-activated
2650
2651     my $provider = $e->retrieve_acq_provider($po->provider);
2652
2653     # find lineitems and create assets for all
2654
2655     my $query = {   
2656         purchase_order => $po_id, 
2657         state => [qw/pending-order new order-ready/]
2658     };
2659
2660     my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2661
2662     my $vl_resp; # imported li's and the managing queue
2663     unless ($dry_run or $no_assets) {
2664         $e->rollback; # read-only thus far
2665
2666         # list_assets manages its own transactions
2667         $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2668             or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2669         $e->xact_begin;
2670     }
2671
2672     # create fund debits for lineitems 
2673
2674     for my $li_id (@$li_ids) {
2675         my $li = $e->retrieve_acq_lineitem($li_id);
2676         
2677         unless ($li->eg_bib_id or $dry_run or $no_assets) {
2678             # we encountered a lineitem that was not successfully imported.
2679             # we cannot continue.  rollback and report.
2680             $e->rollback;
2681             return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2682         }
2683
2684         $li->state('on-order');
2685         $li->claim_policy($provider->default_claim_policy)
2686             if $provider->default_claim_policy and !$li->claim_policy;
2687         create_lineitem_debits($mgr, $li, $options) or return $e->die_event;
2688         update_lineitem($mgr, $li) or return $e->die_event;
2689         $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2690         $mgr->respond;
2691     }
2692
2693     # create po-item debits
2694
2695     for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2696
2697         my $debit = create_fund_debit(
2698             $mgr, 
2699             $dry_run, 
2700             debit_type => 'direct_charge', # to match invoicing
2701             origin_amount => $po_item->estimated_cost,
2702             origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2703             amount => $po_item->estimated_cost,
2704             fund => $po_item->fund
2705         ) or return $e->die_event;
2706         $po_item->fund_debit($debit->id);
2707         $e->update_acq_po_item($po_item) or return $e->die_event;
2708         $mgr->respond;
2709     }
2710
2711     # mark PO as ordered
2712
2713     $po->state('on-order');
2714     $po->order_date('now');
2715     update_purchase_order($mgr, $po) or return $e->die_event;
2716
2717     # clean up the xact
2718     $dry_run and $e->rollback or $e->commit;
2719
2720     # tell the world we activated a PO
2721     $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2722
2723     return undef;
2724 }
2725
2726
2727 __PACKAGE__->register_method(
2728     method    => 'split_purchase_order_by_lineitems',
2729     api_name  => 'open-ils.acq.purchase_order.split_by_lineitems',
2730     signature => {
2731         desc   => q/Splits a PO into many POs, 1 per lineitem.  Only works for / .
2732                   q/POs a) with more than one lineitems, and b) in the "pending" state./,
2733         params => [
2734             {desc => 'Authentication token', type => 'string'},
2735             {desc => 'Purchase order ID',    type => 'number'}
2736         ],
2737         return => {desc => 'list of new PO IDs on success, Event on error'}
2738     }
2739 );
2740
2741 sub split_purchase_order_by_lineitems {
2742     my ($self, $conn, $auth, $po_id) = @_;
2743
2744     my $e = new_editor("xact" => 1, "authtoken" => $auth);
2745     return $e->die_event unless $e->checkauth;
2746
2747     my $po = $e->retrieve_acq_purchase_order([
2748         $po_id, {
2749             "flesh" => 1,
2750             "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2751         }
2752     ]) or return $e->die_event;
2753
2754     return $e->die_event
2755         unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2756
2757     unless ($po->state eq "pending") {
2758         $e->rollback;
2759         return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2760     }
2761
2762     unless (@{$po->lineitems} > 1) {
2763         $e->rollback;
2764         return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2765     }
2766
2767     # To split an existing PO into many, it seems unwise to just delete the
2768     # original PO, so we'll instead detach all of the original POs' lineitems
2769     # but the first, then create new POs for each of the remaining LIs, and
2770     # then attach the LIs to their new POs.
2771
2772     my @po_ids = ($po->id);
2773     my @moving_li = @{$po->lineitems};
2774     shift @moving_li;    # discard first LI
2775
2776     foreach my $li (@moving_li) {
2777         my $new_po = $po->clone;
2778         $new_po->clear_id;
2779         $new_po->clear_name;
2780         $new_po->creator($e->requestor->id);
2781         $new_po->editor($e->requestor->id);
2782         $new_po->owner($e->requestor->id);
2783         $new_po->edit_time("now");
2784         $new_po->create_time("now");
2785
2786         $new_po = $e->create_acq_purchase_order($new_po);
2787
2788         # Clone any notes attached to the old PO and attach to the new one.
2789         foreach my $note (@{$po->notes}) {
2790             my $new_note = $note->clone;
2791             $new_note->clear_id;
2792             $new_note->edit_time("now");
2793             $new_note->purchase_order($new_po->id);
2794             $e->create_acq_po_note($new_note);
2795         }
2796
2797         $li->edit_time("now");
2798         $li->purchase_order($new_po->id);
2799         $e->update_acq_lineitem($li);
2800
2801         push @po_ids, $new_po->id;
2802     }
2803
2804     $po->edit_time("now");
2805     $e->update_acq_purchase_order($po);
2806
2807     return \@po_ids if $e->commit;
2808     return $e->die_event;
2809 }
2810
2811
2812 sub not_cancelable {
2813     my $o = shift;
2814     (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2815 }
2816
2817 __PACKAGE__->register_method(
2818     method => "cancel_purchase_order_api",
2819     api_name    => "open-ils.acq.purchase_order.cancel",
2820     signature => {
2821         desc => q/Cancels an on-order purchase order/,
2822         params => [
2823             {desc => "Authentication token", type => "string"},
2824             {desc => "PO ID to cancel", type => "number"},
2825             {desc => "Cancel reason ID", type => "number"}
2826         ],
2827         return => {desc => q/Object describing changed POs, LIs and LIDs
2828             on success; Event on error./}
2829     }
2830 );
2831
2832 sub cancel_purchase_order_api {
2833     my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2834
2835     my $e = new_editor("xact" => 1, "authtoken" => $auth);
2836     return $e->die_event unless $e->checkauth;
2837     my $mgr = new OpenILS::Application::Acq::BatchManager(
2838         "editor" => $e, "conn" => $conn
2839     );
2840
2841     $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2842         return new OpenILS::Event(
2843             "BAD_PARAMS", "note" => "Provide cancel reason ID"
2844         );
2845
2846     my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2847         return $e->die_event;
2848     if (not_cancelable($result)) { # event not from CStoreEditor
2849         $e->rollback;
2850         return $result;
2851     } elsif ($result == -1) {
2852         $e->rollback;
2853         return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2854     }
2855
2856     $e->commit or return $e->die_event;
2857
2858     # XXX create purchase order status events?
2859
2860     if ($mgr->{post_commit}) {
2861         foreach my $func (@{$mgr->{post_commit}}) {
2862             $func->();
2863         }
2864     }
2865
2866     return $result;
2867 }
2868
2869 sub cancel_purchase_order {
2870     my ($mgr, $po_id, $cancel_reason) = @_;
2871
2872     my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2873
2874     # XXX is "cancelled" a typo?  It's not correct US spelling, anyway.
2875     # Depending on context, this may not warrant an event.
2876     return -1 if $po->state eq "cancelled";
2877
2878     # But this always does.
2879     return new OpenILS::Event(
2880         "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2881     ) unless ($po->state eq "on-order" or $po->state eq "pending");
2882
2883     return 0 unless
2884         $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2885
2886     $po->state("cancelled");
2887     $po->cancel_reason($cancel_reason->id);
2888
2889     my $li_ids = $mgr->editor->search_acq_lineitem(
2890         {"purchase_order" => $po_id}, {"idlist" => 1}
2891     );
2892
2893     my $result = {"li" => {}, "lid" => {}};
2894     foreach my $li_id (@$li_ids) {
2895         my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2896             or return 0;
2897
2898         next if $li_result == -1; # already canceled:skip.
2899         return $li_result if not_cancelable($li_result); # not cancelable:stop.
2900
2901         # Merge in each LI result (there's only going to be
2902         # one per call to cancel_lineitem).
2903         my ($k, $v) = each %{$li_result->{"li"}};
2904         $result->{"li"}->{$k} = $v;
2905
2906         # Merge in each LID result (there may be many per call to
2907         # cancel_lineitem).
2908         while (($k, $v) = each %{$li_result->{"lid"}}) {
2909             $result->{"lid"}->{$k} = $v;
2910         }
2911     }
2912
2913     # TODO who/what/where/how do we indicate this change for electronic orders?
2914     # TODO return changes to encumbered/spent
2915     # TODO maybe cascade up from smaller object to container object if last
2916     # smaller object in the container has been canceled?
2917
2918     update_purchase_order($mgr, $po) or return 0;
2919     $result->{"po"} = {
2920         $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2921     };
2922     return $result;
2923 }
2924
2925
2926 __PACKAGE__->register_method(
2927     method => "cancel_lineitem_api",
2928     api_name    => "open-ils.acq.lineitem.cancel",
2929     signature => {
2930         desc => q/Cancels an on-order lineitem/,
2931         params => [
2932             {desc => "Authentication token", type => "string"},
2933             {desc => "Lineitem ID to cancel", type => "number"},
2934             {desc => "Cancel reason ID", type => "number"}
2935         ],
2936         return => {desc => q/Object describing changed LIs and LIDs on success;
2937             Event on error./}
2938     }
2939 );
2940
2941 __PACKAGE__->register_method(
2942     method => "cancel_lineitem_api",
2943     api_name    => "open-ils.acq.lineitem.cancel.batch",
2944     signature => {
2945         desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2946         return => {desc => q/Object describing changed LIs and LIDs on success;
2947             Event on error./}
2948     }
2949 );
2950
2951 sub cancel_lineitem_api {
2952     my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2953
2954     my $batched = $self->api_name =~ /\.batch/;
2955
2956     my $e = new_editor("xact" => 1, "authtoken" => $auth);
2957     return $e->die_event unless $e->checkauth;
2958     my $mgr = new OpenILS::Application::Acq::BatchManager(
2959         "editor" => $e, "conn" => $conn
2960     );
2961
2962     $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2963         return new OpenILS::Event(
2964             "BAD_PARAMS", "note" => "Provide cancel reason ID"
2965         );
2966
2967     my ($result, $maybe_event);
2968
2969     if ($batched) {
2970         $result = {"li" => {}, "lid" => {}};
2971         foreach my $one_li_id (@$li_id) {
2972             my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2973                 return $e->die_event;
2974             if (not_cancelable($one)) {
2975                 $maybe_event = $one;
2976             } elsif ($result == -1) {
2977                 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2978             } else {
2979                 my ($k, $v);
2980                 if ($one->{"li"}) {
2981                     while (($k, $v) = each %{$one->{"li"}}) {
2982                         $result->{"li"}->{$k} = $v;
2983                     }
2984                 }
2985                 if ($one->{"lid"}) {
2986                     while (($k, $v) = each %{$one->{"lid"}}) {
2987                         $result->{"lid"}->{$k} = $v;
2988                     }
2989                 }
2990             }
2991         }
2992     } else {
2993         $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2994             return $e->die_event;
2995
2996         if (not_cancelable($result)) {
2997             $e->rollback;
2998             return $result;
2999         } elsif ($result == -1) {
3000             $e->rollback;
3001             return new OpenILS::Event("ACQ_ALREADY_CANCELED");
3002         }
3003     }
3004
3005     if ($batched and not scalar keys %{$result->{"li"}}) {
3006         $e->rollback;
3007         return $maybe_event;
3008     } else {
3009         $e->commit or return $e->die_event;
3010         # create_lineitem_status_events should handle array li_id ok
3011         create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
3012
3013         if ($mgr->{post_commit}) {
3014             foreach my $func (@{$mgr->{post_commit}}) {
3015                 $func->();
3016             }
3017         }
3018
3019         return $result;
3020     }
3021 }
3022
3023 sub cancel_lineitem {
3024     my ($mgr, $li_id, $cancel_reason) = @_;
3025     my $li = $mgr->editor->retrieve_acq_lineitem([
3026         $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
3027     ]) or return 0;
3028
3029     return 0 unless $mgr->editor->allowed(
3030         "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
3031     );
3032
3033     # Depending on context, this may not warrant an event.
3034     return -1 if $li->state eq "cancelled";
3035
3036     # But this always does.  Note that this used to be looser, but you can
3037     # no longer cancel lineitems that lack a PO or that are in "pending-order"
3038     # state (you could in the past).
3039     return new OpenILS::Event(
3040         "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
3041     ) unless $li->purchase_order and $li->state eq "on-order";
3042
3043     $li->state("cancelled");
3044     $li->cancel_reason($cancel_reason->id);
3045
3046     my $lids = $mgr->editor->search_acq_lineitem_detail([{
3047         "lineitem" => $li_id
3048     }, {
3049         flesh => 1,
3050         flesh_fields => { acqlid => ['eg_copy_id'] }
3051     }]);
3052
3053     my $result = {"lid" => {}};
3054     my $copies = [];
3055     foreach my $lid (@$lids) {
3056         my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
3057             or return 0;
3058
3059         # gathering any real copies for deletion
3060         if ($lid->eg_copy_id) {
3061             $lid->eg_copy_id->isdeleted('t');
3062             push @$copies, $lid->eg_copy_id;
3063         }
3064
3065         next if $lid_result == -1; # already canceled: just skip it.
3066         return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
3067
3068         # Merge in each LID result (there's only going to be one per call to
3069         # cancel_lineitem_detail).
3070         my ($k, $v) = each %{$lid_result->{"lid"}};
3071         $result->{"lid"}->{$k} = $v;
3072     }
3073
3074     # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
3075     # Delete empty bibs according org unit setting
3076     my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
3077         $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
3078     if (scalar(@$copies)>0) {
3079         my $override = 1;
3080         my $delete_stats = undef;
3081         my $retarget_holds = [];
3082         my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
3083             $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
3084
3085         if( $cat_evt ) {
3086             $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
3087             return new OpenILS::Event(
3088                 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
3089             );
3090         }
3091
3092         # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
3093         #my $ses = OpenSRF::AppSession->create('open-ils.circ');
3094         #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
3095     }
3096
3097     # if we have a bib, check to see whether it has been deleted.  if so, cancel any active holds targeting that bib
3098     if ($li->eg_bib_id) {
3099         my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
3100             "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
3101         );
3102         if ($U->is_true($bib->deleted)) {
3103             my $holds = $mgr->editor->search_action_hold_request(
3104                 {   cancel_time => undef,
3105                     fulfillment_time => undef,
3106                     target => $li->eg_bib_id
3107                 }
3108             );
3109
3110             my %cached_usr_home_ou = ();
3111
3112             for my $hold (@$holds) {
3113
3114                 $logger->info("Cancelling hold ".$hold->id.
3115                     " due to acq lineitem cancellation.");
3116
3117                 $hold->cancel_time('now');
3118                 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
3119                 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
3120                 unless($mgr->editor->update_action_hold_request($hold)) {
3121                     my $evt = $mgr->editor->event;
3122                     $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
3123                     return new OpenILS::Event(
3124                         "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
3125                     );
3126                 }
3127                 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
3128                     $mgr->{post_commit} = [];
3129                 }
3130                 push @{ $mgr->{post_commit} }, sub {
3131                     my $home_ou = $cached_usr_home_ou{$hold->usr};
3132                     if (! $home_ou) {
3133                         my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
3134                         $home_ou = $user->home_ou;
3135                         $cached_usr_home_ou{$hold->usr} = $home_ou;
3136                     }
3137                     $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
3138                 };
3139             }
3140         }
3141     }
3142
3143     update_lineitem($mgr, $li) or return 0;
3144     $result->{"li"} = {
3145         $li_id => {
3146             "state" => $li->state,
3147             "cancel_reason" => $cancel_reason
3148         }
3149     };
3150     return $result;
3151 }
3152
3153
3154 __PACKAGE__->register_method(
3155     method => "cancel_lineitem_detail_api",
3156     api_name    => "open-ils.acq.lineitem_detail.cancel",
3157     signature => {
3158         desc => q/Cancels an on-order lineitem detail/,
3159         params => [
3160             {desc => "Authentication token", type => "string"},
3161             {desc => "Lineitem detail ID to cancel", type => "number"},
3162             {desc => "Cancel reason ID", type => "number"}
3163         ],
3164         return => {desc => q/Object describing changed LIDs on success;
3165             Event on error./}
3166     }
3167 );
3168
3169 sub cancel_lineitem_detail_api {
3170     my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
3171
3172     my $e = new_editor("xact" => 1, "authtoken" => $auth);
3173     return $e->die_event unless $e->checkauth;
3174     my $mgr = new OpenILS::Application::Acq::BatchManager(
3175         "editor" => $e, "conn" => $conn
3176     );
3177
3178     $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
3179         return new OpenILS::Event(
3180             "BAD_PARAMS", "note" => "Provide cancel reason ID"
3181         );
3182
3183     my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
3184         return $e->die_event;
3185
3186     if (not_cancelable($result)) {
3187         $e->rollback;
3188         return $result;
3189     } elsif ($result == -1) {
3190         $e->rollback;
3191         return new OpenILS::Event("ACQ_ALREADY_CANCELED");
3192     }
3193
3194     $e->commit or return $e->die_event;
3195
3196     # XXX create lineitem detail status events?
3197     return $result;
3198 }
3199
3200 sub cancel_lineitem_detail {
3201     my ($mgr, $lid_id, $cancel_reason) = @_;
3202     my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
3203         $lid_id, {
3204             "flesh" => 2,
3205             "flesh_fields" => {
3206                 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
3207             }
3208         }
3209     ]) or return 0;
3210
3211     # Depending on context, this may not warrant an event.
3212     return -1 if $lid->cancel_reason;
3213
3214     # But this always does.
3215     return new OpenILS::Event(
3216         "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
3217     ) unless (
3218         (! $lid->lineitem->purchase_order) or
3219         (
3220             (not $lid->recv_time) and
3221             $lid->lineitem and
3222             $lid->lineitem->purchase_order and (
3223                 $lid->lineitem->state eq "on-order" or
3224                 $lid->lineitem->state eq "pending-order"
3225             )
3226         )
3227     );
3228
3229     return 0 unless $mgr->editor->allowed(
3230         "CREATE_PURCHASE_ORDER",
3231         $lid->lineitem->purchase_order->ordering_agency
3232     ) or (! $lid->lineitem->purchase_order);
3233
3234     $lid->cancel_reason($cancel_reason->id);
3235
3236     unless($U->is_true($cancel_reason->keep_debits)) {
3237         my $debit_id = $lid->fund_debit;
3238         $lid->clear_fund_debit;
3239
3240         if($debit_id) {
3241             # item is cancelled.  Remove the fund debit.
3242             my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
3243             if (!$U->is_true($debit->encumbrance)) {
3244                 $mgr->editor->rollback;
3245                 return OpenILS::Event->new('ACQ_NOT_CANCELABLE', 
3246                     note => "Debit is marked as paid: $debit_id");
3247             }
3248             $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
3249         }
3250     }
3251
3252     # XXX LIDs don't have either an editor or a edit_time field. Should we
3253     # update these on the LI when we alter an LID?
3254     $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
3255
3256     return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
3257 }
3258
3259
3260 __PACKAGE__->register_method(
3261     method    => 'user_requests',
3262     api_name  => 'open-ils.acq.user_request.retrieve.by_user_id',
3263     stream    => 1,
3264     signature => {
3265         desc   => 'Retrieve fleshed user requests and related data for a given user.',
3266         params => [
3267             { desc => 'Authentication token',      type => 'string' },
3268             { desc => 'User ID of the owner, or array of IDs',      },
3269             { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3270               type => 'object'
3271             }
3272         ],
3273         return => {
3274             desc => 'Fleshed user requests and related data',
3275             type => 'object'
3276         }
3277     }
3278 );
3279
3280 __PACKAGE__->register_method(
3281     method    => 'user_requests',
3282     api_name  => 'open-ils.acq.user_request.retrieve.by_home_ou',
3283     stream    => 1,
3284     signature => {
3285         desc   => 'Retrieve fleshed user requests and related data for a given org unit or units.',
3286         params => [
3287             { desc => 'Authentication token',      type => 'string' },
3288             { desc => 'Org unit ID, or array of IDs',               },
3289             { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3290               type => 'object'
3291             }
3292         ],
3293         return => {
3294             desc => 'Fleshed user requests and related data',
3295             type => 'object'
3296         }
3297     }
3298 );
3299
3300 sub user_requests {
3301     my($self, $conn, $auth, $search_value, $options) = @_;
3302     my $e = new_editor(authtoken => $auth);
3303     return $e->event unless $e->checkauth;
3304     my $rid = $e->requestor->id;
3305     $options ||= {};
3306
3307     my $query = {
3308         "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
3309         "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
3310         "where"=>{
3311             "+jub"=> {
3312                 "-or" => [
3313                     {"id"=>undef}, # this with the left-join pulls in requests without lineitems
3314                     {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
3315                 ]
3316             }
3317         },
3318         "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
3319     };
3320
3321     foreach (qw/ order_by limit offset /) {
3322         $query->{$_} = $options->{$_} if defined $options->{$_};
3323     }
3324     if (defined $options->{'state'}) {
3325         $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};        
3326     }
3327
3328     if ($self->api_name =~ /by_user_id/) {
3329         $query->{'where'}->{'usr'} = $search_value;
3330     } else {
3331         $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3332     }
3333
3334     my $pertinent_ids = $e->json_query($query);
3335
3336     my %perm_test = ();
3337     for my $id_blob (@$pertinent_ids) {
3338         if ($rid != $id_blob->{usr_id}) {
3339             if (!defined $perm_test{ $id_blob->{home_ou} }) {
3340                 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3341             }
3342             if (!$perm_test{ $id_blob->{home_ou} }) {
3343                 next; # failed test
3344             }
3345         }
3346         my $aur_obj = $e->retrieve_acq_user_request([
3347             $id_blob->{id},
3348             {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3349         ]);
3350         if (! $aur_obj) { next; }
3351
3352         if ($aur_obj->lineitem()) {
3353             $aur_obj->lineitem()->clear_marc();
3354         }
3355         $conn->respond($aur_obj);
3356     }
3357
3358     return undef;
3359 }
3360
3361 __PACKAGE__->register_method (
3362     method    => 'update_user_request',
3363     api_name  => 'open-ils.acq.user_request.cancel.batch',
3364     stream    => 1,
3365     signature => {
3366         desc   => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether.  The '    .
3367                   'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3368         params => [
3369             { desc => 'Authentication token',              type => 'string' },
3370             { desc => 'ID or array of IDs for the user requests to cancel'  },
3371             { desc => 'Cancel Reason ID (optional)',       type => 'string' }
3372         ],
3373         return => {
3374             desc => 'progress object, event on error',
3375         }
3376     }
3377 );
3378 __PACKAGE__->register_method (
3379     method    => 'update_user_request',
3380     api_name  => 'open-ils.acq.user_request.set_no_hold.batch',
3381     stream    => 1,
3382     signature => {
3383         desc   => 'Remove the hold from a user request or set of requests',
3384         params => [
3385             { desc => 'Authentication token',              type => 'string' },
3386             { desc => 'ID or array of IDs for the user requests to modify'  }
3387         ],
3388         return => {
3389             desc => 'progress object, event on error',
3390         }
3391     }
3392 );
3393
3394 sub update_user_request {
3395     my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3396     my $e = new_editor(xact => 1, authtoken => $auth);
3397     return $e->die_event unless $e->checkauth;
3398     my $rid = $e->requestor->id;
3399
3400     my $x = 1;
3401     my %perm_test = ();
3402     for my $id (@$aur_ids) {
3403
3404         my $aur_obj = $e->retrieve_acq_user_request([
3405             $id,
3406             {   flesh => 1,
3407                 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3408             }
3409         ]) or return $e->die_event;
3410
3411         my $context_org = $aur_obj->usr()->home_ou();
3412         $aur_obj->usr( $aur_obj->usr()->id() );
3413
3414         if ($rid != $aur_obj->usr) {
3415             if (!defined $perm_test{ $context_org }) {
3416                 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3417             }
3418             if (!$perm_test{ $context_org }) {
3419                 next; # failed test
3420             }
3421         }
3422
3423         if($self->api_name =~ /set_no_hold/) {
3424             if ($U->is_true($aur_obj->hold)) { 
3425                 $aur_obj->hold(0); 
3426                 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3427             }
3428         }
3429
3430         if($self->api_name =~ /cancel/) {
3431             if ( $cancel_reason ) {
3432                 $aur_obj->cancel_reason( $cancel_reason );
3433                 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3434                 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3435             } else {
3436                 $e->delete_acq_user_request($aur_obj);
3437             }
3438         }
3439
3440         $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3441     }
3442
3443     $e->commit;
3444     return {complete => 1};
3445 }
3446
3447 __PACKAGE__->register_method (
3448     method    => 'new_user_request',
3449     api_name  => 'open-ils.acq.user_request.create',
3450     signature => {
3451         desc   => 'Create a new user request object in the DB',
3452         param  => [
3453             { desc => 'Authentication token',   type => 'string' },
3454             { desc => 'User request data hash.  Hash keys match the fields for the "aur" object', type => 'object' }
3455         ],
3456         return => {
3457             desc => 'The created user request object, or event on error'
3458         }
3459     }
3460 );
3461
3462 sub new_user_request {
3463     my($self, $conn, $auth, $form_data) = @_;
3464     my $e = new_editor(xact => 1, authtoken => $auth);
3465     return $e->die_event unless $e->checkauth;
3466     my $rid = $e->requestor->id;
3467     my $target_user_fleshed;
3468     if (! defined $$form_data{'usr'}) {
3469         $$form_data{'usr'} = $rid;
3470     }
3471     if ($$form_data{'usr'} != $rid) {
3472         # See if the requestor can place the request on behalf of a different user.
3473         $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3474         $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3475     } else {
3476         $target_user_fleshed = $e->requestor;
3477         $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3478     }
3479     if (! defined $$form_data{'pickup_lib'}) {
3480         if ($target_user_fleshed->ws_ou) {
3481             $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3482         } else {
3483             $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3484         }
3485     }
3486     if (! defined $$form_data{'request_type'}) {
3487         $$form_data{'request_type'} = 1; # Books
3488     }
3489     my $aur_obj = new Fieldmapper::acq::user_request; 
3490     $aur_obj->isnew(1);
3491     $aur_obj->usr( $$form_data{'usr'} );
3492     $aur_obj->request_date( 'now' );
3493     for my $field ( keys %$form_data ) {
3494         if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3495             $aur_obj->$field( $$form_data{$field} );
3496         }
3497     }
3498
3499     $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3500
3501     $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3502
3503     return $aur_obj;
3504 }
3505
3506 sub create_user_request_events {
3507     my($e, $user_reqs, $hook) = @_;
3508
3509     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3510     $ses->connect;
3511
3512     my %cached_usr_home_ou = ();
3513     for my $user_req (@$user_reqs) {
3514         my $home_ou = $cached_usr_home_ou{$user_req->usr};
3515         if (! $home_ou) {
3516             my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3517             $home_ou = $user->home_ou;
3518             $cached_usr_home_ou{$user_req->usr} = $home_ou;
3519         }
3520         my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3521         $req->recv;
3522     }
3523
3524     $ses->disconnect;
3525     return undef;
3526 }
3527
3528
3529 __PACKAGE__->register_method(
3530     method => "po_note_CUD_batch",
3531     api_name => "open-ils.acq.po_note.cud.batch",
3532     stream => 1,
3533     signature => {
3534         desc => q/Manage purchase order notes/,
3535         params => [
3536             {desc => "Authentication token", type => "string"},
3537             {desc => "List of po_notes to manage", type => "array"},
3538         ],
3539         return => {desc => "Stream of successfully managed objects"}
3540     }
3541 );
3542
3543 sub po_note_CUD_batch {
3544     my ($self, $conn, $auth, $notes) = @_;
3545
3546     my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3547     return $e->die_event unless $e->checkauth;
3548     # XXX perms
3549
3550     my $total = @$notes;
3551     my $count = 0;
3552
3553     foreach my $note (@$notes) {
3554
3555         $note->editor($e->requestor->id);
3556         $note->edit_time("now");
3557
3558         if ($note->isnew) {
3559             $note->creator($e->requestor->id);
3560             $note = $e->create_acq_po_note($note) or return $e->die_event;
3561         } elsif ($note->isdeleted) {
3562             $e->delete_acq_po_note($note) or return $e->die_event;
3563         } elsif ($note->ischanged) {
3564             $e->update_acq_po_note($note) or return $e->die_event;
3565         }
3566
3567         unless ($note->isdeleted) {
3568             $note = $e->retrieve_acq_po_note($note->id) or
3569                 return $e->die_event;
3570         }
3571
3572         $conn->respond(
3573             {"maximum" => $total, "progress" => ++$count, "note" => $note}
3574         );
3575     }
3576
3577     $e->commit and $conn->respond_complete or return $e->die_event;
3578 }
3579
3580
3581 # retrieves a lineitem, fleshes its PO and PL, checks perms
3582 # returns ($li, $evt, $org)
3583 sub fetch_and_check_li {
3584     my $e = shift;
3585     my $li_id = shift;
3586     my $perm_mode = shift || 'read';
3587
3588     my $li = $e->retrieve_acq_lineitem([
3589         $li_id,
3590         {   flesh => 1,
3591             flesh_fields => {jub => ['purchase_order', 'picklist']}
3592         }
3593     ]) or return (undef, $e->die_event);
3594
3595     my $org;
3596     if(my $po = $li->purchase_order) {
3597         $org = $po->ordering_agency;
3598         my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3599         return ($li, $e->die_event) unless $e->allowed($perms, $org);
3600
3601     } elsif(my $pl = $li->picklist) {
3602         $org = $pl->org_unit;
3603         my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3604         return ($li, $e->die_event) unless $e->allowed($perms, $org);
3605     }
3606
3607     return ($li, undef, $org);
3608 }
3609
3610
3611 __PACKAGE__->register_method(
3612     method => "clone_distrib_form",
3613     api_name => "open-ils.acq.distribution_formula.clone",
3614     stream => 1,
3615     signature => {
3616         desc => q/Clone a distribution formula/,
3617         params => [
3618             {desc => "Authentication token", type => "string"},
3619             {desc => "Original formula ID", type => 'integer'},
3620             {desc => "Name of new formula", type => 'string'},
3621         ],
3622         return => {desc => "ID of newly created formula"}
3623     }
3624 );
3625
3626 sub clone_distrib_form {
3627     my($self, $client, $auth, $form_id, $new_name) = @_;
3628
3629     my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3630     return $e->die_event unless $e->checkauth;
3631
3632     my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3633     return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3634
3635     my $new_form = Fieldmapper::acq::distribution_formula->new;
3636
3637     $new_form->owner($old_form->owner);
3638     $new_form->name($new_name);
3639     $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3640
3641     my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3642     for my $entry (@$entries) {
3643        my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3644        $new_entry->$_($entry->$_()) for $entry->real_fields;
3645        $new_entry->formula($new_form->id);
3646        $new_entry->clear_id;
3647        $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3648     }
3649
3650     $e->commit;
3651     return $new_form->id;
3652 }
3653
3654 __PACKAGE__->register_method(
3655     method => 'add_li_to_po',
3656     api_name    => 'open-ils.acq.purchase_order.add_lineitem',
3657     signature => {
3658         desc => q/Adds a lineitem to an existing purchase order/,
3659         params => [
3660             {desc => 'Authentication token', type => 'string'},
3661             {desc => 'The purchase order id', type => 'number'},
3662             {desc => 'The lineitem ID (or an array of them)', type => 'mixed'},
3663         ],
3664         return => {desc => 'Streams a total versus completed counts object, event on error'}
3665     }
3666 );
3667
3668 sub add_li_to_po {
3669     my($self, $conn, $auth, $po_id, $li_id) = @_;
3670
3671     my $e = new_editor(authtoken => $auth, xact => 1);
3672     return $e->die_event unless $e->checkauth;
3673
3674     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3675
3676     my $po = $e->retrieve_acq_purchase_order($po_id)
3677         or return $e->die_event;
3678
3679     return $e->die_event unless 
3680         $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3681
3682     unless ($po->state =~ /new|pending/) {
3683         $e->rollback;
3684         return {success => 0, po => $po, error => 'bad-po-state'};
3685     }
3686
3687     my $lis;
3688
3689     if (ref $li_id eq "ARRAY") {
3690         $li_id = [ map { int($_) } @$li_id ];
3691         return $e->die_event(new OpenILS::Event("BAD_PARAMS")) unless @$li_id;
3692
3693         $lis = $e->search_acq_lineitem({id => $li_id})
3694             or return $e->die_event;
3695     } else {
3696         my $li = $e->retrieve_acq_lineitem(int($li_id))
3697             or return $e->die_event;
3698         $lis = [$li];
3699     }
3700
3701     foreach my $li (@$lis) {
3702         if ($li->state !~ /new|order-ready|pending-order/ or
3703             $li->purchase_order) {
3704             $e->rollback;
3705             return {success => 0, li => $li, error => 'bad-li-state'};
3706         }
3707
3708         $li->provider($po->provider);
3709         $li->purchase_order($po_id);
3710         $li->state('pending-order');
3711         apply_default_copies($mgr, $po, $li->id) or return $e->die_event;
3712         update_lineitem($mgr, $li) or return $e->die_event;
3713     }
3714
3715     $e->commit;
3716     return {success => 1};
3717 }
3718
3719 __PACKAGE__->register_method(
3720     method => 'po_lineitems_no_copies',
3721     api_name => 'open-ils.acq.purchase_order.no_copy_lineitems.id_list',
3722     stream => 1,
3723     authoritative => 1, 
3724     signature => {
3725         desc => q/Returns the set of lineitem IDs for a given PO that have no copies attached/,
3726         params => [
3727             {desc => 'Authentication token', type => 'string'},
3728             {desc => 'The purchase order id', type => 'number'},
3729         ],
3730         return => {desc => 'Stream of lineitem IDs on success, event on error'}
3731     }
3732 );
3733
3734 sub po_lineitems_no_copies {
3735     my ($self, $conn, $auth, $po_id) = @_;
3736
3737     my $e = new_editor(authtoken => $auth);
3738     return $e->event unless $e->checkauth;
3739
3740     # first check the view perms for LI's attached to this PO
3741     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->event;
3742     return $e->event unless $e->allowed('VIEW_PURCHASE_ORDER', $po->ordering_agency);
3743
3744     my $ids = $e->json_query({
3745         select => {jub => ['id']},
3746         from => {jub => {acqlid => {type => 'left'}}},
3747         where => {
3748             '+jub' => {purchase_order => $po_id},
3749             '+acqlid' => {lineitem => undef}
3750         }
3751     });
3752
3753     $conn->respond($_->{id}) for @$ids;
3754     return undef;
3755 }
3756
3757 __PACKAGE__->register_method(
3758     method => 'set_li_order_ident',
3759     api_name => 'open-ils.acq.lineitem.order_identifier.set',
3760     signature => {
3761         desc => q/
3762             Given an existing lineitem_attr (typically a marc_attr), this will
3763             create a matching local_attr to store the name and value and mark
3764             the attr as the order_ident.  Any existing local_attr marked as
3765             order_ident is removed.
3766         /,
3767         params => [
3768             {desc => 'Authentication token', type => 'string'},
3769             {desc => q/Args object:
3770                 source_attr_id : ID of the existing lineitem_attr to use as
3771                     order ident.
3772                 lineitem_id : lineitem id
3773                 attr_name : name ('isbn', etc.) of a new marc_attr to add to 
3774                     the lineitem to use for the order ident
3775                 attr_value : value for the new marc_attr
3776                 no_apply_bre : if set, newly added attrs will not be applied 
3777                     to the lineitems' linked bib record/,
3778                 type => 'object'}
3779         ],
3780         return => {desc => q/Returns the attribute 
3781             responsible for tracking the order identifier/}
3782     }
3783 );
3784
3785 sub set_li_order_ident {
3786     my ($self, $conn, $auth, $args) = @_;
3787     $args ||= {};
3788
3789     my $source_attr;
3790     my $source_attr_id = $args->{source_attr_id};
3791
3792     my $e = new_editor(authtoken => $auth, xact => 1);
3793     return $e->die_event unless $e->checkauth;
3794
3795     # fetch attr, LI, and check update permissions
3796
3797     my $li_id = $args->{lineitem_id};
3798
3799     if ($source_attr_id) {
3800         $source_attr = $e->retrieve_acq_lineitem_attr($source_attr_id)
3801             or return $e->die_event;
3802         $li_id = $source_attr->lineitem;
3803     }
3804
3805     my ($li, $evt, $perm_org) = fetch_and_check_li($e, $li_id, 'write');
3806     return $evt if $evt;
3807
3808     return $e->die_event unless 
3809         $e->allowed('ACQ_SET_LINEITEM_IDENTIFIER', $perm_org);
3810
3811     # if needed, create a new marc attr for 
3812     # the lineitem to represent the ident value
3813
3814     ($source_attr, $evt) = apply_new_li_ident_attr(
3815         $e, $li, $perm_org, $args->{attr_name}, $args->{attr_value}) 
3816         unless $source_attr;
3817
3818     return $evt if $evt;
3819
3820     # remove the existing order_ident attribute if present
3821
3822     my $old_attr = $e->search_acq_lineitem_attr({
3823         attr_type => 'lineitem_local_attr_definition',
3824         lineitem => $li->id,
3825         order_ident => 't'
3826     })->[0];
3827
3828     if ($old_attr) {
3829
3830         # if we already have an order_ident that matches the 
3831         # source attr, there's nothing left to do.
3832
3833         if ($old_attr->attr_name eq $source_attr->attr_name and
3834             $old_attr->attr_value eq $source_attr->attr_value) {
3835
3836             $e->rollback;
3837             return $old_attr;
3838
3839         } else {
3840             # remove the old order_ident attribute
3841             $e->delete_acq_lineitem_attr($old_attr) or return $e->die_event;
3842         }
3843     }
3844
3845     # make sure we have a local_attr_def to match the source attr def
3846
3847     my $local_def = $e->search_acq_lineitem_local_attr_definition({
3848         code => $source_attr->attr_name
3849     })->[0];
3850
3851     if (!$local_def) {
3852         my $source_def = 
3853             $e->retrieve_acq_lineitem_attr_definition($source_attr->definition);
3854         $local_def = Fieldmapper::acq::lineitem_local_attr_definition->new;
3855         $local_def->code($source_def->code);
3856         $local_def->description($source_def->description);
3857         $local_def = $e->create_acq_lineitem_local_attr_definition($local_def)
3858             or return $e->die_event;
3859     }
3860
3861     # create the new order_ident local attr
3862
3863     my $new_attr = Fieldmapper::acq::lineitem_attr->new;
3864     $new_attr->definition($local_def->id);
3865     $new_attr->attr_type('lineitem_local_attr_definition');
3866     $new_attr->lineitem($li->id);
3867     $new_attr->attr_name($source_attr->attr_name);
3868     $new_attr->attr_value($source_attr->attr_value);
3869     $new_attr->order_ident('t');
3870
3871     $new_attr = $e->create_acq_lineitem_attr($new_attr) 
3872         or return $e->die_event;
3873     
3874     $e->commit;
3875     return $new_attr;
3876 }
3877
3878
3879 # Given an isbn, issn, or upc, add the value to the lineitem marc.
3880 # Upon update, the value will be auto-magically represented as
3881 # a lineitem marc attr.
3882 # If the li is linked to a bib record and the user has the correct
3883 # permissions, update the bib record to match.
3884 sub apply_new_li_ident_attr {
3885     my ($e, $li, $perm_org, $attr_name, $attr_value) = @_;
3886
3887     my %tags = (
3888         isbn => '020',
3889         issn => '022',
3890         upc  => '024'
3891     );
3892
3893     my $marc_field = MARC::Field->new(
3894         $tags{$attr_name}, '', '','a' => $attr_value);
3895
3896     my $li_rec = MARC::Record->new_from_xml($li->marc, 'UTF-8', 'USMARC');
3897     $li_rec->insert_fields_ordered($marc_field);
3898
3899     $li->marc(clean_marc($li_rec));
3900     $li->editor($e->requestor->id);
3901     $li->edit_time('now');
3902
3903     $e->update_acq_lineitem($li) or return (undef, $e->die_event);
3904
3905     my $source_attr = $e->search_acq_lineitem_attr({
3906         attr_name => $attr_name,
3907         attr_value => $attr_value,
3908         attr_type => 'lineitem_marc_attr_definition'
3909     })->[0];
3910
3911     if (!$source_attr) {
3912         $logger->error("ACQ lineitem update failed to produce a matching ".
3913             " marc attribute for $attr_name => $attr_value");
3914         return (undef, OpenILS::Event->new('INTERNAL_SERVER_ERROR'));
3915     }
3916
3917     return ($source_attr) unless 
3918         $li->eg_bib_id and
3919         $e->allowed('ACQ_ADD_LINEITEM_IDENTIFIER', $perm_org);
3920
3921     # li is linked to a bib record and user has the update perms
3922
3923     my $bre = $e->retrieve_biblio_record_entry($li->eg_bib_id);
3924     my $bre_marc = MARC::Record->new_from_xml($bre->marc, 'UTF-8', 'USMARC');
3925     $bre_marc->insert_fields_ordered($marc_field);
3926
3927     $bre->marc(clean_marc($bre_marc));
3928     $bre->editor($e->requestor->id);
3929     $bre->edit_date('now');
3930
3931     $e->update_biblio_record_entry($bre) or return (undef, $e->die_event);
3932
3933     return ($source_attr);
3934 }
3935
3936
3937 1;
3938