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