lib/NOLookup/Brreg/DataLookup.pm untested

filter: Statementstmt 0.0% 0 / 167 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 32 MC/DCmcdc 0.0% 0 / 20 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 290 CC 24 SCAR 35.9
CC
24
Cov
0%
_lookup_org_entries
110.0
_init_lookup
20.0
lookup_reg_dates
20.0
CRAP 36.1
1 package NOLookup::Brreg::DataLookup;
2  
3 use warnings;
4 use strict;
5 use base qw(Class::Accessor::Chained); ## Provides a new() method
6 use POSIX qw(locale_h);
7 use NOLookup::Brreg::Entry;
8 use WWW::Mechanize;
9 use JSON;
10 use URI::Encode qw(uri_encode);
11 use Data::Dumper;
12  
13 $Data::Dumper::Indent=1;
14  
15 my $BRREG_TIMEOUT = 60; # secs (default is 180 secs but we want shorter time).
16 my $MAX_PAGES = 10; # max pages to fetch if no max is specified
17 my $MAX_SIZE = 100; # max size to ask for in each request
18  
19 # API service URLs
20 my $BRREG = "https://data.brreg.no/enhetsregisteret/api";
21 my $BRREG_UPD = "https://data.brreg.no/enhetsregisteret/api/oppdateringer";
22  
23 ###
24 # API version selection.
25 # It is possible to specify a specific version of the API,
26 # and we use that to get a more stable API.
27 #
28 # Version is signalled by use of the http accept_header in request,
29 # with the below header strings.
30  
31 my $use_header = 1; # Set to 0 for no header, 1 to use header
32  
33 # Only v1 supported for now, as it is the only one that exists.
34 my $hver = "v1"; # Set to "v1" for version 1, etc.
35  
36 my $AC_COMMON = "application/vnd.brreg.enhetsregisteret";
37
38 my $AC_HEADER_E = "$AC_COMMON.enhet.$hver+json";
39 my $AC_HEADER_UE = "$AC_COMMON.underenhet.$hver+json";
40 my $AC_HEADER_E_UPD = "$AC_COMMON.oppdatering.enhet.$hver+json";
41 my $AC_HEADER_UE_UPD = "$AC_COMMON.oppdatering.underenhet.$hver+json";
42  
43 my @module_methods = qw /
44  
45 lookup_orgno
46 lookup_orgname
47 lookup_reg_dates
48 lookup_update_dates
49  
50 orgno_ok
51  
52 status
53 error
54 warning
55  
56 data
57 size
58 total_size
59  
60 cur_page
61 next_page
62 prev_page
63 total_page_count
64  
65 raw_json_decoded
66 /;
67  
68 # The new method and also the accessor methods
69 __PACKAGE__->mk_accessors(
70 @module_methods
71 );
72  
73  
74 ######## L o o k u p
75  
76 sub _init_lookup {
77 my ($self, $sok_underenheter, $sok_updates) = @_;
78
79 my $ENHETER = "enheter";
80 my $AC_HEADER = $AC_HEADER_E;
81 if ($sok_updates) {
82 $AC_HEADER = $AC_HEADER_E_UPD;
83 }
84 if ($sok_underenheter) {
85 $ENHETER = "under" . $ENHETER;
86 $AC_HEADER = $AC_HEADER_UE;
87 if ($sok_updates) {
88 $AC_HEADER = $AC_HEADER_UE_UPD;
89 }
90 }
91 return ($ENHETER, $AC_HEADER);
92  
93 }
94  
95 sub lookup_orgno {
96 my ($self, $orgno, $sok_underenheter) = @_;
97  
98 unless ($orgno) {
99 $self->status("mandatory parameter 'orgno' not specified");
100 $self->error(1);
101 return 0;
102 }
103  
104 # validate the organizaton number
105 unless ($self->orgno_ok($orgno)) {
106 # errno has already been set
107 return $self;
108 }
109  
110 my ($ENHETER, $AC_HEADER) = $self->_init_lookup($sok_underenheter);
111
112 ##
113 # Use the orgno as key to brreg.
114 # Match is only found if number does exist.
115 $self->size(0);
116 $self->_lookup_org_entries("$BRREG/$ENHETER/$orgno", $AC_HEADER);
117  
118 }
119  
120 sub lookup_orgname {
121 my ($self, $orgname, $max_no_pages, $page_ix, $sok_underenheter, $page_sz) = @_;
122
123 unless ($orgname) {
124 $self->status("mandatory parameter 'orgname' not specified");
125 $self->error(1);
126 return 0;
127 }
128  
129 my ($ENHETER, $AC_HEADER) = $self->_init_lookup($sok_underenheter);
130  
131 # Use the orgname as filter in search to brreg
132 my $onm_e = uri_encode($orgname, {encode_reserved => 1});
133  
134 my $PAGE_SIZE = $page_sz || $MAX_SIZE;
135
136 my $BR = "$BRREG/$ENHETER/?size=$PAGE_SIZE&navn=$onm_e";
137  
138 $self->_fetch_pages($BR, $max_no_pages, $page_ix, $AC_HEADER);
139 }
140  
141 sub lookup_reg_dates {
142 my ($self, $from_date, $to_date, $max_no_pages, $page_ix, $sok_underenheter) = @_;
143
144 unless ($from_date || $to_date) {
145 $self->status("mandatory parameter 'from_date or to_date' not specified");
146 $self->error(1);
147 return 0;
148 }
149  
150 my ($ENHETER, $AC_HEADER) = $self->_init_lookup($sok_underenheter);
151
152 # Use the from / to dates as filter for lookup on
153 # registration dates
154 my $rdateF = "fraRegistreringsdatoEnhetsregisteret";
155 my $rdateT = "tilRegistreringsdatoEnhetsregisteret";
156  
157 my $dateFilter;
158  
159 if ($from_date && !$to_date) {
160 $dateFilter = "$rdateF=$from_date";
161 } elsif (!$from_date && $to_date) {
162 $dateFilter = "$rdateT=$to_date";
163 } else {
164 $dateFilter = "$rdateF=$from_date&$rdateT=$to_date";
165 }
166
167 my $BR = "$BRREG/$ENHETER/?size=$MAX_SIZE&$dateFilter";
168
169 $self->_fetch_pages($BR, $max_no_pages, $page_ix, $AC_HEADER);
170  
171 }
172  
173  
174 sub lookup_update_dates {
175 my ($self, $from_date, $update_id, $max_no_pages, $page_ix, $sok_underenheter) = @_;
176  
177 unless ($from_date || $update_id) {
178 $self->status("mandatory parameter 'update from_date or update_id' not specified");
179 $self->error(1);
180 return 0;
181 }
182  
183 my ($ENHETER, $AC_HEADER) = $self->_init_lookup($sok_underenheter, 1);
184  
185 # Use the from / to dates as filter for lookup on
186 # update date
187 my $updFilter;
188 my $midnight = "T00:00:00.000Z";
189
190 if ($from_date && !$update_id) {
191 $updFilter = "dato=$from_date$midnight";
192 } elsif (!$from_date && $update_id) {
193 $updFilter = "oppdateringsid=$update_id";
194 } else {
195 $updFilter = "dato=$from_date$midnight&oppdateringsid=$update_id";
196 }
197
198 my $BR = "$BRREG_UPD/$ENHETER/?size=$MAX_SIZE&$updFilter";
199
200 $self->_fetch_pages($BR, $max_no_pages, $page_ix, $AC_HEADER);
201  
202 }
203  
204  
205 sub orgno_ok {
206 my ($self, $orgno) = @_;
207  
208 # remove any white spaces
209 $orgno =~ s/\s+//g;
210  
211 if ($orgno eq "000000000") {
212 $self->status("Invalid orgno: $orgno");
213 $self->error(1);
214 return 0;
215 }
216 unless ($orgno =~ m/\d{9}/) {
217 $self->status("Organization number $orgno must be 9 digits");
218 $self->error(1);
219 return 0;
220 }
221 return 1;
222 }
223  
224 sub _fetch_pages {
225 my ($self, $BR, $max_no_pages, $page_ix, $accept_header) = @_;
226
227 # Fetch the requested pages
228 # First page is 0
229 # Set size and total size so we get the first lookup
230  
231 my $max_pg_to_fetch = $max_no_pages || $MAX_PAGES;
232 my $pg_ix = $page_ix || 0;
233  
234 my $pix = $pg_ix;
235 my $pcnt = 1;
236 my $bsize = -1;
237  
238 $self->size(0);
239 $self->total_size(1);
240 $self->next_page(1); # force the first lookup
241  
242 while ($pcnt <= $max_pg_to_fetch && $bsize < $self->size && $self->size < $self->total_size) {
243 # Remember size before next lookup. If size has not increased, stop the loop.
244 $bsize = $self->size;
245  
246 $self->_lookup_org_entries("$BR&page=$pix", $accept_header);
247 ++$pcnt;
248 ++$pix;
249 }
250 }
251  
252 sub _lookup_org_entries {
253 my ($self, $URL, $accept_header) = @_;
254  
255 print STDERR "URL: $URL\n" if ($self->{debug});
256
257 my $mech = WWW::Mechanize->new(
258 timeout => $BRREG_TIMEOUT,
259 autocheck => 0,
260 );
261  
262 # Specify API version to use
263 #https://data.brreg.no/enhetsregisteret/api/docs/index.html#_hvordan_velger_jeg_versjon
264 if ($use_header) {
265 $mech->add_header( Accept => $accept_header);
266 $mech->add_header( Charset => "UTF-8");
267 }
268
269 my $resp = $mech->get($URL);
270  
271 unless ($mech->success) {
272 $self->status($resp->status_line);
273 $self->error(1);
274 $self->next_page(undef);
275 return $self;
276 }
277
278 my $json;
279 {
280 local $@; # protect existing $@
281 eval {
282 $json = decode_json($mech->content(format=>'text'));
283 };
284 if ($@) {
285 # Some error
286 $self->status("Invalid response");
287 $self->error(1);
288 $self->next_page(undef);
289 return $self;
290 }
291 }
292  
293 if ($json) {
294 $self->raw_json_decoded($json);
295
296 # Map the json data structure to
297 # internal entry objects
298 my $eo = NOLookup::Brreg::Entry->new;
299 my $entries = $eo->map_json_entries($json);
300  
301 #print STDERR "eo: ", Dumper $eo;
302  
303 # Collect any accumulated problems
304 $self->status($eo->status) if ($eo->status);
305 $self->warning($eo->warning) if ($eo->warning);
306 $self->error($eo->error) if ($eo->error);
307  
308 # Save the found data
309 if (@$entries) {
310 push @{$self->{data}}, @$entries;
311  
312 $self->size($self->size + scalar @$entries);
313 $self->total_size($eo->total_result_count);
314  
315 $self->total_page_count($eo->total_page_count);
316  
317 $self->cur_page($eo->cur_page);
318 $self->next_page($eo->next_page);
319 $self->prev_page($eo->prev_page);
320 } else {
321 $self->total_size(0);
322 }
323 }
324  
325 #print STDERR Dumper $self;
326
327 return $self;
328 }
329  
330 =pod
331  
332 =encoding ISO-8859-1
333  
334 =head1 NAME
335  
336 NOLookup::Brreg::DataLookup - Lookup Brreg basic organization data from
337 the JSON formatted service offered by the Brreg data API via
338 https://data.brreg.no/enhetsregisteret/oppslag/enheter
339 https://data.brreg.no/enhetsregisteret/api/docs/index.html
340  
341 (Brreg is a short name for 'Brønnysundregistrene, the Norwegian
342 Central Organization Registry).
343  
344 =head1 DESCRIPTION
345  
346 Use WWW::Mechanize and JSON to lookup data from the JSON API at brreg.
347 Use NOLookup::Brreg::Entry module to map the resulting json data
348 structure to a NOLookup::Brreg::Entry objects.
349  
350 The timeout period $BRREG_TIMEOUT is used to trap and return the call
351 if Brreg lookup is hanging for some reason.
352  
353 =head1 METHODS
354  
355 The module provides the below methods.
356  
357 =head3 _init_lookup
358  
359 Common init method.
360  
361 - Set seach URLs.
362 - Returns URL and accept header.
363  
364
365 =head3 lookup_orgno()
366  
367 Lookup based on a complete organization number.
368  
369 Returns an array of one single NOLookup::Brreg::Entry object in the data
370 when a match is found.
371  
372 =head3 lookup_orgname()
373  
374 Lookup based on a complete or part of an organization name.
375  
376 Returns 0 entries if none found.
377  
378 Returns an array of NOLookup::Brreg::Entry objects in the data
379 when matches are found.
380  
381 A maximum of $max_no_pages pages are fetched, each of $page_sz
382 entries, default $MAX_SIZE.
383  
384 =head3 lookup_reg_dates()
385  
386 Lookup based on registration dates.
387 A from_date and/or a to_date can be specified.
388  
389 The lookup will find registrations performed after midnight starting
390 the from date, and until midnight at the end of the to date.
391  
392 Returns 0 entries if none found.
393  
394 Returns an array of NOLookup::Brreg::Entry objects in the data
395 when matches are found.
396  
397 A maximum of $max_no_pages pages are fetched, each of 100 entries.
398  
399  
400 =head3 lookup_update_dates()
401  
402 Lookup based on update date and update id.
403  
404 The lookup will find updated organizations performed after midnight
405 starting on the from date. The minimum update id can also be set.
406  
407 Returns 0 entries if none found.
408  
409 Returns an array of NOLookup::Brreg::Entry objects in the data
410 when matches are found.
411  
412 A maximum of $max_no_pages pages are fetched, each of 100 entries.
413  
414  
415 =head3 orgno_ok()
416  
417 Check if org. number basic syntax is OK, i.e. 9 digits.
418 Note that Brreg may reject the number due to stricter
419 requirements, like checksum etc.
420  
421 =head3 raw_json_decoded()
422  
423 The raw JSON data structure, as returned by the JSON service,
424 and then decoded to a perl data structure with decode_json().
425  
426 =head3 error()
427  
428 Set if an error has occured.
429 On errors, the lookup terminates, with more info
430 in the status().
431  
432 =head3 warning()
433  
434 Set if a warning has occured.
435 On warnings, the lookup continues, but warnings
436 are accumulated in the status().
437  
438 =head3 status()
439  
440 Further description of error/warning situations.
441  
442 =head3 data()
443  
444 The found data, an array of NOLookup::Brreg::Entry data objects.
445  
446 See doc. for NOLookup::Brreg::Entry for details.
447  
448 =head3 size()
449  
450 The number of objects found in a page lookup
451  
452 =head3 total_size()
453  
454 The total number of objects found by the search.
455  
456 Only set if all data has been fetched.
457  
458 Only if total_size is set, the user can assume that all data has been
459 fetched.
460  
461 =head3 cur_page()/prev_page()/next_page()
462  
463 If more pages can be fetched, those methods give the URL to that page
464  
465 =head3 total_page_count()
466  
467 Count of total nuber of pages matching the search
468  
469 =head3 result_count()
470  
471 Count of total results for the search
472  
473  
474 =head1 SUPPORT
475  
476 For now, support questions should be sent to:
477  
478 E<lt>(nospam)info(at)norid.noE<gt>
479  
480 Please also see the README file in the distribution.
481  
482 =head1 SEE ALSO
483  
484 https://www.brreg.no
485 https://data.brreg.no/enhetsregisteret/oppslag/enheter
486  
487 =head1 AUTHOR
488  
489 Trond Haugen, E<lt>(nospam)info(at)norid.noE<gt>
490  
491 =head1 COPYRIGHT
492  
493 Copyright (c) 2017- Trond Haugen <(nospam)info(at)norid.no>.
494 All rights reserved.
495  
496 This program is free software; you can redistribute it and/or modify
497 it under the terms of the GNU General Public License as published by
498 the Free Software Foundation; either version 2 of the License, or
499 (at your option) any later version.
500  
501 =head1 LICENSE
502  
503 This library is free software. You can redistribute it and/or modify
504 it under the same terms as Perl itself.
505  
506 =cut
507  
508 =head1 TODO
509  
510 Perhaps add an address object to contain the address info.
511  
512 =cut
513
514 1;