]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Acq/Order.pm
194fdb5fff275b8320d07c59039869c83043bdae
[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     $$options{dry_run} = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2603
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, $options);
2608     return $e->die_event if $die_event;
2609     $conn->respond_complete(1);
2610     $mgr->run_post_response_hooks unless $$options{dry_run};
2611     return undef;
2612 }
2613
2614 # xacts managed within
2615 sub activate_purchase_order_impl {
2616     my ($mgr, $po_id, $vandelay, $options) = @_;
2617     $options ||= {};
2618     my $dry_run = $$options{dry_run};
2619     my $no_assets = $$options{no_assets};
2620
2621     # read-only until lineitem asset creation
2622     my $e = $mgr->editor;
2623     $e->xact_begin;
2624
2625     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2626     return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2627
2628     return $e->die_event(OpenILS::Event->new('PO_ALREADY_ACTIVATED'))
2629         if $po->order_date; # PO cannot be re-activated
2630
2631     my $provider = $e->retrieve_acq_provider($po->provider);
2632
2633     # find lineitems and create assets for all
2634
2635     my $query = {   
2636         purchase_order => $po_id, 
2637         state => [qw/pending-order new order-ready/]
2638     };
2639
2640     my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2641
2642     my $vl_resp; # imported li's and the managing queue
2643     unless ($dry_run or $no_assets) {
2644         $e->rollback; # read-only thus far
2645
2646         # list_assets manages its own transactions
2647         $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2648             or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2649         $e->xact_begin;
2650     }
2651
2652     # create fund debits for lineitems 
2653
2654     for my $li_id (@$li_ids) {
2655         my $li = $e->retrieve_acq_lineitem($li_id);
2656         
2657         unless ($li->eg_bib_id or $dry_run or $no_assets) {
2658             # we encountered a lineitem that was not successfully imported.
2659             # we cannot continue.  rollback and report.
2660             $e->rollback;
2661             return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2662         }
2663
2664         $li->state('on-order');
2665         $li->claim_policy($provider->default_claim_policy)
2666             if $provider->default_claim_policy and !$li->claim_policy;
2667         create_lineitem_debits($mgr, $li, $dry_run) or return $e->die_event;
2668         update_lineitem($mgr, $li) or return $e->die_event;
2669         $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2670         $mgr->respond;
2671     }
2672
2673     # create po-item debits
2674
2675     for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2676
2677         my $debit = create_fund_debit(
2678             $mgr, 
2679             $dry_run, 
2680             debit_type => 'direct_charge', # to match invoicing
2681             origin_amount => $po_item->estimated_cost,
2682             origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2683             amount => $po_item->estimated_cost,
2684             fund => $po_item->fund
2685         ) or return $e->die_event;
2686         $po_item->fund_debit($debit->id);
2687         $e->update_acq_po_item($po_item) or return $e->die_event;
2688         $mgr->respond;
2689     }
2690
2691     # mark PO as ordered
2692
2693     $po->state('on-order');
2694     $po->order_date('now');
2695     update_purchase_order($mgr, $po) or return $e->die_event;
2696
2697     # clean up the xact
2698     $dry_run and $e->rollback or $e->commit;
2699
2700     # tell the world we activated a PO
2701     $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2702
2703     return undef;
2704 }
2705
2706
2707 __PACKAGE__->register_method(
2708     method    => 'split_purchase_order_by_lineitems',
2709     api_name  => 'open-ils.acq.purchase_order.split_by_lineitems',
2710     signature => {
2711         desc   => q/Splits a PO into many POs, 1 per lineitem.  Only works for / .
2712                   q/POs a) with more than one lineitems, and b) in the "pending" state./,
2713         params => [
2714             {desc => 'Authentication token', type => 'string'},
2715             {desc => 'Purchase order ID',    type => 'number'}
2716         ],
2717         return => {desc => 'list of new PO IDs on success, Event on error'}
2718     }
2719 );
2720
2721 sub split_purchase_order_by_lineitems {
2722     my ($self, $conn, $auth, $po_id) = @_;
2723
2724     my $e = new_editor("xact" => 1, "authtoken" => $auth);
2725     return $e->die_event unless $e->checkauth;
2726
2727     my $po = $e->retrieve_acq_purchase_order([
2728         $po_id, {
2729             "flesh" => 1,
2730             "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2731         }
2732     ]) or return $e->die_event;
2733
2734     return $e->die_event
2735         unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2736
2737     unless ($po->state eq "pending") {
2738         $e->rollback;
2739         return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2740     }
2741
2742     unless (@{$po->lineitems} > 1) {
2743         $e->rollback;
2744         return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2745     }
2746
2747     # To split an existing PO into many, it seems unwise to just delete the
2748     # original PO, so we'll instead detach all of the original POs' lineitems
2749     # but the first, then create new POs for each of the remaining LIs, and
2750     # then attach the LIs to their new POs.
2751
2752     my @po_ids = ($po->id);
2753     my @moving_li = @{$po->lineitems};
2754     shift @moving_li;    # discard first LI
2755
2756     foreach my $li (@moving_li) {
2757         my $new_po = $po->clone;
2758         $new_po->clear_id;
2759         $new_po->clear_name;
2760         $new_po->creator($e->requestor->id);
2761         $new_po->editor($e->requestor->id);
2762         $new_po->owner($e->requestor->id);
2763         $new_po->edit_time("now");
2764         $new_po->create_time("now");
2765
2766         $new_po = $e->create_acq_purchase_order($new_po);
2767
2768         # Clone any notes attached to the old PO and attach to the new one.
2769         foreach my $note (@{$po->notes}) {
2770             my $new_note = $note->clone;
2771             $new_note->clear_id;
2772             $new_note->edit_time("now");
2773             $new_note->purchase_order($new_po->id);
2774             $e->create_acq_po_note($new_note);
2775         }
2776
2777         $li->edit_time("now");
2778         $li->purchase_order($new_po->id);
2779         $e->update_acq_lineitem($li);
2780
2781         push @po_ids, $new_po->id;
2782     }
2783
2784     $po->edit_time("now");
2785     $e->update_acq_purchase_order($po);
2786
2787     return \@po_ids if $e->commit;
2788     return $e->die_event;
2789 }
2790
2791
2792 sub not_cancelable {
2793     my $o = shift;
2794     (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2795 }
2796
2797 __PACKAGE__->register_method(
2798     method => "cancel_purchase_order_api",
2799     api_name    => "open-ils.acq.purchase_order.cancel",
2800     signature => {
2801         desc => q/Cancels an on-order purchase order/,
2802         params => [
2803             {desc => "Authentication token", type => "string"},
2804             {desc => "PO ID to cancel", type => "number"},
2805             {desc => "Cancel reason ID", type => "number"}
2806         ],
2807         return => {desc => q/Object describing changed POs, LIs and LIDs
2808             on success; Event on error./}
2809     }
2810 );
2811
2812 sub cancel_purchase_order_api {
2813     my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2814
2815     my $e = new_editor("xact" => 1, "authtoken" => $auth);
2816     return $e->die_event unless $e->checkauth;
2817     my $mgr = new OpenILS::Application::Acq::BatchManager(
2818         "editor" => $e, "conn" => $conn
2819     );
2820
2821     $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2822         return new OpenILS::Event(
2823             "BAD_PARAMS", "note" => "Provide cancel reason ID"
2824         );
2825
2826     my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2827         return $e->die_event;
2828     if (not_cancelable($result)) { # event not from CStoreEditor
2829         $e->rollback;
2830         return $result;
2831     } elsif ($result == -1) {
2832         $e->rollback;
2833         return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2834     }
2835
2836     $e->commit or return $e->die_event;
2837
2838     # XXX create purchase order status events?
2839
2840     if ($mgr->{post_commit}) {
2841         foreach my $func (@{$mgr->{post_commit}}) {
2842             $func->();
2843         }
2844     }
2845
2846     return $result;
2847 }
2848
2849 sub cancel_purchase_order {
2850     my ($mgr, $po_id, $cancel_reason) = @_;
2851
2852     my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2853
2854     # XXX is "cancelled" a typo?  It's not correct US spelling, anyway.
2855     # Depending on context, this may not warrant an event.
2856     return -1 if $po->state eq "cancelled";
2857
2858     # But this always does.
2859     return new OpenILS::Event(
2860         "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2861     ) unless ($po->state eq "on-order" or $po->state eq "pending");
2862
2863     return 0 unless
2864         $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2865
2866     $po->state("cancelled");
2867     $po->cancel_reason($cancel_reason->id);
2868
2869     my $li_ids = $mgr->editor->search_acq_lineitem(
2870         {"purchase_order" => $po_id}, {"idlist" => 1}
2871     );
2872
2873     my $result = {"li" => {}, "lid" => {}};
2874     foreach my $li_id (@$li_ids) {
2875         my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2876             or return 0;
2877
2878         next if $li_result == -1; # already canceled:skip.
2879         return $li_result if not_cancelable($li_result); # not cancelable:stop.
2880
2881         # Merge in each LI result (there's only going to be
2882         # one per call to cancel_lineitem).
2883         my ($k, $v) = each %{$li_result->{"li"}};
2884         $result->{"li"}->{$k} = $v;
2885
2886         # Merge in each LID result (there may be many per call to
2887         # cancel_lineitem).
2888         while (($k, $v) = each %{$li_result->{"lid"}}) {
2889             $result->{"lid"}->{$k} = $v;
2890         }
2891     }
2892
2893     # TODO who/what/where/how do we indicate this change for electronic orders?
2894     # TODO return changes to encumbered/spent
2895     # TODO maybe cascade up from smaller object to container object if last
2896     # smaller object in the container has been canceled?
2897
2898     update_purchase_order($mgr, $po) or return 0;
2899     $result->{"po"} = {
2900         $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2901     };
2902     return $result;
2903 }
2904
2905
2906 __PACKAGE__->register_method(
2907     method => "cancel_lineitem_api",
2908     api_name    => "open-ils.acq.lineitem.cancel",
2909     signature => {
2910         desc => q/Cancels an on-order lineitem/,
2911         params => [
2912             {desc => "Authentication token", type => "string"},
2913             {desc => "Lineitem ID to cancel", type => "number"},
2914             {desc => "Cancel reason ID", type => "number"}
2915         ],
2916         return => {desc => q/Object describing changed LIs and LIDs on success;
2917             Event on error./}
2918     }
2919 );
2920
2921 __PACKAGE__->register_method(
2922     method => "cancel_lineitem_api",
2923     api_name    => "open-ils.acq.lineitem.cancel.batch",
2924     signature => {
2925         desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2926         return => {desc => q/Object describing changed LIs and LIDs on success;
2927             Event on error./}
2928     }
2929 );
2930
2931 sub cancel_lineitem_api {
2932     my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2933
2934     my $batched = $self->api_name =~ /\.batch/;
2935
2936     my $e = new_editor("xact" => 1, "authtoken" => $auth);
2937     return $e->die_event unless $e->checkauth;
2938     my $mgr = new OpenILS::Application::Acq::BatchManager(
2939         "editor" => $e, "conn" => $conn
2940     );
2941
2942     $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2943         return new OpenILS::Event(
2944             "BAD_PARAMS", "note" => "Provide cancel reason ID"
2945         );
2946
2947     my ($result, $maybe_event);
2948
2949     if ($batched) {
2950         $result = {"li" => {}, "lid" => {}};
2951         foreach my $one_li_id (@$li_id) {
2952             my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2953                 return $e->die_event;
2954             if (not_cancelable($one)) {
2955                 $maybe_event = $one;
2956             } elsif ($result == -1) {
2957                 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2958             } else {
2959                 my ($k, $v);
2960                 if ($one->{"li"}) {
2961                     while (($k, $v) = each %{$one->{"li"}}) {
2962                         $result->{"li"}->{$k} = $v;
2963                     }
2964                 }
2965                 if ($one->{"lid"}) {
2966                     while (($k, $v) = each %{$one->{"lid"}}) {
2967                         $result->{"lid"}->{$k} = $v;
2968                     }
2969                 }
2970             }
2971         }
2972     } else {
2973         $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2974             return $e->die_event;
2975
2976         if (not_cancelable($result)) {
2977             $e->rollback;
2978             return $result;
2979         } elsif ($result == -1) {
2980             $e->rollback;
2981             return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2982         }
2983     }
2984
2985     if ($batched and not scalar keys %{$result->{"li"}}) {
2986         $e->rollback;
2987         return $maybe_event;
2988     } else {
2989         $e->commit or return $e->die_event;
2990         # create_lineitem_status_events should handle array li_id ok
2991         create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2992
2993         if ($mgr->{post_commit}) {
2994             foreach my $func (@{$mgr->{post_commit}}) {
2995                 $func->();
2996             }
2997         }
2998
2999         return $result;
3000     }
3001 }
3002
3003 sub cancel_lineitem {
3004     my ($mgr, $li_id, $cancel_reason) = @_;
3005     my $li = $mgr->editor->retrieve_acq_lineitem([
3006         $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
3007     ]) or return 0;
3008
3009     return 0 unless $mgr->editor->allowed(
3010         "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
3011     );
3012
3013     # Depending on context, this may not warrant an event.
3014     return -1 if $li->state eq "cancelled";
3015
3016     # But this always does.  Note that this used to be looser, but you can
3017     # no longer cancel lineitems that lack a PO or that are in "pending-order"
3018     # state (you could in the past).
3019     return new OpenILS::Event(
3020         "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
3021     ) unless $li->purchase_order and $li->state eq "on-order";
3022
3023     $li->state("cancelled");
3024     $li->cancel_reason($cancel_reason->id);
3025
3026     my $lids = $mgr->editor->search_acq_lineitem_detail([{
3027         "lineitem" => $li_id
3028     }, {
3029         flesh => 1,
3030         flesh_fields => { acqlid => ['eg_copy_id'] }
3031     }]);
3032
3033     my $result = {"lid" => {}};
3034     my $copies = [];
3035     foreach my $lid (@$lids) {
3036         my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
3037             or return 0;
3038
3039         # gathering any real copies for deletion
3040         if ($lid->eg_copy_id) {
3041             $lid->eg_copy_id->isdeleted('t');
3042             push @$copies, $lid->eg_copy_id;
3043         }
3044
3045         next if $lid_result == -1; # already canceled: just skip it.
3046         return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
3047
3048         # Merge in each LID result (there's only going to be one per call to
3049         # cancel_lineitem_detail).
3050         my ($k, $v) = each %{$lid_result->{"lid"}};
3051         $result->{"lid"}->{$k} = $v;
3052     }
3053
3054     # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
3055     # Delete empty bibs according org unit setting
3056     my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
3057         $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
3058     if (scalar(@$copies)>0) {
3059         my $override = 1;
3060         my $delete_stats = undef;
3061         my $retarget_holds = [];
3062         my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
3063             $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
3064
3065         if( $cat_evt ) {
3066             $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
3067             return new OpenILS::Event(
3068                 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
3069             );
3070         }
3071
3072         # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
3073         #my $ses = OpenSRF::AppSession->create('open-ils.circ');
3074         #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
3075     }
3076
3077     # if we have a bib, check to see whether it has been deleted.  if so, cancel any active holds targeting that bib
3078     if ($li->eg_bib_id) {
3079         my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
3080             "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
3081         );
3082         if ($U->is_true($bib->deleted)) {
3083             my $holds = $mgr->editor->search_action_hold_request(
3084                 {   cancel_time => undef,
3085                     fulfillment_time => undef,
3086                     target => $li->eg_bib_id
3087                 }
3088             );
3089
3090             my %cached_usr_home_ou = ();
3091
3092             for my $hold (@$holds) {
3093
3094                 $logger->info("Cancelling hold ".$hold->id.
3095                     " due to acq lineitem cancellation.");
3096
3097                 $hold->cancel_time('now');
3098                 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
3099                 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
3100                 unless($mgr->editor->update_action_hold_request($hold)) {
3101                     my $evt = $mgr->editor->event;
3102                     $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
3103                     return new OpenILS::Event(
3104                         "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
3105                     );
3106                 }
3107                 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
3108                     $mgr->{post_commit} = [];
3109                 }
3110                 push @{ $mgr->{post_commit} }, sub {
3111                     my $home_ou = $cached_usr_home_ou{$hold->usr};
3112                     if (! $home_ou) {
3113                         my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
3114                         $home_ou = $user->home_ou;
3115                         $cached_usr_home_ou{$hold->usr} = $home_ou;
3116                     }
3117                     $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
3118                 };
3119             }
3120         }
3121     }
3122
3123     update_lineitem($mgr, $li) or return 0;
3124     $result->{"li"} = {
3125         $li_id => {
3126             "state" => $li->state,
3127             "cancel_reason" => $cancel_reason
3128         }
3129     };
3130     return $result;
3131 }
3132
3133
3134 __PACKAGE__->register_method(
3135     method => "cancel_lineitem_detail_api",
3136     api_name    => "open-ils.acq.lineitem_detail.cancel",
3137     signature => {
3138         desc => q/Cancels an on-order lineitem detail/,
3139         params => [
3140             {desc => "Authentication token", type => "string"},
3141             {desc => "Lineitem detail ID to cancel", type => "number"},
3142             {desc => "Cancel reason ID", type => "number"}
3143         ],
3144         return => {desc => q/Object describing changed LIDs on success;
3145             Event on error./}
3146     }
3147 );
3148
3149 sub cancel_lineitem_detail_api {
3150     my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
3151
3152     my $e = new_editor("xact" => 1, "authtoken" => $auth);
3153     return $e->die_event unless $e->checkauth;
3154     my $mgr = new OpenILS::Application::Acq::BatchManager(
3155         "editor" => $e, "conn" => $conn
3156     );
3157
3158     $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
3159         return new OpenILS::Event(
3160             "BAD_PARAMS", "note" => "Provide cancel reason ID"
3161         );
3162
3163     my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
3164         return $e->die_event;
3165
3166     if (not_cancelable($result)) {
3167         $e->rollback;
3168         return $result;
3169     } elsif ($result == -1) {
3170         $e->rollback;
3171         return new OpenILS::Event("ACQ_ALREADY_CANCELED");
3172     }
3173
3174     $e->commit or return $e->die_event;
3175
3176     # XXX create lineitem detail status events?
3177     return $result;
3178 }
3179
3180 sub cancel_lineitem_detail {
3181     my ($mgr, $lid_id, $cancel_reason) = @_;
3182     my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
3183         $lid_id, {
3184             "flesh" => 2,
3185             "flesh_fields" => {
3186                 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
3187             }
3188         }
3189     ]) or return 0;
3190
3191     # Depending on context, this may not warrant an event.
3192     return -1 if $lid->cancel_reason;
3193
3194     # But this always does.
3195     return new OpenILS::Event(
3196         "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
3197     ) unless (
3198         (! $lid->lineitem->purchase_order) or
3199         (
3200             (not $lid->recv_time) and
3201             $lid->lineitem and
3202             $lid->lineitem->purchase_order and (
3203                 $lid->lineitem->state eq "on-order" or
3204                 $lid->lineitem->state eq "pending-order"
3205             )
3206         )
3207     );
3208
3209     return 0 unless $mgr->editor->allowed(
3210         "CREATE_PURCHASE_ORDER",
3211         $lid->lineitem->purchase_order->ordering_agency
3212     ) or (! $lid->lineitem->purchase_order);
3213
3214     $lid->cancel_reason($cancel_reason->id);
3215
3216     unless($U->is_true($cancel_reason->keep_debits)) {
3217         my $debit_id = $lid->fund_debit;
3218         $lid->clear_fund_debit;
3219
3220         if($debit_id) {
3221             # item is cancelled.  Remove the fund debit.
3222             my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
3223             if (!$U->is_true($debit->encumbrance)) {
3224                 $mgr->editor->rollback;
3225                 return OpenILS::Event->new('ACQ_NOT_CANCELABLE', 
3226                     note => "Debit is marked as paid: $debit_id");
3227             }
3228             $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
3229         }
3230     }
3231
3232     # XXX LIDs don't have either an editor or a edit_time field. Should we
3233     # update these on the LI when we alter an LID?
3234     $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
3235
3236     return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
3237 }
3238
3239
3240 __PACKAGE__->register_method(
3241     method    => 'user_requests',
3242     api_name  => 'open-ils.acq.user_request.retrieve.by_user_id',
3243     stream    => 1,
3244     signature => {
3245         desc   => 'Retrieve fleshed user requests and related data for a given user.',
3246         params => [
3247             { desc => 'Authentication token',      type => 'string' },
3248             { desc => 'User ID of the owner, or array of IDs',      },
3249             { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3250               type => 'object'
3251             }
3252         ],
3253         return => {
3254             desc => 'Fleshed user requests and related data',
3255             type => 'object'
3256         }
3257     }
3258 );
3259
3260 __PACKAGE__->register_method(
3261     method    => 'user_requests',
3262     api_name  => 'open-ils.acq.user_request.retrieve.by_home_ou',
3263     stream    => 1,
3264     signature => {
3265         desc   => 'Retrieve fleshed user requests and related data for a given org unit or units.',
3266         params => [
3267             { desc => 'Authentication token',      type => 'string' },
3268             { desc => 'Org unit ID, or array of IDs',               },
3269             { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3270               type => 'object'
3271             }
3272         ],
3273         return => {
3274             desc => 'Fleshed user requests and related data',
3275             type => 'object'
3276         }
3277     }
3278 );
3279
3280 sub user_requests {
3281     my($self, $conn, $auth, $search_value, $options) = @_;
3282     my $e = new_editor(authtoken => $auth);
3283     return $e->event unless $e->checkauth;
3284     my $rid = $e->requestor->id;
3285     $options ||= {};
3286
3287     my $query = {
3288         "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
3289         "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
3290         "where"=>{
3291             "+jub"=> {
3292                 "-or" => [
3293                     {"id"=>undef}, # this with the left-join pulls in requests without lineitems
3294                     {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
3295                 ]
3296             }
3297         },
3298         "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
3299     };
3300
3301     foreach (qw/ order_by limit offset /) {
3302         $query->{$_} = $options->{$_} if defined $options->{$_};
3303     }
3304     if (defined $options->{'state'}) {
3305         $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};        
3306     }
3307
3308     if ($self->api_name =~ /by_user_id/) {
3309         $query->{'where'}->{'usr'} = $search_value;
3310     } else {
3311         $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3312     }
3313
3314     my $pertinent_ids = $e->json_query($query);
3315
3316     my %perm_test = ();
3317     for my $id_blob (@$pertinent_ids) {
3318         if ($rid != $id_blob->{usr_id}) {
3319             if (!defined $perm_test{ $id_blob->{home_ou} }) {
3320                 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3321             }
3322             if (!$perm_test{ $id_blob->{home_ou} }) {
3323                 next; # failed test
3324             }
3325         }
3326         my $aur_obj = $e->retrieve_acq_user_request([
3327             $id_blob->{id},
3328             {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3329         ]);
3330         if (! $aur_obj) { next; }
3331
3332         if ($aur_obj->lineitem()) {
3333             $aur_obj->lineitem()->clear_marc();
3334         }
3335         $conn->respond($aur_obj);
3336     }
3337
3338     return undef;
3339 }
3340
3341 __PACKAGE__->register_method (
3342     method    => 'update_user_request',
3343     api_name  => 'open-ils.acq.user_request.cancel.batch',
3344     stream    => 1,
3345     signature => {
3346         desc   => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether.  The '    .
3347                   'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3348         params => [
3349             { desc => 'Authentication token',              type => 'string' },
3350             { desc => 'ID or array of IDs for the user requests to cancel'  },
3351             { desc => 'Cancel Reason ID (optional)',       type => 'string' }
3352         ],
3353         return => {
3354             desc => 'progress object, event on error',
3355         }
3356     }
3357 );
3358 __PACKAGE__->register_method (
3359     method    => 'update_user_request',
3360     api_name  => 'open-ils.acq.user_request.set_no_hold.batch',
3361     stream    => 1,
3362     signature => {
3363         desc   => 'Remove the hold from a user request or set of requests',
3364         params => [
3365             { desc => 'Authentication token',              type => 'string' },
3366             { desc => 'ID or array of IDs for the user requests to modify'  }
3367         ],
3368         return => {
3369             desc => 'progress object, event on error',
3370         }
3371     }
3372 );
3373
3374 sub update_user_request {
3375     my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3376     my $e = new_editor(xact => 1, authtoken => $auth);
3377     return $e->die_event unless $e->checkauth;
3378     my $rid = $e->requestor->id;
3379
3380     my $x = 1;
3381     my %perm_test = ();
3382     for my $id (@$aur_ids) {
3383
3384         my $aur_obj = $e->retrieve_acq_user_request([
3385             $id,
3386             {   flesh => 1,
3387                 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3388             }
3389         ]) or return $e->die_event;
3390
3391         my $context_org = $aur_obj->usr()->home_ou();
3392         $aur_obj->usr( $aur_obj->usr()->id() );
3393
3394         if ($rid != $aur_obj->usr) {
3395             if (!defined $perm_test{ $context_org }) {
3396                 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3397             }
3398             if (!$perm_test{ $context_org }) {
3399                 next; # failed test
3400             }
3401         }
3402
3403         if($self->api_name =~ /set_no_hold/) {
3404             if ($U->is_true($aur_obj->hold)) { 
3405                 $aur_obj->hold(0); 
3406                 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3407             }
3408         }
3409
3410         if($self->api_name =~ /cancel/) {
3411             if ( $cancel_reason ) {
3412                 $aur_obj->cancel_reason( $cancel_reason );
3413                 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3414                 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3415             } else {
3416                 $e->delete_acq_user_request($aur_obj);
3417             }
3418         }
3419
3420         $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3421     }
3422
3423     $e->commit;
3424     return {complete => 1};
3425 }
3426
3427 __PACKAGE__->register_method (
3428     method    => 'new_user_request',
3429     api_name  => 'open-ils.acq.user_request.create',
3430     signature => {
3431         desc   => 'Create a new user request object in the DB',
3432         param  => [
3433             { desc => 'Authentication token',   type => 'string' },
3434             { desc => 'User request data hash.  Hash keys match the fields for the "aur" object', type => 'object' }
3435         ],
3436         return => {
3437             desc => 'The created user request object, or event on error'
3438         }
3439     }
3440 );
3441
3442 sub new_user_request {
3443     my($self, $conn, $auth, $form_data) = @_;
3444     my $e = new_editor(xact => 1, authtoken => $auth);
3445     return $e->die_event unless $e->checkauth;
3446     my $rid = $e->requestor->id;
3447     my $target_user_fleshed;
3448     if (! defined $$form_data{'usr'}) {
3449         $$form_data{'usr'} = $rid;
3450     }
3451     if ($$form_data{'usr'} != $rid) {
3452         # See if the requestor can place the request on behalf of a different user.
3453         $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3454         $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3455     } else {
3456         $target_user_fleshed = $e->requestor;
3457         $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3458     }
3459     if (! defined $$form_data{'pickup_lib'}) {
3460         if ($target_user_fleshed->ws_ou) {
3461             $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3462         } else {
3463             $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3464         }
3465     }
3466     if (! defined $$form_data{'request_type'}) {
3467         $$form_data{'request_type'} = 1; # Books
3468     }
3469     my $aur_obj = new Fieldmapper::acq::user_request; 
3470     $aur_obj->isnew(1);
3471     $aur_obj->usr( $$form_data{'usr'} );
3472     $aur_obj->request_date( 'now' );
3473     for my $field ( keys %$form_data ) {
3474         if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3475             $aur_obj->$field( $$form_data{$field} );
3476         }
3477     }
3478
3479     $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3480
3481     $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3482
3483     return $aur_obj;
3484 }
3485
3486 sub create_user_request_events {
3487     my($e, $user_reqs, $hook) = @_;
3488
3489     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3490     $ses->connect;
3491
3492     my %cached_usr_home_ou = ();
3493     for my $user_req (@$user_reqs) {
3494         my $home_ou = $cached_usr_home_ou{$user_req->usr};
3495         if (! $home_ou) {
3496             my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3497             $home_ou = $user->home_ou;
3498             $cached_usr_home_ou{$user_req->usr} = $home_ou;
3499         }
3500         my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3501         $req->recv;
3502     }
3503
3504     $ses->disconnect;
3505     return undef;
3506 }
3507
3508
3509 __PACKAGE__->register_method(
3510     method => "po_note_CUD_batch",
3511     api_name => "open-ils.acq.po_note.cud.batch",
3512     stream => 1,
3513     signature => {
3514         desc => q/Manage purchase order notes/,
3515         params => [
3516             {desc => "Authentication token", type => "string"},
3517             {desc => "List of po_notes to manage", type => "array"},
3518         ],
3519         return => {desc => "Stream of successfully managed objects"}
3520     }
3521 );
3522
3523 sub po_note_CUD_batch {
3524     my ($self, $conn, $auth, $notes) = @_;
3525
3526     my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3527     return $e->die_event unless $e->checkauth;
3528     # XXX perms
3529
3530     my $total = @$notes;
3531     my $count = 0;
3532
3533     foreach my $note (@$notes) {
3534
3535         $note->editor($e->requestor->id);
3536         $note->edit_time("now");
3537
3538         if ($note->isnew) {
3539             $note->creator($e->requestor->id);
3540             $note = $e->create_acq_po_note($note) or return $e->die_event;
3541         } elsif ($note->isdeleted) {
3542             $e->delete_acq_po_note($note) or return $e->die_event;
3543         } elsif ($note->ischanged) {
3544             $e->update_acq_po_note($note) or return $e->die_event;
3545         }
3546
3547         unless ($note->isdeleted) {
3548             $note = $e->retrieve_acq_po_note($note->id) or
3549                 return $e->die_event;
3550         }
3551
3552         $conn->respond(
3553             {"maximum" => $total, "progress" => ++$count, "note" => $note}
3554         );
3555     }
3556
3557     $e->commit and $conn->respond_complete or return $e->die_event;
3558 }
3559
3560
3561 # retrieves a lineitem, fleshes its PO and PL, checks perms
3562 # returns ($li, $evt, $org)
3563 sub fetch_and_check_li {
3564     my $e = shift;
3565     my $li_id = shift;
3566     my $perm_mode = shift || 'read';
3567
3568     my $li = $e->retrieve_acq_lineitem([
3569         $li_id,
3570         {   flesh => 1,
3571             flesh_fields => {jub => ['purchase_order', 'picklist']}
3572         }
3573     ]) or return (undef, $e->die_event);
3574
3575     my $org;
3576     if(my $po = $li->purchase_order) {
3577         $org = $po->ordering_agency;
3578         my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3579         return ($li, $e->die_event) unless $e->allowed($perms, $org);
3580
3581     } elsif(my $pl = $li->picklist) {
3582         $org = $pl->org_unit;
3583         my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3584         return ($li, $e->die_event) unless $e->allowed($perms, $org);
3585     }
3586
3587     return ($li, undef, $org);
3588 }
3589
3590
3591 __PACKAGE__->register_method(
3592     method => "clone_distrib_form",
3593     api_name => "open-ils.acq.distribution_formula.clone",
3594     stream => 1,
3595     signature => {
3596         desc => q/Clone a distribution formula/,
3597         params => [
3598             {desc => "Authentication token", type => "string"},
3599             {desc => "Original formula ID", type => 'integer'},
3600             {desc => "Name of new formula", type => 'string'},
3601         ],
3602         return => {desc => "ID of newly created formula"}
3603     }
3604 );
3605
3606 sub clone_distrib_form {
3607     my($self, $client, $auth, $form_id, $new_name) = @_;
3608
3609     my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3610     return $e->die_event unless $e->checkauth;
3611
3612     my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3613     return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3614
3615     my $new_form = Fieldmapper::acq::distribution_formula->new;
3616
3617     $new_form->owner($old_form->owner);
3618     $new_form->name($new_name);
3619     $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3620
3621     my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3622     for my $entry (@$entries) {
3623        my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3624        $new_entry->$_($entry->$_()) for $entry->real_fields;
3625        $new_entry->formula($new_form->id);
3626        $new_entry->clear_id;
3627        $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3628     }
3629
3630     $e->commit;
3631     return $new_form->id;
3632 }
3633
3634 __PACKAGE__->register_method(
3635     method => 'add_li_to_po',
3636     api_name    => 'open-ils.acq.purchase_order.add_lineitem',
3637     signature => {
3638         desc => q/Adds a lineitem to an existing purchase order/,
3639         params => [
3640             {desc => 'Authentication token', type => 'string'},
3641             {desc => 'The purchase order id', type => 'number'},
3642             {desc => 'The lineitem ID (or an array of them)', type => 'mixed'},
3643         ],
3644         return => {desc => 'Streams a total versus completed counts object, event on error'}
3645     }
3646 );
3647
3648 sub add_li_to_po {
3649     my($self, $conn, $auth, $po_id, $li_id) = @_;
3650
3651     my $e = new_editor(authtoken => $auth, xact => 1);
3652     return $e->die_event unless $e->checkauth;
3653
3654     my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3655
3656     my $po = $e->retrieve_acq_purchase_order($po_id)
3657         or return $e->die_event;
3658
3659     return $e->die_event unless 
3660         $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3661
3662     unless ($po->state =~ /new|pending/) {
3663         $e->rollback;
3664         return {success => 0, po => $po, error => 'bad-po-state'};
3665     }
3666
3667     my $lis;
3668
3669     if (ref $li_id eq "ARRAY") {
3670         $li_id = [ map { int($_) } @$li_id ];
3671         return $e->die_event(new OpenILS::Event("BAD_PARAMS")) unless @$li_id;
3672
3673         $lis = $e->search_acq_lineitem({id => $li_id})
3674             or return $e->die_event;
3675     } else {
3676         my $li = $e->retrieve_acq_lineitem(int($li_id))
3677             or return $e->die_event;
3678         $lis = [$li];
3679     }
3680
3681     foreach my $li (@$lis) {
3682         if ($li->state !~ /new|order-ready|pending-order/ or
3683             $li->purchase_order) {
3684             $e->rollback;
3685             return {success => 0, li => $li, error => 'bad-li-state'};
3686         }
3687
3688         $li->provider($po->provider);
3689         $li->purchase_order($po_id);
3690         $li->state('pending-order');
3691         apply_default_copies($mgr, $po, $li->id) or return $e->die_event;
3692         update_lineitem($mgr, $li) or return $e->die_event;
3693     }
3694
3695     $e->commit;
3696     return {success => 1};
3697 }
3698
3699 __PACKAGE__->register_method(
3700     method => 'po_lineitems_no_copies',
3701     api_name => 'open-ils.acq.purchase_order.no_copy_lineitems.id_list',
3702     stream => 1,
3703     authoritative => 1, 
3704     signature => {
3705         desc => q/Returns the set of lineitem IDs for a given PO that have no copies attached/,
3706         params => [
3707             {desc => 'Authentication token', type => 'string'},
3708             {desc => 'The purchase order id', type => 'number'},
3709         ],
3710         return => {desc => 'Stream of lineitem IDs on success, event on error'}
3711     }
3712 );
3713
3714 sub po_lineitems_no_copies {
3715     my ($self, $conn, $auth, $po_id) = @_;
3716
3717     my $e = new_editor(authtoken => $auth);
3718     return $e->event unless $e->checkauth;
3719
3720     # first check the view perms for LI's attached to this PO
3721     my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->event;
3722     return $e->event unless $e->allowed('VIEW_PURCHASE_ORDER', $po->ordering_agency);
3723
3724     my $ids = $e->json_query({
3725         select => {jub => ['id']},
3726         from => {jub => {acqlid => {type => 'left'}}},
3727         where => {
3728             '+jub' => {purchase_order => $po_id},
3729             '+acqlid' => {lineitem => undef}
3730         }
3731     });
3732
3733     $conn->respond($_->{id}) for @$ids;
3734     return undef;
3735 }
3736
3737 __PACKAGE__->register_method(
3738     method => 'set_li_order_ident',
3739     api_name => 'open-ils.acq.lineitem.order_identifier.set',
3740     signature => {
3741         desc => q/
3742             Given an existing lineitem_attr (typically a marc_attr), this will
3743             create a matching local_attr to store the name and value and mark
3744             the attr as the order_ident.  Any existing local_attr marked as
3745             order_ident is removed.
3746         /,
3747         params => [
3748             {desc => 'Authentication token', type => 'string'},
3749             {desc => q/Args object:
3750                 source_attr_id : ID of the existing lineitem_attr to use as
3751                     order ident.
3752                 lineitem_id : lineitem id
3753                 attr_name : name ('isbn', etc.) of a new marc_attr to add to 
3754                     the lineitem to use for the order ident
3755                 attr_value : value for the new marc_attr
3756                 no_apply_bre : if set, newly added attrs will not be applied 
3757                     to the lineitems' linked bib record/,
3758                 type => 'object'}
3759         ],
3760         return => {desc => q/Returns the attribute 
3761             responsible for tracking the order identifier/}
3762     }
3763 );
3764
3765 sub set_li_order_ident {
3766     my ($self, $conn, $auth, $args) = @_;
3767     $args ||= {};
3768
3769     my $source_attr;
3770     my $source_attr_id = $args->{source_attr_id};
3771
3772     my $e = new_editor(authtoken => $auth, xact => 1);
3773     return $e->die_event unless $e->checkauth;
3774
3775     # fetch attr, LI, and check update permissions
3776
3777     my $li_id = $args->{lineitem_id};
3778
3779     if ($source_attr_id) {
3780         $source_attr = $e->retrieve_acq_lineitem_attr($source_attr_id)
3781             or return $e->die_event;
3782         $li_id = $source_attr->lineitem;
3783     }
3784
3785     my ($li, $evt, $perm_org) = fetch_and_check_li($e, $li_id, 'write');
3786     return $evt if $evt;
3787
3788     return $e->die_event unless 
3789         $e->allowed('ACQ_SET_LINEITEM_IDENTIFIER', $perm_org);
3790
3791     # if needed, create a new marc attr for 
3792     # the lineitem to represent the ident value
3793
3794     ($source_attr, $evt) = apply_new_li_ident_attr(
3795         $e, $li, $perm_org, $args->{attr_name}, $args->{attr_value}) 
3796         unless $source_attr;
3797
3798     return $evt if $evt;
3799
3800     # remove the existing order_ident attribute if present
3801
3802     my $old_attr = $e->search_acq_lineitem_attr({
3803         attr_type => 'lineitem_local_attr_definition',
3804         lineitem => $li->id,
3805         order_ident => 't'
3806     })->[0];
3807
3808     if ($old_attr) {
3809
3810         # if we already have an order_ident that matches the 
3811         # source attr, there's nothing left to do.
3812
3813         if ($old_attr->attr_name eq $source_attr->attr_name and
3814             $old_attr->attr_value eq $source_attr->attr_value) {
3815
3816             $e->rollback;
3817             return $old_attr;
3818
3819         } else {
3820             # remove the old order_ident attribute
3821             $e->delete_acq_lineitem_attr($old_attr) or return $e->die_event;
3822         }
3823     }
3824
3825     # make sure we have a local_attr_def to match the source attr def
3826
3827     my $local_def = $e->search_acq_lineitem_local_attr_definition({
3828         code => $source_attr->attr_name
3829     })->[0];
3830
3831     if (!$local_def) {
3832         my $source_def = 
3833             $e->retrieve_acq_lineitem_attr_definition($source_attr->definition);
3834         $local_def = Fieldmapper::acq::lineitem_local_attr_definition->new;
3835         $local_def->code($source_def->code);
3836         $local_def->description($source_def->description);
3837         $local_def = $e->create_acq_lineitem_local_attr_definition($local_def)
3838             or return $e->die_event;
3839     }
3840
3841     # create the new order_ident local attr
3842
3843     my $new_attr = Fieldmapper::acq::lineitem_attr->new;
3844     $new_attr->definition($local_def->id);
3845     $new_attr->attr_type('lineitem_local_attr_definition');
3846     $new_attr->lineitem($li->id);
3847     $new_attr->attr_name($source_attr->attr_name);
3848     $new_attr->attr_value($source_attr->attr_value);
3849     $new_attr->order_ident('t');
3850
3851     $new_attr = $e->create_acq_lineitem_attr($new_attr) 
3852         or return $e->die_event;
3853     
3854     $e->commit;
3855     return $new_attr;
3856 }
3857
3858
3859 # Given an isbn, issn, or upc, add the value to the lineitem marc.
3860 # Upon update, the value will be auto-magically represented as
3861 # a lineitem marc attr.
3862 # If the li is linked to a bib record and the user has the correct
3863 # permissions, update the bib record to match.
3864 sub apply_new_li_ident_attr {
3865     my ($e, $li, $perm_org, $attr_name, $attr_value) = @_;
3866
3867     my %tags = (
3868         isbn => '020',
3869         issn => '022',
3870         upc  => '024'
3871     );
3872
3873     my $marc_field = MARC::Field->new(
3874         $tags{$attr_name}, '', '','a' => $attr_value);
3875
3876     my $li_rec = MARC::Record->new_from_xml($li->marc, 'UTF-8', 'USMARC');
3877     $li_rec->insert_fields_ordered($marc_field);
3878
3879     $li->marc(clean_marc($li_rec));
3880     $li->editor($e->requestor->id);
3881     $li->edit_time('now');
3882
3883     $e->update_acq_lineitem($li) or return (undef, $e->die_event);
3884
3885     my $source_attr = $e->search_acq_lineitem_attr({
3886         attr_name => $attr_name,
3887         attr_value => $attr_value,
3888         attr_type => 'lineitem_marc_attr_definition'
3889     })->[0];
3890
3891     if (!$source_attr) {
3892         $logger->error("ACQ lineitem update failed to produce a matching ".
3893             " marc attribute for $attr_name => $attr_value");
3894         return (undef, OpenILS::Event->new('INTERNAL_SERVER_ERROR'));
3895     }
3896
3897     return ($source_attr) unless 
3898         $li->eg_bib_id and
3899         $e->allowed('ACQ_ADD_LINEITEM_IDENTIFIER', $perm_org);
3900
3901     # li is linked to a bib record and user has the update perms
3902
3903     my $bre = $e->retrieve_biblio_record_entry($li->eg_bib_id);
3904     my $bre_marc = MARC::Record->new_from_xml($bre->marc, 'UTF-8', 'USMARC');
3905     $bre_marc->insert_fields_ordered($marc_field);
3906
3907     $bre->marc(clean_marc($bre_marc));
3908     $bre->editor($e->requestor->id);
3909     $bre->edit_date('now');
3910
3911     $e->update_biblio_record_entry($bre) or return (undef, $e->die_event);
3912
3913     return ($source_attr);
3914 }
3915
3916
3917 1;
3918