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