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