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