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