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