]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Acq/Order.pm
LP 1177388 'Add to Po' Honors default copy count
[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     stream => 1,
2162     signature => {
2163         desc => 'Mark lineitems as received',
2164         params => [
2165             {desc => 'Authentication token', type => 'string'},
2166             {desc => 'lineitem ID list', type => 'array'}
2167         ],
2168         return => {desc =>
2169             q/On success, stream of objects describing changes to LIs and
2170             possibly PO; onerror, Event.  Any event, even after lots of other
2171             objects, should mean general failure of whole batch operation./
2172         }
2173     }
2174 );
2175
2176 sub receive_lineitem_batch_api {
2177     my ($self, $conn, $auth, $li_idlist) = @_;
2178
2179     return unless ref $li_idlist eq 'ARRAY' and @$li_idlist;
2180
2181     my $e = new_editor(xact => 1, authtoken => $auth);
2182     return $e->die_event unless $e->checkauth;
2183
2184     my $mgr = new OpenILS::Application::Acq::BatchManager(
2185         editor => $e, conn => $conn
2186     );
2187
2188     for my $li_id (map { int $_ } @$li_idlist) {
2189         my $li = $e->retrieve_acq_lineitem([
2190             $li_id, {
2191                 flesh => 1,
2192                 flesh_fields => { jub => ['purchase_order'] }
2193             }
2194         ]) or return $e->die_event;
2195
2196         return $e->die_event unless $e->allowed(
2197             'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency
2198         );
2199
2200         receive_lineitem($mgr, $li_id) or return $e->die_event;
2201         $mgr->respond;
2202     }
2203
2204     $e->commit or return $e->die_event;
2205     $mgr->respond_complete;
2206     $mgr->run_post_response_hooks;
2207 }
2208
2209 __PACKAGE__->register_method(
2210     method   => 'rollback_receive_po_api',
2211     api_name => 'open-ils.acq.purchase_order.receive.rollback'
2212 );
2213
2214 sub rollback_receive_po_api {
2215     my($self, $conn, $auth, $po_id) = @_;
2216     my $e = new_editor(xact => 1, authtoken => $auth);
2217     return $e->die_event unless $e->checkauth;
2218     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2219
2220     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2221     return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2222
2223     my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
2224
2225     for my $li_id (@$li_ids) {
2226         rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2227         $mgr->respond;
2228     }
2229
2230     $po->state('on-order');
2231     update_purchase_order($mgr, $po) or return $e->die_event;
2232
2233     $e->commit;
2234     return $mgr->respond_complete;
2235 }
2236
2237
2238 __PACKAGE__->register_method(
2239     method    => 'rollback_receive_lineitem_detail_api',
2240     api_name  => 'open-ils.acq.lineitem_detail.receive.rollback',
2241     signature => {
2242         desc   => 'Mark a lineitem_detail as Un-received',
2243         params => [
2244             {desc => 'Authentication token', type => 'string'},
2245             {desc => 'lineitem detail ID', type => 'number'}
2246         ],
2247         return => {desc =>
2248             "on success, object describing changes to LID and possibly " .
2249             "to LI and PO; on error, Event"
2250         }
2251     }
2252 );
2253
2254 sub rollback_receive_lineitem_detail_api {
2255     my($self, $conn, $auth, $lid_id) = @_;
2256
2257     my $e = new_editor(xact=>1, authtoken=>$auth);
2258     return $e->die_event unless $e->checkauth;
2259     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2260
2261     my $lid = $e->retrieve_acq_lineitem_detail([
2262         $lid_id, {
2263             flesh => 2,
2264             flesh_fields => {
2265                 acqlid => ['lineitem'],
2266                 jub => ['purchase_order']
2267             }
2268         }
2269     ]);
2270     my $li = $lid->lineitem;
2271     my $po = $li->purchase_order;
2272
2273     return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2274
2275     my $result = {};
2276
2277     my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2278         or return $e->die_event;
2279
2280     if (ref $recvd) {
2281         $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2282     } else {
2283         $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2284     }
2285
2286     if ($li->state eq "received") {
2287         $li->state("on-order");
2288         $li = update_lineitem($mgr, $li) or return $e->die_event;
2289         $result->{"li"} = {$li->id => {"state" => $li->state}};
2290     }
2291
2292     if ($po->state eq "received") {
2293         $po->state("on-order");
2294         $po = update_purchase_order($mgr, $po) or return $e->die_event;
2295     }
2296     $result->{"po"} = describe_affected_po($e, $po);
2297
2298     $e->commit and return $result or return $e->die_event;
2299 }
2300
2301 __PACKAGE__->register_method(
2302     method    => 'rollback_receive_lineitem_api',
2303     api_name  => 'open-ils.acq.lineitem.receive.rollback',
2304     signature => {
2305         desc   => 'Mark a lineitem as Un-received',
2306         params => [
2307             {desc => 'Authentication token', type => 'string'},
2308             {desc => 'lineitem ID',          type => 'number'}
2309         ],
2310         return => {desc =>
2311             "on success, object describing changes to LI and possibly PO; " .
2312             "on error, Event"
2313         }
2314     }
2315 );
2316
2317 sub rollback_receive_lineitem_api {
2318     my($self, $conn, $auth, $li_id) = @_;
2319
2320     my $e = new_editor(xact=>1, authtoken=>$auth);
2321     return $e->die_event unless $e->checkauth;
2322     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2323
2324     my $li = $e->retrieve_acq_lineitem([
2325         $li_id, {
2326             "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2327         }
2328     ]);
2329     my $po = $li->purchase_order;
2330
2331     return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2332
2333     $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2334
2335     my $result = {"li" => {$li->id => {"state" => $li->state}}};
2336     if ($po->state eq "received") {
2337         $po->state("on-order");
2338         $po = update_purchase_order($mgr, $po) or return $e->die_event;
2339     }
2340     $result->{"po"} = describe_affected_po($e, $po);
2341
2342     $e->commit and return $result or return $e->die_event;
2343 }
2344
2345 __PACKAGE__->register_method(
2346     method    => 'rollback_receive_lineitem_batch_api',
2347     api_name  => 'open-ils.acq.lineitem.receive.rollback.batch',
2348     stream => 1,
2349     signature => {
2350         desc   => 'Mark a list of lineitems as Un-received',
2351         params => [
2352             {desc => 'Authentication token', type => 'string'},
2353             {desc => 'lineitem ID list',     type => 'array'}
2354         ],
2355         return => {desc =>
2356             q/on success, a stream of objects describing changes to LI and
2357             possibly PO; on error, Event. Any event means all previously
2358             returned objects indicate changes that didn't really happen./
2359         }
2360     }
2361 );
2362
2363 sub rollback_receive_lineitem_batch_api {
2364     my ($self, $conn, $auth, $li_idlist) = @_;
2365
2366     return unless ref $li_idlist eq 'ARRAY' and @$li_idlist;
2367
2368     my $e = new_editor(xact => 1, authtoken => $auth);
2369     return $e->die_event unless $e->checkauth;
2370
2371     my $mgr = new OpenILS::Application::Acq::BatchManager(
2372         editor => $e, conn => $conn
2373     );
2374
2375     for my $li_id (map { int $_ } @$li_idlist) {
2376         my $li = $e->retrieve_acq_lineitem([
2377             $li_id, {
2378                 "flesh" => 1,
2379                 "flesh_fields" => {"jub" => ["purchase_order"]}
2380             }
2381         ]);
2382
2383         my $po = $li->purchase_order;
2384
2385         return $e->die_event unless
2386             $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2387
2388         $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2389
2390         my $result = {"li" => {$li->id => {"state" => $li->state}}};
2391         if ($po->state eq "received") { # should happen first time, not after
2392             $po->state("on-order");
2393             $po = update_purchase_order($mgr, $po) or return $e->die_event;
2394         }
2395         $result->{"po"} = describe_affected_po($e, $po);
2396
2397         $mgr->respond(%$result);
2398     }
2399
2400     $e->commit or return $e->die_event;
2401     $mgr->respond_complete;
2402     $mgr->run_post_response_hooks;
2403 }
2404
2405
2406 __PACKAGE__->register_method(
2407     method    => 'set_lineitem_price_api',
2408     api_name  => 'open-ils.acq.lineitem.price.set',
2409     signature => {
2410         desc   => 'Set lineitem price.  If debits already exist, update them as well',
2411         params => [
2412             {desc => 'Authentication token', type => 'string'},
2413             {desc => 'lineitem ID',          type => 'number'}
2414         ],
2415         return => {desc => 'status blob, Event on error'}
2416     }
2417 );
2418
2419 sub set_lineitem_price_api {
2420     my($self, $conn, $auth, $li_id, $price) = @_;
2421
2422     my $e = new_editor(xact=>1, authtoken=>$auth);
2423     return $e->die_event unless $e->checkauth;
2424     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2425
2426     my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2427     return $evt if $evt;
2428
2429     $li->estimated_unit_price($price);
2430     update_lineitem($mgr, $li) or return $e->die_event;
2431
2432     my $lid_ids = $e->search_acq_lineitem_detail(
2433         {lineitem => $li_id, fund_debit => {'!=' => undef}}, 
2434         {idlist => 1}
2435     );
2436
2437     for my $lid_id (@$lid_ids) {
2438
2439         my $lid = $e->retrieve_acq_lineitem_detail([
2440             $lid_id, {
2441             flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2442         ]);
2443
2444         $lid->fund_debit->amount($price);
2445         $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2446         $mgr->add_lid;
2447         $mgr->respond;
2448     }
2449
2450     $e->commit;
2451     return $mgr->respond_complete;
2452 }
2453
2454
2455 __PACKAGE__->register_method(
2456     method    => 'clone_picklist_api',
2457     api_name  => 'open-ils.acq.picklist.clone',
2458     signature => {
2459         desc   => 'Clones a picklist, including lineitem and lineitem details',
2460         params => [
2461             {desc => 'Authentication token', type => 'string'},
2462             {desc => 'Picklist ID', type => 'number'},
2463             {desc => 'New Picklist Name', type => 'string'}
2464         ],
2465         return => {desc => 'status blob, Event on error'}
2466     }
2467 );
2468
2469 sub clone_picklist_api {
2470     my($self, $conn, $auth, $pl_id, $name) = @_;
2471
2472     my $e = new_editor(xact=>1, authtoken=>$auth);
2473     return $e->die_event unless $e->checkauth;
2474     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2475
2476     my $old_pl = $e->retrieve_acq_picklist($pl_id);
2477     my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2478
2479     my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2480
2481     # get the current user
2482     my $cloner = $mgr->editor->requestor->id;
2483
2484     for my $li_id (@$li_ids) {
2485
2486         # copy the lineitems' MARC
2487         my $marc = ($e->retrieve_acq_lineitem($li_id))->marc;
2488
2489         # create a skeletal clone of the item
2490         my $li = Fieldmapper::acq::lineitem->new;
2491         $li->creator($cloner);
2492         $li->selector($cloner);
2493         $li->editor($cloner);
2494         $li->marc($marc);
2495
2496         my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2497
2498         $mgr->respond;
2499     }
2500
2501     $e->commit;
2502     return $mgr->respond_complete;
2503 }
2504
2505
2506 __PACKAGE__->register_method(
2507     method    => 'merge_picklist_api',
2508     api_name  => 'open-ils.acq.picklist.merge',
2509     signature => {
2510         desc   => 'Merges 2 or more picklists into a single list',
2511         params => [
2512             {desc => 'Authentication token', type => 'string'},
2513             {desc => 'Lead Picklist ID', type => 'number'},
2514             {desc => 'List of subordinate picklist IDs', type => 'array'}
2515         ],
2516         return => {desc => 'status blob, Event on error'}
2517     }
2518 );
2519
2520 sub merge_picklist_api {
2521     my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2522
2523     my $e = new_editor(xact=>1, authtoken=>$auth);
2524     return $e->die_event unless $e->checkauth;
2525     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2526
2527     # XXX perms on each picklist modified
2528
2529     $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2530     # point all of the lineitems at the lead picklist
2531     my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2532
2533     for my $li_id (@$li_ids) {
2534         my $li = $e->retrieve_acq_lineitem($li_id);
2535         $li->picklist($lead_pl);
2536         update_lineitem($mgr, $li) or return $e->die_event;
2537         $mgr->respond;
2538     }
2539
2540     # now delete the subordinate lists
2541     for my $pl_id (@$pl_list) {
2542         my $pl = $e->retrieve_acq_picklist($pl_id);
2543         $e->delete_acq_picklist($pl) or return $e->die_event;
2544     }
2545
2546     update_picklist($mgr, $lead_pl) or return $e->die_event;
2547
2548     $e->commit;
2549     return $mgr->respond_complete;
2550 }
2551
2552
2553 __PACKAGE__->register_method(
2554     method    => 'delete_picklist_api',
2555     api_name  => 'open-ils.acq.picklist.delete',
2556     signature => {
2557         desc   => q/Deletes a picklist.  It also deletes any lineitems in the "new" state. / .
2558                   q/Other attached lineitems are detached/,
2559         params => [
2560             {desc => 'Authentication token',  type => 'string'},
2561             {desc => 'Picklist ID to delete', type => 'number'}
2562         ],
2563         return => {desc => '1 on success, Event on error'}
2564     }
2565 );
2566
2567 sub delete_picklist_api {
2568     my($self, $conn, $auth, $picklist_id) = @_;
2569     my $e = new_editor(xact=>1, authtoken=>$auth);
2570     return $e->die_event unless $e->checkauth;
2571     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2572     my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2573     delete_picklist($mgr, $pl) or return $e->die_event;
2574     $e->commit;
2575     return $mgr->respond_complete;
2576 }
2577
2578
2579
2580 __PACKAGE__->register_method(
2581     method   => 'activate_purchase_order',
2582     api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2583 );
2584
2585 __PACKAGE__->register_method(
2586     method    => 'activate_purchase_order',
2587     api_name  => 'open-ils.acq.purchase_order.activate',
2588     signature => {
2589         desc => q/Activates a purchase order.  This updates the status of the PO / .
2590                 q/and Lineitems to 'on-order'.  Activated PO's are ready for EDI delivery if appropriate./,
2591         params => [
2592             {desc => 'Authentication token', type => 'string'},
2593             {desc => 'Purchase ID', type => 'number'}
2594         ],
2595         return => {desc => '1 on success, Event on error'}
2596     }
2597 );
2598
2599 sub activate_purchase_order {
2600     my($self, $conn, $auth, $po_id, $vandelay, $options) = @_;
2601     $options ||= {};
2602
2603     my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2604     my $e = new_editor(authtoken=>$auth);
2605     return $e->die_event unless $e->checkauth;
2606     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2607     my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run, $options);
2608     return $e->die_event if $die_event;
2609     $conn->respond_complete(1);
2610     $mgr->run_post_response_hooks unless $dry_run;
2611     return undef;
2612 }
2613
2614 # xacts managed within
2615 sub activate_purchase_order_impl {
2616     my ($mgr, $po_id, $vandelay, $dry_run, $options) = @_;
2617
2618     # read-only until lineitem asset creation
2619     my $e = $mgr->editor;
2620     $e->xact_begin;
2621
2622     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2623     return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2624
2625     return $e->die_event(OpenILS::Event->new('PO_ALREADY_ACTIVATED'))
2626         if $po->order_date; # PO cannot be re-activated
2627
2628     my $provider = $e->retrieve_acq_provider($po->provider);
2629
2630     # find lineitems and create assets for all
2631
2632     my $query = {   
2633         purchase_order => $po_id, 
2634         state => [qw/pending-order new order-ready/]
2635     };
2636
2637     my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2638
2639     my $vl_resp; # imported li's and the queue the managing queue
2640     if (!$dry_run) {
2641         $e->rollback; # read-only thus far
2642         $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2643             or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2644         $e->xact_begin;
2645     }
2646
2647     # create fund debits for lineitems 
2648
2649     for my $li_id (@$li_ids) {
2650         my $li = $e->retrieve_acq_lineitem($li_id);
2651         
2652         if (!$li->eg_bib_id and !$dry_run) {
2653             # we encountered a lineitem that was not successfully imported.
2654             # we cannot continue.  rollback and report.
2655             $e->rollback;
2656             return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2657         }
2658
2659         $li->state('on-order');
2660         $li->claim_policy($provider->default_claim_policy)
2661             if $provider->default_claim_policy and !$li->claim_policy;
2662         create_lineitem_debits($mgr, $li, $dry_run, $options) or return $e->die_event;
2663         update_lineitem($mgr, $li) or return $e->die_event;
2664         $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2665         $mgr->respond;
2666     }
2667
2668     # create po-item debits
2669
2670     for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2671
2672         my $debit = create_fund_debit(
2673             $mgr, 
2674             $dry_run, 
2675             debit_type => 'direct_charge', # to match invoicing
2676             origin_amount => $po_item->estimated_cost,
2677             origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2678             amount => $po_item->estimated_cost,
2679             fund => $po_item->fund
2680         ) or return $e->die_event;
2681         $po_item->fund_debit($debit->id);
2682         $e->update_acq_po_item($po_item) or return $e->die_event;
2683         $mgr->respond;
2684     }
2685
2686     # mark PO as ordered
2687
2688     $po->state('on-order');
2689     $po->order_date('now');
2690     update_purchase_order($mgr, $po) or return $e->die_event;
2691
2692     # clean up the xact
2693     $dry_run and $e->rollback or $e->commit;
2694
2695     # tell the world we activated a PO
2696     $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2697
2698     return undef;
2699 }
2700
2701
2702 __PACKAGE__->register_method(
2703     method    => 'split_purchase_order_by_lineitems',
2704     api_name  => 'open-ils.acq.purchase_order.split_by_lineitems',
2705     signature => {
2706         desc   => q/Splits a PO into many POs, 1 per lineitem.  Only works for / .
2707                   q/POs a) with more than one lineitems, and b) in the "pending" state./,
2708         params => [
2709             {desc => 'Authentication token', type => 'string'},
2710             {desc => 'Purchase order ID',    type => 'number'}
2711         ],
2712         return => {desc => 'list of new PO IDs on success, Event on error'}
2713     }
2714 );
2715
2716 sub split_purchase_order_by_lineitems {
2717     my ($self, $conn, $auth, $po_id) = @_;
2718
2719     my $e = new_editor("xact" => 1, "authtoken" => $auth);
2720     return $e->die_event unless $e->checkauth;
2721
2722     my $po = $e->retrieve_acq_purchase_order([
2723         $po_id, {
2724             "flesh" => 1,
2725             "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2726         }
2727     ]) or return $e->die_event;
2728
2729     return $e->die_event
2730         unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2731
2732     unless ($po->state eq "pending") {
2733         $e->rollback;
2734         return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2735     }
2736
2737     unless (@{$po->lineitems} > 1) {
2738         $e->rollback;
2739         return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2740     }
2741
2742     # To split an existing PO into many, it seems unwise to just delete the
2743     # original PO, so we'll instead detach all of the original POs' lineitems
2744     # but the first, then create new POs for each of the remaining LIs, and
2745     # then attach the LIs to their new POs.
2746
2747     my @po_ids = ($po->id);
2748     my @moving_li = @{$po->lineitems};
2749     shift @moving_li;    # discard first LI
2750
2751     foreach my $li (@moving_li) {
2752         my $new_po = $po->clone;
2753         $new_po->clear_id;
2754         $new_po->clear_name;
2755         $new_po->creator($e->requestor->id);
2756         $new_po->editor($e->requestor->id);
2757         $new_po->owner($e->requestor->id);
2758         $new_po->edit_time("now");
2759         $new_po->create_time("now");
2760
2761         $new_po = $e->create_acq_purchase_order($new_po);
2762
2763         # Clone any notes attached to the old PO and attach to the new one.
2764         foreach my $note (@{$po->notes}) {
2765             my $new_note = $note->clone;
2766             $new_note->clear_id;
2767             $new_note->edit_time("now");
2768             $new_note->purchase_order($new_po->id);
2769             $e->create_acq_po_note($new_note);
2770         }
2771
2772         $li->edit_time("now");
2773         $li->purchase_order($new_po->id);
2774         $e->update_acq_lineitem($li);
2775
2776         push @po_ids, $new_po->id;
2777     }
2778
2779     $po->edit_time("now");
2780     $e->update_acq_purchase_order($po);
2781
2782     return \@po_ids if $e->commit;
2783     return $e->die_event;
2784 }
2785
2786
2787 sub not_cancelable {
2788     my $o = shift;
2789     (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2790 }
2791
2792 __PACKAGE__->register_method(
2793     method => "cancel_purchase_order_api",
2794     api_name    => "open-ils.acq.purchase_order.cancel",
2795     signature => {
2796         desc => q/Cancels an on-order purchase order/,
2797         params => [
2798             {desc => "Authentication token", type => "string"},
2799             {desc => "PO ID to cancel", type => "number"},
2800             {desc => "Cancel reason ID", type => "number"}
2801         ],
2802         return => {desc => q/Object describing changed POs, LIs and LIDs
2803             on success; Event on error./}
2804     }
2805 );
2806
2807 sub cancel_purchase_order_api {
2808     my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2809
2810     my $e = new_editor("xact" => 1, "authtoken" => $auth);
2811     return $e->die_event unless $e->checkauth;
2812     my $mgr = new OpenILS::Application::Acq::BatchManager(
2813         "editor" => $e, "conn" => $conn
2814     );
2815
2816     $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2817         return new OpenILS::Event(
2818             "BAD_PARAMS", "note" => "Provide cancel reason ID"
2819         );
2820
2821     my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2822         return $e->die_event;
2823     if (not_cancelable($result)) { # event not from CStoreEditor
2824         $e->rollback;
2825         return $result;
2826     } elsif ($result == -1) {
2827         $e->rollback;
2828         return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2829     }
2830
2831     $e->commit or return $e->die_event;
2832
2833     # XXX create purchase order status events?
2834
2835     if ($mgr->{post_commit}) {
2836         foreach my $func (@{$mgr->{post_commit}}) {
2837             $func->();
2838         }
2839     }
2840
2841     return $result;
2842 }
2843
2844 sub cancel_purchase_order {
2845     my ($mgr, $po_id, $cancel_reason) = @_;
2846
2847     my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2848
2849     # XXX is "cancelled" a typo?  It's not correct US spelling, anyway.
2850     # Depending on context, this may not warrant an event.
2851     return -1 if $po->state eq "cancelled";
2852
2853     # But this always does.
2854     return new OpenILS::Event(
2855         "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2856     ) unless ($po->state eq "on-order" or $po->state eq "pending");
2857
2858     return 0 unless
2859         $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2860
2861     $po->state("cancelled");
2862     $po->cancel_reason($cancel_reason->id);
2863
2864     my $li_ids = $mgr->editor->search_acq_lineitem(
2865         {"purchase_order" => $po_id}, {"idlist" => 1}
2866     );
2867
2868     my $result = {"li" => {}, "lid" => {}};
2869     foreach my $li_id (@$li_ids) {
2870         my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2871             or return 0;
2872
2873         next if $li_result == -1; # already canceled:skip.
2874         return $li_result if not_cancelable($li_result); # not cancelable:stop.
2875
2876         # Merge in each LI result (there's only going to be
2877         # one per call to cancel_lineitem).
2878         my ($k, $v) = each %{$li_result->{"li"}};
2879         $result->{"li"}->{$k} = $v;
2880
2881         # Merge in each LID result (there may be many per call to
2882         # cancel_lineitem).
2883         while (($k, $v) = each %{$li_result->{"lid"}}) {
2884             $result->{"lid"}->{$k} = $v;
2885         }
2886     }
2887
2888     # TODO who/what/where/how do we indicate this change for electronic orders?
2889     # TODO return changes to encumbered/spent
2890     # TODO maybe cascade up from smaller object to container object if last
2891     # smaller object in the container has been canceled?
2892
2893     update_purchase_order($mgr, $po) or return 0;
2894     $result->{"po"} = {
2895         $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2896     };
2897     return $result;
2898 }
2899
2900
2901 __PACKAGE__->register_method(
2902     method => "cancel_lineitem_api",
2903     api_name    => "open-ils.acq.lineitem.cancel",
2904     signature => {
2905         desc => q/Cancels an on-order lineitem/,
2906         params => [
2907             {desc => "Authentication token", type => "string"},
2908             {desc => "Lineitem ID to cancel", type => "number"},
2909             {desc => "Cancel reason ID", type => "number"}
2910         ],
2911         return => {desc => q/Object describing changed LIs and LIDs on success;
2912             Event on error./}
2913     }
2914 );
2915
2916 __PACKAGE__->register_method(
2917     method => "cancel_lineitem_api",
2918     api_name    => "open-ils.acq.lineitem.cancel.batch",
2919     signature => {
2920         desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2921         return => {desc => q/Object describing changed LIs and LIDs on success;
2922             Event on error./}
2923     }
2924 );
2925
2926 sub cancel_lineitem_api {
2927     my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2928
2929     my $batched = $self->api_name =~ /\.batch/;
2930
2931     my $e = new_editor("xact" => 1, "authtoken" => $auth);
2932     return $e->die_event unless $e->checkauth;
2933     my $mgr = new OpenILS::Application::Acq::BatchManager(
2934         "editor" => $e, "conn" => $conn
2935     );
2936
2937     $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2938         return new OpenILS::Event(
2939             "BAD_PARAMS", "note" => "Provide cancel reason ID"
2940         );
2941
2942     my ($result, $maybe_event);
2943
2944     if ($batched) {
2945         $result = {"li" => {}, "lid" => {}};
2946         foreach my $one_li_id (@$li_id) {
2947             my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2948                 return $e->die_event;
2949             if (not_cancelable($one)) {
2950                 $maybe_event = $one;
2951             } elsif ($result == -1) {
2952                 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2953             } else {
2954                 my ($k, $v);
2955                 if ($one->{"li"}) {
2956                     while (($k, $v) = each %{$one->{"li"}}) {
2957                         $result->{"li"}->{$k} = $v;
2958                     }
2959                 }
2960                 if ($one->{"lid"}) {
2961                     while (($k, $v) = each %{$one->{"lid"}}) {
2962                         $result->{"lid"}->{$k} = $v;
2963                     }
2964                 }
2965             }
2966         }
2967     } else {
2968         $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2969             return $e->die_event;
2970
2971         if (not_cancelable($result)) {
2972             $e->rollback;
2973             return $result;
2974         } elsif ($result == -1) {
2975             $e->rollback;
2976             return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2977         }
2978     }
2979
2980     if ($batched and not scalar keys %{$result->{"li"}}) {
2981         $e->rollback;
2982         return $maybe_event;
2983     } else {
2984         $e->commit or return $e->die_event;
2985         # create_lineitem_status_events should handle array li_id ok
2986         create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2987
2988         if ($mgr->{post_commit}) {
2989             foreach my $func (@{$mgr->{post_commit}}) {
2990                 $func->();
2991             }
2992         }
2993
2994         return $result;
2995     }
2996 }
2997
2998 sub cancel_lineitem {
2999     my ($mgr, $li_id, $cancel_reason) = @_;
3000     my $li = $mgr->editor->retrieve_acq_lineitem([
3001         $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
3002     ]) or return 0;
3003
3004     return 0 unless $mgr->editor->allowed(
3005         "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
3006     );
3007
3008     # Depending on context, this may not warrant an event.
3009     return -1 if $li->state eq "cancelled";
3010
3011     # But this always does.  Note that this used to be looser, but you can
3012     # no longer cancel lineitems that lack a PO or that are in "pending-order"
3013     # state (you could in the past).
3014     return new OpenILS::Event(
3015         "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
3016     ) unless $li->purchase_order and $li->state eq "on-order";
3017
3018     $li->state("cancelled");
3019     $li->cancel_reason($cancel_reason->id);
3020
3021     my $lids = $mgr->editor->search_acq_lineitem_detail([{
3022         "lineitem" => $li_id
3023     }, {
3024         flesh => 1,
3025         flesh_fields => { acqlid => ['eg_copy_id'] }
3026     }]);
3027
3028     my $result = {"lid" => {}};
3029     my $copies = [];
3030     foreach my $lid (@$lids) {
3031         my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
3032             or return 0;
3033
3034         # gathering any real copies for deletion
3035         if ($lid->eg_copy_id) {
3036             $lid->eg_copy_id->isdeleted('t');
3037             push @$copies, $lid->eg_copy_id;
3038         }
3039
3040         next if $lid_result == -1; # already canceled: just skip it.
3041         return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
3042
3043         # Merge in each LID result (there's only going to be one per call to
3044         # cancel_lineitem_detail).
3045         my ($k, $v) = each %{$lid_result->{"lid"}};
3046         $result->{"lid"}->{$k} = $v;
3047     }
3048
3049     # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
3050     # Delete empty bibs according org unit setting
3051     my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
3052         $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
3053     if (scalar(@$copies)>0) {
3054         my $override = 1;
3055         my $delete_stats = undef;
3056         my $retarget_holds = [];
3057         my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
3058             $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
3059
3060         if( $cat_evt ) {
3061             $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
3062             return new OpenILS::Event(
3063                 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
3064             );
3065         }
3066
3067         # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
3068         #my $ses = OpenSRF::AppSession->create('open-ils.circ');
3069         #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
3070     }
3071
3072     # if we have a bib, check to see whether it has been deleted.  if so, cancel any active holds targeting that bib
3073     if ($li->eg_bib_id) {
3074         my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
3075             "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
3076         );
3077         if ($U->is_true($bib->deleted)) {
3078             my $holds = $mgr->editor->search_action_hold_request(
3079                 {   cancel_time => undef,
3080                     fulfillment_time => undef,
3081                     target => $li->eg_bib_id
3082                 }
3083             );
3084
3085             my %cached_usr_home_ou = ();
3086
3087             for my $hold (@$holds) {
3088
3089                 $logger->info("Cancelling hold ".$hold->id.
3090                     " due to acq lineitem cancellation.");
3091
3092                 $hold->cancel_time('now');
3093                 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
3094                 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
3095                 unless($mgr->editor->update_action_hold_request($hold)) {
3096                     my $evt = $mgr->editor->event;
3097                     $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
3098                     return new OpenILS::Event(
3099                         "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
3100                     );
3101                 }
3102                 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
3103                     $mgr->{post_commit} = [];
3104                 }
3105                 push @{ $mgr->{post_commit} }, sub {
3106                     my $home_ou = $cached_usr_home_ou{$hold->usr};
3107                     if (! $home_ou) {
3108                         my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
3109                         $home_ou = $user->home_ou;
3110                         $cached_usr_home_ou{$hold->usr} = $home_ou;
3111                     }
3112                     $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
3113                 };
3114             }
3115         }
3116     }
3117
3118     update_lineitem($mgr, $li) or return 0;
3119     $result->{"li"} = {
3120         $li_id => {
3121             "state" => $li->state,
3122             "cancel_reason" => $cancel_reason
3123         }
3124     };
3125     return $result;
3126 }
3127
3128
3129 __PACKAGE__->register_method(
3130     method => "cancel_lineitem_detail_api",
3131     api_name    => "open-ils.acq.lineitem_detail.cancel",
3132     signature => {
3133         desc => q/Cancels an on-order lineitem detail/,
3134         params => [
3135             {desc => "Authentication token", type => "string"},
3136             {desc => "Lineitem detail ID to cancel", type => "number"},
3137             {desc => "Cancel reason ID", type => "number"}
3138         ],
3139         return => {desc => q/Object describing changed LIDs on success;
3140             Event on error./}
3141     }
3142 );
3143
3144 sub cancel_lineitem_detail_api {
3145     my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
3146
3147     my $e = new_editor("xact" => 1, "authtoken" => $auth);
3148     return $e->die_event unless $e->checkauth;
3149     my $mgr = new OpenILS::Application::Acq::BatchManager(
3150         "editor" => $e, "conn" => $conn
3151     );
3152
3153     $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
3154         return new OpenILS::Event(
3155             "BAD_PARAMS", "note" => "Provide cancel reason ID"
3156         );
3157
3158     my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
3159         return $e->die_event;
3160
3161     if (not_cancelable($result)) {
3162         $e->rollback;
3163         return $result;
3164     } elsif ($result == -1) {
3165         $e->rollback;
3166         return new OpenILS::Event("ACQ_ALREADY_CANCELED");
3167     }
3168
3169     $e->commit or return $e->die_event;
3170
3171     # XXX create lineitem detail status events?
3172     return $result;
3173 }
3174
3175 sub cancel_lineitem_detail {
3176     my ($mgr, $lid_id, $cancel_reason) = @_;
3177     my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
3178         $lid_id, {
3179             "flesh" => 2,
3180             "flesh_fields" => {
3181                 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
3182             }
3183         }
3184     ]) or return 0;
3185
3186     # Depending on context, this may not warrant an event.
3187     return -1 if $lid->cancel_reason;
3188
3189     # But this always does.
3190     return new OpenILS::Event(
3191         "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
3192     ) unless (
3193         (! $lid->lineitem->purchase_order) or
3194         (
3195             (not $lid->recv_time) and
3196             $lid->lineitem and
3197             $lid->lineitem->purchase_order and (
3198                 $lid->lineitem->state eq "on-order" or
3199                 $lid->lineitem->state eq "pending-order"
3200             )
3201         )
3202     );
3203
3204     return 0 unless $mgr->editor->allowed(
3205         "CREATE_PURCHASE_ORDER",
3206         $lid->lineitem->purchase_order->ordering_agency
3207     ) or (! $lid->lineitem->purchase_order);
3208
3209     $lid->cancel_reason($cancel_reason->id);
3210
3211     unless($U->is_true($cancel_reason->keep_debits)) {
3212         my $debit_id = $lid->fund_debit;
3213         $lid->clear_fund_debit;
3214
3215         if($debit_id) {
3216             # item is cancelled.  Remove the fund debit.
3217             my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
3218             if (!$U->is_true($debit->encumbrance)) {
3219                 $mgr->editor->rollback;
3220                 return OpenILS::Event->new('ACQ_NOT_CANCELABLE', 
3221                     note => "Debit is marked as paid: $debit_id");
3222             }
3223             $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
3224         }
3225     }
3226
3227     # XXX LIDs don't have either an editor or a edit_time field. Should we
3228     # update these on the LI when we alter an LID?
3229     $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
3230
3231     return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
3232 }
3233
3234
3235 __PACKAGE__->register_method(
3236     method    => 'user_requests',
3237     api_name  => 'open-ils.acq.user_request.retrieve.by_user_id',
3238     stream    => 1,
3239     signature => {
3240         desc   => 'Retrieve fleshed user requests and related data for a given user.',
3241         params => [
3242             { desc => 'Authentication token',      type => 'string' },
3243             { desc => 'User ID of the owner, or array of IDs',      },
3244             { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3245               type => 'object'
3246             }
3247         ],
3248         return => {
3249             desc => 'Fleshed user requests and related data',
3250             type => 'object'
3251         }
3252     }
3253 );
3254
3255 __PACKAGE__->register_method(
3256     method    => 'user_requests',
3257     api_name  => 'open-ils.acq.user_request.retrieve.by_home_ou',
3258     stream    => 1,
3259     signature => {
3260         desc   => 'Retrieve fleshed user requests and related data for a given org unit or units.',
3261         params => [
3262             { desc => 'Authentication token',      type => 'string' },
3263             { desc => 'Org unit ID, or array of IDs',               },
3264             { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3265               type => 'object'
3266             }
3267         ],
3268         return => {
3269             desc => 'Fleshed user requests and related data',
3270             type => 'object'
3271         }
3272     }
3273 );
3274
3275 sub user_requests {
3276     my($self, $conn, $auth, $search_value, $options) = @_;
3277     my $e = new_editor(authtoken => $auth);
3278     return $e->event unless $e->checkauth;
3279     my $rid = $e->requestor->id;
3280     $options ||= {};
3281
3282     my $query = {
3283         "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
3284         "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
3285         "where"=>{
3286             "+jub"=> {
3287                 "-or" => [
3288                     {"id"=>undef}, # this with the left-join pulls in requests without lineitems
3289                     {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
3290                 ]
3291             }
3292         },
3293         "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
3294     };
3295
3296     foreach (qw/ order_by limit offset /) {
3297         $query->{$_} = $options->{$_} if defined $options->{$_};
3298     }
3299     if (defined $options->{'state'}) {
3300         $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};        
3301     }
3302
3303     if ($self->api_name =~ /by_user_id/) {
3304         $query->{'where'}->{'usr'} = $search_value;
3305     } else {
3306         $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3307     }
3308
3309     my $pertinent_ids = $e->json_query($query);
3310
3311     my %perm_test = ();
3312     for my $id_blob (@$pertinent_ids) {
3313         if ($rid != $id_blob->{usr_id}) {
3314             if (!defined $perm_test{ $id_blob->{home_ou} }) {
3315                 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3316             }
3317             if (!$perm_test{ $id_blob->{home_ou} }) {
3318                 next; # failed test
3319             }
3320         }
3321         my $aur_obj = $e->retrieve_acq_user_request([
3322             $id_blob->{id},
3323             {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3324         ]);
3325         if (! $aur_obj) { next; }
3326
3327         if ($aur_obj->lineitem()) {
3328             $aur_obj->lineitem()->clear_marc();
3329         }
3330         $conn->respond($aur_obj);
3331     }
3332
3333     return undef;
3334 }
3335
3336 __PACKAGE__->register_method (
3337     method    => 'update_user_request',
3338     api_name  => 'open-ils.acq.user_request.cancel.batch',
3339     stream    => 1,
3340     signature => {
3341         desc   => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether.  The '    .
3342                   'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3343         params => [
3344             { desc => 'Authentication token',              type => 'string' },
3345             { desc => 'ID or array of IDs for the user requests to cancel'  },
3346             { desc => 'Cancel Reason ID (optional)',       type => 'string' }
3347         ],
3348         return => {
3349             desc => 'progress object, event on error',
3350         }
3351     }
3352 );
3353 __PACKAGE__->register_method (
3354     method    => 'update_user_request',
3355     api_name  => 'open-ils.acq.user_request.set_no_hold.batch',
3356     stream    => 1,
3357     signature => {
3358         desc   => 'Remove the hold from a user request or set of requests',
3359         params => [
3360             { desc => 'Authentication token',              type => 'string' },
3361             { desc => 'ID or array of IDs for the user requests to modify'  }
3362         ],
3363         return => {
3364             desc => 'progress object, event on error',
3365         }
3366     }
3367 );
3368
3369 sub update_user_request {
3370     my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3371     my $e = new_editor(xact => 1, authtoken => $auth);
3372     return $e->die_event unless $e->checkauth;
3373     my $rid = $e->requestor->id;
3374
3375     my $x = 1;
3376     my %perm_test = ();
3377     for my $id (@$aur_ids) {
3378
3379         my $aur_obj = $e->retrieve_acq_user_request([
3380             $id,
3381             {   flesh => 1,
3382                 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3383             }
3384         ]) or return $e->die_event;
3385
3386         my $context_org = $aur_obj->usr()->home_ou();
3387         $aur_obj->usr( $aur_obj->usr()->id() );
3388
3389         if ($rid != $aur_obj->usr) {
3390             if (!defined $perm_test{ $context_org }) {
3391                 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3392             }
3393             if (!$perm_test{ $context_org }) {
3394                 next; # failed test
3395             }
3396         }
3397
3398         if($self->api_name =~ /set_no_hold/) {
3399             if ($U->is_true($aur_obj->hold)) { 
3400                 $aur_obj->hold(0); 
3401                 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3402             }
3403         }
3404
3405         if($self->api_name =~ /cancel/) {
3406             if ( $cancel_reason ) {
3407                 $aur_obj->cancel_reason( $cancel_reason );
3408                 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3409                 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3410             } else {
3411                 $e->delete_acq_user_request($aur_obj);
3412             }
3413         }
3414
3415         $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3416     }
3417
3418     $e->commit;
3419     return {complete => 1};
3420 }
3421
3422 __PACKAGE__->register_method (
3423     method    => 'new_user_request',
3424     api_name  => 'open-ils.acq.user_request.create',
3425     signature => {
3426         desc   => 'Create a new user request object in the DB',
3427         param  => [
3428             { desc => 'Authentication token',   type => 'string' },
3429             { desc => 'User request data hash.  Hash keys match the fields for the "aur" object', type => 'object' }
3430         ],
3431         return => {
3432             desc => 'The created user request object, or event on error'
3433         }
3434     }
3435 );
3436
3437 sub new_user_request {
3438     my($self, $conn, $auth, $form_data) = @_;
3439     my $e = new_editor(xact => 1, authtoken => $auth);
3440     return $e->die_event unless $e->checkauth;
3441     my $rid = $e->requestor->id;
3442     my $target_user_fleshed;
3443     if (! defined $$form_data{'usr'}) {
3444         $$form_data{'usr'} = $rid;
3445     }
3446     if ($$form_data{'usr'} != $rid) {
3447         # See if the requestor can place the request on behalf of a different user.
3448         $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3449         $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3450     } else {
3451         $target_user_fleshed = $e->requestor;
3452         $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3453     }
3454     if (! defined $$form_data{'pickup_lib'}) {
3455         if ($target_user_fleshed->ws_ou) {
3456             $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3457         } else {
3458             $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3459         }
3460     }
3461     if (! defined $$form_data{'request_type'}) {
3462         $$form_data{'request_type'} = 1; # Books
3463     }
3464     my $aur_obj = new Fieldmapper::acq::user_request; 
3465     $aur_obj->isnew(1);
3466     $aur_obj->usr( $$form_data{'usr'} );
3467     $aur_obj->request_date( 'now' );
3468     for my $field ( keys %$form_data ) {
3469         if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3470             $aur_obj->$field( $$form_data{$field} );
3471         }
3472     }
3473
3474     $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3475
3476     $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3477
3478     return $aur_obj;
3479 }
3480
3481 sub create_user_request_events {
3482     my($e, $user_reqs, $hook) = @_;
3483
3484     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3485     $ses->connect;
3486
3487     my %cached_usr_home_ou = ();
3488     for my $user_req (@$user_reqs) {
3489         my $home_ou = $cached_usr_home_ou{$user_req->usr};
3490         if (! $home_ou) {
3491             my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3492             $home_ou = $user->home_ou;
3493             $cached_usr_home_ou{$user_req->usr} = $home_ou;
3494         }
3495         my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3496         $req->recv;
3497     }
3498
3499     $ses->disconnect;
3500     return undef;
3501 }
3502
3503
3504 __PACKAGE__->register_method(
3505     method => "po_note_CUD_batch",
3506     api_name => "open-ils.acq.po_note.cud.batch",
3507     stream => 1,
3508     signature => {
3509         desc => q/Manage purchase order notes/,
3510         params => [
3511             {desc => "Authentication token", type => "string"},
3512             {desc => "List of po_notes to manage", type => "array"},
3513         ],
3514         return => {desc => "Stream of successfully managed objects"}
3515     }
3516 );
3517
3518 sub po_note_CUD_batch {
3519     my ($self, $conn, $auth, $notes) = @_;
3520
3521     my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3522     return $e->die_event unless $e->checkauth;
3523     # XXX perms
3524
3525     my $total = @$notes;
3526     my $count = 0;
3527
3528     foreach my $note (@$notes) {
3529
3530         $note->editor($e->requestor->id);
3531         $note->edit_time("now");
3532
3533         if ($note->isnew) {
3534             $note->creator($e->requestor->id);
3535             $note = $e->create_acq_po_note($note) or return $e->die_event;
3536         } elsif ($note->isdeleted) {
3537             $e->delete_acq_po_note($note) or return $e->die_event;
3538         } elsif ($note->ischanged) {
3539             $e->update_acq_po_note($note) or return $e->die_event;
3540         }
3541
3542         unless ($note->isdeleted) {
3543             $note = $e->retrieve_acq_po_note($note->id) or
3544                 return $e->die_event;
3545         }
3546
3547         $conn->respond(
3548             {"maximum" => $total, "progress" => ++$count, "note" => $note}
3549         );
3550     }
3551
3552     $e->commit and $conn->respond_complete or return $e->die_event;
3553 }
3554
3555
3556 # retrieves a lineitem, fleshes its PO and PL, checks perms
3557 # returns ($li, $evt, $org)
3558 sub fetch_and_check_li {
3559     my $e = shift;
3560     my $li_id = shift;
3561     my $perm_mode = shift || 'read';
3562
3563     my $li = $e->retrieve_acq_lineitem([
3564         $li_id,
3565         {   flesh => 1,
3566             flesh_fields => {jub => ['purchase_order', 'picklist']}
3567         }
3568     ]) or return (undef, $e->die_event);
3569
3570     my $org;
3571     if(my $po = $li->purchase_order) {
3572         $org = $po->ordering_agency;
3573         my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3574         return ($li, $e->die_event) unless $e->allowed($perms, $org);
3575
3576     } elsif(my $pl = $li->picklist) {
3577         $org = $pl->org_unit;
3578         my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3579         return ($li, $e->die_event) unless $e->allowed($perms, $org);
3580     }
3581
3582     return ($li, undef, $org);
3583 }
3584
3585
3586 __PACKAGE__->register_method(
3587     method => "clone_distrib_form",
3588     api_name => "open-ils.acq.distribution_formula.clone",
3589     stream => 1,
3590     signature => {
3591         desc => q/Clone a distribution formula/,
3592         params => [
3593             {desc => "Authentication token", type => "string"},
3594             {desc => "Original formula ID", type => 'integer'},
3595             {desc => "Name of new formula", type => 'string'},
3596         ],
3597         return => {desc => "ID of newly created formula"}
3598     }
3599 );
3600
3601 sub clone_distrib_form {
3602     my($self, $client, $auth, $form_id, $new_name) = @_;
3603
3604     my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3605     return $e->die_event unless $e->checkauth;
3606
3607     my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3608     return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3609
3610     my $new_form = Fieldmapper::acq::distribution_formula->new;
3611
3612     $new_form->owner($old_form->owner);
3613     $new_form->name($new_name);
3614     $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3615
3616     my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3617     for my $entry (@$entries) {
3618        my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3619        $new_entry->$_($entry->$_()) for $entry->real_fields;
3620        $new_entry->formula($new_form->id);
3621        $new_entry->clear_id;
3622        $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3623     }
3624
3625     $e->commit;
3626     return $new_form->id;
3627 }
3628
3629 __PACKAGE__->register_method(
3630     method => 'add_li_to_po',
3631     api_name    => 'open-ils.acq.purchase_order.add_lineitem',
3632     signature => {
3633         desc => q/Adds a lineitem to an existing purchase order/,
3634         params => [
3635             {desc => 'Authentication token', type => 'string'},
3636             {desc => 'The purchase order id', type => 'number'},
3637             {desc => 'The lineitem ID (or an array of them)', type => 'mixed'},
3638         ],
3639         return => {desc => 'Streams a total versus completed counts object, event on error'}
3640     }
3641 );
3642
3643 sub add_li_to_po {
3644     my($self, $conn, $auth, $po_id, $li_id) = @_;
3645
3646     my $e = new_editor(authtoken => $auth, xact => 1);
3647     return $e->die_event unless $e->checkauth;
3648
3649     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3650
3651     my $po = $e->retrieve_acq_purchase_order($po_id)
3652         or return $e->die_event;
3653
3654     return $e->die_event unless 
3655         $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3656
3657     unless ($po->state =~ /new|pending/) {
3658         $e->rollback;
3659         return {success => 0, po => $po, error => 'bad-po-state'};
3660     }
3661
3662     my $lis;
3663
3664     if (ref $li_id eq "ARRAY") {
3665         $li_id = [ map { int($_) } @$li_id ];
3666         return $e->die_event(new OpenILS::Event("BAD_PARAMS")) unless @$li_id;
3667
3668         $lis = $e->search_acq_lineitem({id => $li_id})
3669             or return $e->die_event;
3670     } else {
3671         my $li = $e->retrieve_acq_lineitem(int($li_id))
3672             or return $e->die_event;
3673         $lis = [$li];
3674     }
3675
3676     foreach my $li (@$lis) {
3677         if ($li->state !~ /new|order-ready|pending-order/ or
3678             $li->purchase_order) {
3679             $e->rollback;
3680             return {success => 0, li => $li, error => 'bad-li-state'};
3681         }
3682
3683         $li->provider($po->provider);
3684         $li->purchase_order($po_id);
3685         $li->state('pending-order');
3686         apply_default_copies($mgr, $po, $li->id) or return $e->die_event;
3687         update_lineitem($mgr, $li) or return $e->die_event;
3688     }
3689
3690     $e->commit;
3691     return {success => 1};
3692 }
3693
3694 __PACKAGE__->register_method(
3695     method => 'po_lineitems_no_copies',
3696     api_name => 'open-ils.acq.purchase_order.no_copy_lineitems.id_list',
3697     stream => 1,
3698     authoritative => 1, 
3699     signature => {
3700         desc => q/Returns the set of lineitem IDs for a given PO that have no copies attached/,
3701         params => [
3702             {desc => 'Authentication token', type => 'string'},
3703             {desc => 'The purchase order id', type => 'number'},
3704         ],
3705         return => {desc => 'Stream of lineitem IDs on success, event on error'}
3706     }
3707 );
3708
3709 sub po_lineitems_no_copies {
3710     my ($self, $conn, $auth, $po_id) = @_;
3711
3712     my $e = new_editor(authtoken => $auth);
3713     return $e->event unless $e->checkauth;
3714
3715     # first check the view perms for LI's attached to this PO
3716     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->event;
3717     return $e->event unless $e->allowed('VIEW_PURCHASE_ORDER', $po->ordering_agency);
3718
3719     my $ids = $e->json_query({
3720         select => {jub => ['id']},
3721         from => {jub => {acqlid => {type => 'left'}}},
3722         where => {
3723             '+jub' => {purchase_order => $po_id},
3724             '+acqlid' => {lineitem => undef}
3725         }
3726     });
3727
3728     $conn->respond($_->{id}) for @$ids;
3729     return undef;
3730 }
3731
3732 __PACKAGE__->register_method(
3733     method => 'set_li_order_ident',
3734     api_name => 'open-ils.acq.lineitem.order_identifier.set',
3735     signature => {
3736         desc => q/
3737             Given an existing lineitem_attr (typically a marc_attr), this will
3738             create a matching local_attr to store the name and value and mark
3739             the attr as the order_ident.  Any existing local_attr marked as
3740             order_ident is removed.
3741         /,
3742         params => [
3743             {desc => 'Authentication token', type => 'string'},
3744             {desc => q/Args object:
3745                 source_attr_id : ID of the existing lineitem_attr to use as
3746                     order ident.
3747                 lineitem_id : lineitem id
3748                 attr_name : name ('isbn', etc.) of a new marc_attr to add to 
3749                     the lineitem to use for the order ident
3750                 attr_value : value for the new marc_attr
3751                 no_apply_bre : if set, newly added attrs will not be applied 
3752                     to the lineitems' linked bib record/,
3753                 type => 'object'}
3754         ],
3755         return => {desc => q/Returns the attribute 
3756             responsible for tracking the order identifier/}
3757     }
3758 );
3759
3760 sub set_li_order_ident {
3761     my ($self, $conn, $auth, $args) = @_;
3762     $args ||= {};
3763
3764     my $source_attr;
3765     my $source_attr_id = $args->{source_attr_id};
3766
3767     my $e = new_editor(authtoken => $auth, xact => 1);
3768     return $e->die_event unless $e->checkauth;
3769
3770     # fetch attr, LI, and check update permissions
3771
3772     my $li_id = $args->{lineitem_id};
3773
3774     if ($source_attr_id) {
3775         $source_attr = $e->retrieve_acq_lineitem_attr($source_attr_id)
3776             or return $e->die_event;
3777         $li_id = $source_attr->lineitem;
3778     }
3779
3780     my ($li, $evt, $perm_org) = fetch_and_check_li($e, $li_id, 'write');
3781     return $evt if $evt;
3782
3783     return $e->die_event unless 
3784         $e->allowed('ACQ_SET_LINEITEM_IDENTIFIER', $perm_org);
3785
3786     # if needed, create a new marc attr for 
3787     # the lineitem to represent the ident value
3788
3789     ($source_attr, $evt) = apply_new_li_ident_attr(
3790         $e, $li, $perm_org, $args->{attr_name}, $args->{attr_value}) 
3791         unless $source_attr;
3792
3793     return $evt if $evt;
3794
3795     # remove the existing order_ident attribute if present
3796
3797     my $old_attr = $e->search_acq_lineitem_attr({
3798         attr_type => 'lineitem_local_attr_definition',
3799         lineitem => $li->id,
3800         order_ident => 't'
3801     })->[0];
3802
3803     if ($old_attr) {
3804
3805         # if we already have an order_ident that matches the 
3806         # source attr, there's nothing left to do.
3807
3808         if ($old_attr->attr_name eq $source_attr->attr_name and
3809             $old_attr->attr_value eq $source_attr->attr_value) {
3810
3811             $e->rollback;
3812             return $old_attr;
3813
3814         } else {
3815             # remove the old order_ident attribute
3816             $e->delete_acq_lineitem_attr($old_attr) or return $e->die_event;
3817         }
3818     }
3819
3820     # make sure we have a local_attr_def to match the source attr def
3821
3822     my $local_def = $e->search_acq_lineitem_local_attr_definition({
3823         code => $source_attr->attr_name
3824     })->[0];
3825
3826     if (!$local_def) {
3827         my $source_def = 
3828             $e->retrieve_acq_lineitem_attr_definition($source_attr->definition);
3829         $local_def = Fieldmapper::acq::lineitem_local_attr_definition->new;
3830         $local_def->code($source_def->code);
3831         $local_def->description($source_def->description);
3832         $local_def = $e->create_acq_lineitem_local_attr_definition($local_def)
3833             or return $e->die_event;
3834     }
3835
3836     # create the new order_ident local attr
3837
3838     my $new_attr = Fieldmapper::acq::lineitem_attr->new;
3839     $new_attr->definition($local_def->id);
3840     $new_attr->attr_type('lineitem_local_attr_definition');
3841     $new_attr->lineitem($li->id);
3842     $new_attr->attr_name($source_attr->attr_name);
3843     $new_attr->attr_value($source_attr->attr_value);
3844     $new_attr->order_ident('t');
3845
3846     $new_attr = $e->create_acq_lineitem_attr($new_attr) 
3847         or return $e->die_event;
3848     
3849     $e->commit;
3850     return $new_attr;
3851 }
3852
3853
3854 # Given an isbn, issn, or upc, add the value to the lineitem marc.
3855 # Upon update, the value will be auto-magically represented as
3856 # a lineitem marc attr.
3857 # If the li is linked to a bib record and the user has the correct
3858 # permissions, update the bib record to match.
3859 sub apply_new_li_ident_attr {
3860     my ($e, $li, $perm_org, $attr_name, $attr_value) = @_;
3861
3862     my %tags = (
3863         isbn => '020',
3864         issn => '022',
3865         upc  => '024'
3866     );
3867
3868     my $marc_field = MARC::Field->new(
3869         $tags{$attr_name}, '', '','a' => $attr_value);
3870
3871     my $li_rec = MARC::Record->new_from_xml($li->marc, 'UTF-8', 'USMARC');
3872     $li_rec->insert_fields_ordered($marc_field);
3873
3874     $li->marc(clean_marc($li_rec));
3875     $li->editor($e->requestor->id);
3876     $li->edit_time('now');
3877
3878     $e->update_acq_lineitem($li) or return (undef, $e->die_event);
3879
3880     my $source_attr = $e->search_acq_lineitem_attr({
3881         attr_name => $attr_name,
3882         attr_value => $attr_value,
3883         attr_type => 'lineitem_marc_attr_definition'
3884     })->[0];
3885
3886     if (!$source_attr) {
3887         $logger->error("ACQ lineitem update failed to produce a matching ".
3888             " marc attribute for $attr_name => $attr_value");
3889         return (undef, OpenILS::Event->new('INTERNAL_SERVER_ERROR'));
3890     }
3891
3892     return ($source_attr) unless 
3893         $li->eg_bib_id and
3894         $e->allowed('ACQ_ADD_LINEITEM_IDENTIFIER', $perm_org);
3895
3896     # li is linked to a bib record and user has the update perms
3897
3898     my $bre = $e->retrieve_biblio_record_entry($li->eg_bib_id);
3899     my $bre_marc = MARC::Record->new_from_xml($bre->marc, 'UTF-8', 'USMARC');
3900     $bre_marc->insert_fields_ordered($marc_field);
3901
3902     $bre->marc(clean_marc($bre_marc));
3903     $bre->editor($e->requestor->id);
3904     $bre->edit_date('now');
3905
3906     $e->update_biblio_record_entry($bre) or return (undef, $e->die_event);
3907
3908     return ($source_attr);
3909 }
3910
3911
3912 1;
3913