]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Acq/Search.pm
Merge branch 'master' of git://git.evergreen-ils.org/Evergreen
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Acq / Search.pm
1 package OpenILS::Application::Acq::Search;
2 use base "OpenILS::Application";
3
4 use strict;
5 use warnings;
6
7 use OpenSRF::AppSession;
8 use OpenSRF::Utils::Logger qw/:logger/;
9 use OpenILS::Event;
10 use OpenILS::Utils::CStoreEditor q/:funcs/;
11 use OpenILS::Utils::Fieldmapper;
12 use OpenILS::Application::Acq::Lineitem;
13 use OpenILS::Application::Acq::Financials;
14 use OpenILS::Application::Acq::Picklist;
15 use OpenILS::Application::Acq::Invoice;
16 use OpenILS::Application::Acq::Order;
17
18 my %RETRIEVERS = (
19     "lineitem" =>
20         \&{"OpenILS::Application::Acq::Lineitem::retrieve_lineitem_impl"},
21     "picklist" =>
22         \&{"OpenILS::Application::Acq::Picklist::retrieve_picklist_impl"},
23     "purchase_order" => \&{
24         "OpenILS::Application::Acq::Financials::retrieve_purchase_order_impl"
25     },
26     "invoice" => \&{
27         "OpenILS::Application::Acq::Invoice::fetch_invoice_impl"
28     },
29 );
30
31 sub F { $Fieldmapper::fieldmap->{"Fieldmapper::" . $_[0]}; }
32
33 # This subroutine returns 1 if the argument is a) a scalar OR
34 # b) an array of ONLY scalars. Otherwise it returns 0.
35 sub check_1d_max {
36     my ($o) = @_;
37     return 1 unless ref $o;
38     if (ref($o) eq "ARRAY") {
39         foreach (@$o) { return 0 if ref $_; }
40         return 1;
41     }
42     0;
43 }
44
45 # Returns 1 if and only if argument is an array of exactly two scalars.
46 sub could_be_range {
47     my ($o) = @_;
48     if (ref $o eq "ARRAY") {
49         return 1 if (scalar(@$o) == 2 && (!ref $o->[0] && !ref $o->[1]));
50     }
51     0;
52 }
53
54 sub castdate {
55     my ($value, $gte, $lte) = @_;
56
57     my $op = "=";
58     $op = ">=" if $gte;
59     $op = "<=" if $lte;
60
61     +{$op => {"transform" => "date", "value" => $value}};
62 }
63
64 sub prepare_acqlia_search_and {
65     my ($acqlia) = @_;
66
67     my @phrases = ();
68     foreach my $unit (@{$acqlia}) {
69         my $subquery = {
70             "select" => {"acqlia" => ["id"]},
71             "from" => "acqlia",
72             "where" => {"-and" => [{"lineitem" => {"=" => {"+jub" => "id"}}}]}
73         };
74
75         # castdate not supported for acqlia fields: they're all type text
76         my ($k, $v, $fuzzy, $between, $not) = breakdown_term($unit);
77         my $point = $subquery->{"where"}->{"-and"};
78         my $term_clause;
79
80         push @$point, {"definition" => $k};
81
82         if ($fuzzy and not ref $v) {
83             push @$point, {"attr_value" => {"ilike" => "%" . $v . "%"}};
84         } elsif ($between and could_be_range($v)) {
85             push @$point, {"attr_value" => {"between" => $v}};
86         } elsif (check_1d_max($v)) {
87             push @$point, {"attr_value" => $v};
88         } else {
89             next;
90         }
91
92         my $operator = $not ? "-not-exists" : "-exists";
93         push @phrases, {$operator => $subquery};
94     }
95     @phrases;
96 }
97
98 sub prepare_acqlia_search_or {
99     my ($acqlia) = @_;
100
101     my $point = [];
102     my $result = {"+acqlia" => {"-or" => $point}};
103
104     foreach my $unit (@$acqlia) {
105         # castdate not supported for acqlia fields: they're all type text
106         my ($k, $v, $fuzzy, $between, $not) = breakdown_term($unit);
107         my $term_clause;
108         if ($fuzzy and not ref $v) {
109             $term_clause = {
110                 "-and" => {
111                     "definition" => $k,
112                     "attr_value" => {"ilike" => "%" . $v . "%"}
113                 }
114             };
115         } elsif ($between and could_be_range($v)) {
116             $term_clause = {
117                 "-and" => {
118                     "definition" => $k, "attr_value" => {"between" => $v}
119                 }
120             };
121         } elsif (check_1d_max($v)) {
122             $term_clause = {
123                 "-and" => {"definition" => $k, "attr_value" => $v}
124             };
125         } else {
126             next;
127         }
128
129         push @$point, $not ? {"-not" => $term_clause} : $term_clause;
130     }
131     $result;
132 }
133
134 sub breakdown_term {
135     my ($term) = @_;
136
137     my $key = (grep { !/^__/ } keys %$term)[0];
138     (
139         $key, $term->{$key},
140         $term->{"__fuzzy"} ? 1 : 0,
141         $term->{"__between"} ? 1 : 0,
142         $term->{"__not"} ? 1 : 0,
143         $term->{"__castdate"} ? 1 : 0,
144         $term->{"__gte"} ? 1 : 0,
145         $term->{"__lte"} ? 1 : 0
146     );
147 }
148
149 sub get_fm_links_by_hint {
150     my ($hint) = @_;
151     foreach my $field (values %{$Fieldmapper::fieldmap}) {
152         return $field->{"links"} if $field->{"hint"} eq $hint;
153     }
154     undef;
155 }
156
157 sub gen_au_term {
158     my ($value, $n) = @_;
159     +{
160         "-or" => [
161             {"+au$n" => {"usrname" => $value}},
162             {"+au$n" => {"first_given_name" => $value}},
163             {"+au$n" => {"second_given_name" => $value}},
164             {"+au$n" => {"family_name" => $value}},
165             {"+ac$n" => {"barcode" => $value}}
166         ]
167     };
168 }
169
170 # go through the terms hash, find keys that correspond to fields links
171 # to actor.usr, and rewrite the search as one that searches not by
172 # actor.usr.id but by any of these user properties: card barcode, username,
173 # given names and family name.
174 sub prepare_au_terms {
175     my ($terms, $join_num) = @_;
176
177     my @joins = ();
178     my $nots = 0;
179     $join_num ||= 0;
180
181     foreach my $conj (qw/-and -or/) {
182         next unless exists $terms->{$conj};
183
184         my @new_outer_terms = ();
185         HINT_UNIT: foreach my $hint_unit (@{$terms->{$conj}}) {
186             my $hint = (keys %$hint_unit)[0];
187             (my $plain_hint = $hint) =~ y/+//d;
188             if ($hint eq "-not") {
189                 $hint_unit = $hint_unit->{$hint};
190                 $nots++;
191                 redo HINT_UNIT;
192             }
193
194             if (my $links = get_fm_links_by_hint($plain_hint) and
195                 $plain_hint ne "acqlia") {
196                 my @new_terms = ();
197                 my ($attr, $value) = breakdown_term($hint_unit->{$hint});
198                 if ($links->{$attr} and
199                     $links->{$attr}->{"class"} eq "au") {
200                     push @joins, [$plain_hint, $attr, $join_num];
201                     my $au_term = gen_au_term($value, $join_num);
202                     if ($nots > 0) {
203                         $au_term = {"-not" => $au_term};
204                         $nots--;
205                     }
206                     push @new_outer_terms, $au_term;
207                     $join_num++;
208                     delete $hint_unit->{$hint};
209                 }
210             }
211             if ($nots > 0) {
212                 $hint_unit = {"-not" => $hint_unit};
213                 $nots--;
214             }
215             push @new_outer_terms, $hint_unit if scalar keys %$hint_unit;
216         }
217         $terms->{$conj} = [ @new_outer_terms ];
218     }
219     @joins;
220 }
221
222 sub prepare_terms {
223     my ($terms, $is_and) = @_;
224
225     my $conj = $is_and ? "-and" : "-or";
226     my $outer_clause = {};
227
228     foreach my $class (qw/acqpo acqpl acqinv jub/) {
229         next if not exists $terms->{$class};
230
231         $outer_clause->{$conj} = [] unless $outer_clause->{$conj};
232         foreach my $unit (@{$terms->{$class}}) {
233             my ($k, $v, $fuzzy, $between, $not, $castdate, $gte, $lte) =
234                 breakdown_term($unit);
235
236             my $term_clause;
237             if ($fuzzy and not ref $v) {
238                 $term_clause = {$k => {"ilike" => "%" . $v . "%"}};
239             } elsif ($between and could_be_range($v)) {
240                 $term_clause = {$k => {"between" => $v}};
241             } elsif (check_1d_max($v)) {
242                 $v = castdate($v, $gte, $lte) if $castdate;
243                 $term_clause = {$k => $v};
244             } else {
245                 next;
246             }
247
248             my $clause = {"+" . $class => $term_clause};
249             $clause = {"-not" => $clause} if $not;
250             push @{$outer_clause->{$conj}}, $clause;
251         }
252     }
253
254     if ($terms->{"acqlia"}) {
255         push @{$outer_clause->{$conj}},
256             $is_and ? prepare_acqlia_search_and($terms->{"acqlia"}) :
257                 prepare_acqlia_search_or($terms->{"acqlia"});
258     }
259
260     return undef unless scalar keys %$outer_clause;
261     $outer_clause;
262 }
263
264 sub add_au_joins {
265     my ($from) = shift;
266
267     my $n = 0;
268     foreach my $join (@_) {
269         my ($hint, $attr, $num) = @$join;
270         my $start = $from->{"acqus"}{$hint};
271         my $clause = {
272             "class" => "au",
273             "type" => "left",
274             "field" => "id",
275             "fkey" => $attr,
276             "join" => {
277                 "ac$num" => {
278                     "class" => "ac",
279                     "type" => "left",
280                     "field" => "id",
281                     "fkey" => "card"
282                 }
283             }
284         };
285         $start->{"join"} ||= {};
286         $start->{"join"}->{"au$num"} = $clause;
287         $n++;
288     }
289     $n;
290 }
291
292 __PACKAGE__->register_method(
293     method    => "unified_search",
294     api_name  => "open-ils.acq.lineitem.unified_search",
295     stream    => 1,
296     signature => {
297         desc   => q/Returns lineitems based on flexible search terms./,
298         params => [
299             {desc => "Authentication token", type => "string"},
300             {desc => "Field/value pairs for AND'ing", type => "object"},
301             {desc => "Field/value pairs for OR'ing", type => "object"},
302             {desc => "Conjunction between AND pairs and OR pairs " .
303                 "(can be 'and' or 'or')", type => "string"},
304             {desc => "Retrieval options (clear_marc, flesh_notes, etc) " .
305                 "- XXX detail all the options",
306                 type => "object"}
307         ],
308         return => {desc => "A stream of LIs on success, Event on failure"}
309     }
310 );
311
312 __PACKAGE__->register_method(
313     method    => "unified_search",
314     api_name  => "open-ils.acq.purchase_order.unified_search",
315     stream    => 1,
316     signature => {
317         desc   => q/Returns purchase orders based on flexible search terms.
318             See open-ils.acq.lineitem.unified_search/,
319         return => {desc => "A stream of POs on success, Event on failure"}
320     }
321 );
322
323 __PACKAGE__->register_method(
324     method    => "unified_search",
325     api_name  => "open-ils.acq.picklist.unified_search",
326     stream    => 1,
327     signature => {
328         desc   => q/Returns pick lists based on flexible search terms.
329             See open-ils.acq.lineitem.unified_search/,
330         return => {desc => "A stream of PLs on success, Event on failure"}
331     }
332 );
333
334 __PACKAGE__->register_method(
335     method    => "unified_search",
336     api_name  => "open-ils.acq.invoice.unified_search",
337     stream    => 1,
338     signature => {
339         desc   => q/Returns invoices lists based on flexible search terms.
340             See open-ils.acq.lineitem.unified_search/,
341         return => {desc => "A stream of invoices on success, Event on failure"}
342     }
343 );
344
345 sub unified_search {
346     my ($self, $conn, $auth, $and_terms, $or_terms, $conj, $options) = @_;
347     $options ||= {};
348
349     my $e = new_editor("authtoken" => $auth);
350     return $e->die_event unless $e->checkauth;
351
352     # What kind of object are we returning? Important: (\w+) had better be
353     # a legit acq classname particle, so don't register any crazy api_names.
354     my $ret_type = ($self->api_name =~ /cq.(\w+).un/)[0];
355     my $retriever = $RETRIEVERS{$ret_type};
356     my $hint = F("acq::$ret_type")->{"hint"};
357
358     my $select_clause = {
359         $hint => [{"column" => "id", "transform" => "distinct"}]
360     };
361
362     if ($options->{"order_by"}) {
363         # What's the point of this block?  When using ORDER BY in conjuction
364         # with SELECT DISTINCT, the fields present in ORDER BY have to also
365         # be in the SELECT clause.  This will take _one_ such field and add
366         # it to the SELECT clause as needed.
367         my ($order_by, $class, $field);
368         unless (
369             ($order_by = $options->{"order_by"}->[0]) &&
370             ($class = $order_by->{"class"}) =~ /^[\da-z_]+$/ &&
371             ($field = $order_by->{"field"}) =~ /^[\da-z_]+$/
372         ) {
373             $e->disconnect;
374             return new OpenILS::Event(
375                 "BAD_PARAMS", "note" =>
376 q/order_by clause must be of the long form, like:
377 "order_by": [{"class": "foo", "field": "bar", "direction": "asc"}]/
378             );
379         } else {
380             $select_clause->{$class} ||= [];
381             push @{$select_clause->{$class}}, $field;
382         }
383     }
384
385     my $query = {
386         "select" => $select_clause,
387         from => {
388             acqus => {
389                 jub => {type => "full"},
390                 acqpo => {type => "full"},
391                 acqpl => {type => "full"},
392                 acqinv => {type => "full"}
393             }
394         },
395         "order_by" => ($options->{"order_by"} || {$hint => {"id" => {}}}),
396         "offset" => ($options->{"offset"} || 0)
397     };
398
399     $query->{"limit"} = $options->{"limit"} if $options->{"limit"};
400
401     # XXX for the future? but it doesn't quite work as is.
402 #    # Remove anything in temporary picklists from search results.
403 #    $and_terms ||= {};
404 #    $and_terms->{"acqpl"} ||= [];
405 #    push @{$and_terms->{"acqpl"}}, {"name" => "", "__not" => 1};
406
407     $and_terms = prepare_terms($and_terms, 1);
408     $or_terms = prepare_terms($or_terms, 0) and do {
409         $query->{"from"}{"acqus"}{"jub"}{"join"}{"acqlia"} = {
410             "type" => "left", "field" => "lineitem", "fkey" => "id",
411         };
412     };
413
414     my $offset = add_au_joins($query->{"from"}, prepare_au_terms($and_terms));
415     add_au_joins($query->{"from"}, prepare_au_terms($or_terms, $offset));
416
417     if ($and_terms and $or_terms) {
418         $query->{"where"} = {
419             "-" . (lc $conj eq "or" ? "or" : "and") => [$and_terms, $or_terms]
420         };
421     } elsif ($and_terms) {
422         $query->{"where"} = $and_terms;
423     } elsif ($or_terms) {
424         $query->{"where"} = $or_terms;
425     } else {
426         $e->disconnect;
427         return new OpenILS::Event("BAD_PARAMS", "desc" => "No usable terms");
428     }
429
430     my $results = $e->json_query($query) or return $e->die_event;
431     my @id_list = map { $_->{"id"} } (grep { $_->{"id"} } @$results);
432
433     if ($options->{"id_list"}) {
434         $conn->respond($_) foreach @id_list;
435     } else {
436         foreach(@id_list){
437             my $resp = $retriever->($e, $_, $options);
438             next if(ref($resp) ne "Fieldmapper::acq::$ret_type");
439             $conn->respond($resp);
440         }
441     }
442
443     $e->disconnect;
444     undef;
445 }
446
447 __PACKAGE__->register_method(
448     method    => "bib_search",
449     api_name  => "open-ils.acq.biblio.wrapped_search",
450     stream    => 1,
451     signature => {
452         desc   => q/Returns new lineitems for each matching bib record/,
453         params => [
454             {desc => "Authentication token", type => "string"},
455             {desc => "search string", type => "string"},
456             {desc => "search options", type => "object"}
457         ],
458         return => {desc => "A stream of LIs on success, Event on failure"}
459     }
460 );
461
462 __PACKAGE__->register_method(
463     method    => "bib_search",
464     api_name  => "open-ils.acq.biblio.create_by_id",
465     stream    => 1,
466     signature => {
467         desc   => q/Returns new lineitems for each matching bib record/,
468         params => [
469             {desc => "Authentication token", type => "string"},
470             {desc => "list of bib IDs", type => "array"},
471             {desc => "options (for lineitem fleshing)", type => "object"}
472         ],
473         return => {desc => "A stream of LIs on success, Event on failure"}
474     }
475 );
476
477 # This is very similar to zsearch() in Order.pm
478 sub bib_search {
479     my ($self, $conn, $auth, $search, $opts) = @_;
480
481     my $e = new_editor("authtoken" => $auth, "xact" => 1);
482     return $e->die_event unless $e->checkauth;
483     return $e->die_event unless $e->allowed("CREATE_PICKLIST");
484
485     my $mgr = new OpenILS::Application::Acq::BatchManager(
486         "editor" => $e, "conn" => $conn
487     );
488
489     $opts ||= {};
490
491     my $picklist;
492     my @li_ids = ();
493     if ($self->api_name =~ /create_by_id/) {
494         $search = [ sort @$search ]; # for consitency
495         my $bibs = $e->search_biblio_record_entry(
496             {"id" => $search}, {"order_by" => {"bre" => ["id"]}}
497         ) or return $e->die_event;
498
499         if ($opts->{"reuse_picklist"}) {
500             $picklist = $e->retrieve_acq_picklist($opts->{"reuse_picklist"}) or
501                 return $e->die_event;
502             return $e->die_event unless
503                 $e->allowed("UPDATE_PICKLIST", $picklist->org_unit);
504
505             # If we're reusing an existing picklist, we don't need to
506             # create new lineitems for any bib records for which we already
507
508             my $already_have = $e->search_acq_lineitem({
509                 "picklist" => $picklist->id,
510                 "eg_bib_id" => [ map { $_->id } @$bibs ]
511             }) or return $e->die_event;
512          
513             # So in that case we a) save the lineitem id's of the relevant
514             # items that already exist so that we can return those items later,
515             # and b) remove the bib id's in question from our list of bib
516             # id's to lineitemize.
517             if (@$already_have) {
518                 push @li_ids, $_->id foreach (@$already_have);
519                 my @new_bibs = ();
520                 foreach my $bib (@$bibs) {
521                     push @new_bibs, $bib unless
522                         grep { $_->eg_bib_id == $bib->id } @$already_have;
523                 }
524                 $bibs = [ @new_bibs ];
525             }
526         } else {
527             $picklist = OpenILS::Application::Acq::Order::zsearch_build_pl($mgr, undef)
528                 or return $e->die_event;
529         }
530
531         $conn->respond($picklist->id);
532
533         push @li_ids, map {
534             OpenILS::Application::Acq::Order::create_lineitem(
535                 $mgr,
536                 "picklist" => $picklist->id,
537                 "source_label" => "native-evergreen-catalog",
538                 "marc" => $_->marc,
539                 "eg_bib_id" => $_->id
540             )->id;
541         } (@$bibs);
542     } else {
543         $opts->{"limit"} ||= 10;
544
545         my $ses = create OpenSRF::AppSession("open-ils.search");
546         my $req = $ses->request(
547             "open-ils.search.biblio.multiclass.query.staff", $opts, $search
548         );
549
550         my $count = 0;
551         while (my $resp = $req->recv("timeout" => 60)) {
552             $picklist = OpenILS::Application::Acq::Order::zsearch_build_pl(
553                 $mgr, undef
554             ) unless $count++;
555
556             my $result = $resp->content;
557             next if not ref $result;
558
559             # The result object contains a whole heck of a lot more information
560             # than just bib IDs, so maybe we could tell the client something
561             # useful (progress meter at least) in the future...
562             push @li_ids, map {
563                 my $bib = $_->[0];
564                 OpenILS::Application::Acq::Order::create_lineitem(
565                     $mgr,
566                     "picklist" => $picklist->id,
567                     "source_label" => "native-evergreen-catalog",
568                     "marc" => $e->retrieve_biblio_record_entry($bib)->marc,
569                     "eg_bib_id" => $bib
570                 )->id;
571             } (@{$result->{"ids"}});
572         }
573         $ses->disconnect;
574     }
575
576     $e->commit;
577
578     $logger->info("created @li_ids new lineitems for picklist $picklist");
579
580     # new editor, but still using transaction to ensure correct retrieval
581     # in a replicated setup
582     $e = new_editor("authtoken" => $auth, xact => 1) or return $e->die_event;
583     return $e->die_event unless $e->checkauth;
584     $conn->respond($RETRIEVERS{"lineitem"}->($e, $_, $opts)) foreach @li_ids;
585     $e->rollback;
586     $e->disconnect;
587
588     undef;
589 }
590
591 1;