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