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