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