datelastborrowed
[ferlib2koha.git] / ferlib2koha.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4 use DBI;
5 use Data::Dump qw/dump/;
6 use Algorithm::CheckDigits;
7
8 # sudo apt-get install libdbd-sqlite3-perl libdbd-csv-perl
9
10 $|++;
11
12 my $import = {
13         borrowers => $ENV{FULL} || 0,
14         issues    => $ENV{FULL} || 1,
15         reserves  => $ENV{FULL} || 0,
16         barcode   => $ENV{FULL} || 0,
17 };
18
19 my $f = DBI->connect("dbi:SQLite:dbname=knjiznica.sqlite","","", { RaiseError => 1, AutoCommit => 0 }) || die $DBI::errstr;
20 $f->{sqlite_unicode} = 1;
21 my $k = DBI->connect("dbi:mysql:database=koha_fer","","", { RaiseError => 1, AutoCommit => 0, mysql_enable_utf8 => 1 }) || die $DBI::errstr;
22 my $u = DBI->connect("dbi:CSV:","","", { RaiseError => 1, f_ext => '.csv', csv_sep_char => '|' }) || die $DBI::errstr;
23
24 our $lookup;
25 sub lookup {
26         my ( $dbh, $t, $k, $v, $s, $default ) = @_;
27         my $hash;
28         my $key = "$t $k $v";
29         if ( exists $lookup->{$key} ) {
30                 $hash = $lookup->{$key};
31         } else {
32                 warn "# select $k,$v from $t";
33                 my $sth = $dbh->prepare( "select $k,$v from $t" );
34                 $sth->execute;
35                 while (my $row = $sth->fetchrow_hashref() ) {
36                         $hash->{ $row->{$k} } = $row->{$v};
37                 }
38                 $lookup->{$key} = $hash;
39                 warn "# lookup $key = ",dump($hash);
40         }
41         return unless length $s > 1;
42         if ( ! exists $lookup->{$key}->{$s} ) {
43                 warn "ERROR: no $s in $key\n";
44                 return $default;
45         } else {
46                 $lookup->{$key}->{$s};
47         }
48 }
49
50 our $insert;
51 sub insert {
52         my ( $table, $row ) = @_;
53         $insert->{$table} ||= $k->prepare(
54                         "insert into $table ("
55                         . join(',', keys %$row)
56                         . ") values ("
57                         . join(',', map { '?' } keys %$row )
58                         . ")"
59         );
60
61         foreach my $c ( grep { /(date|timestamp)/ } keys %$row ) {
62                 $row->{$c} =~ s/^(\d\d)\.(\d\d)\.(\d\d\d\d)/$3-$2-$1/;
63                 $row->{$c} = undef if $row->{$c} eq ''; # XXX NULL dates istead of 0000-00-00
64         }
65
66         $insert->{$table}->execute( values %$row );
67         warn "# inserted $table ", dump $row;
68
69 }
70
71 sub borrowers {
72         my $sql = shift;
73         my $sth = $f->prepare($sql);
74         $sth->execute;
75
76         $insert = undef;
77
78         while (my $row = $sth->fetchrow_hashref ) {
79
80 #               warn dump $row;
81
82                 # poor man's (sqlite) outer join
83                 $row->{'country'} = lookup($f, 'drzava', 'ozn_drzava', 'naz_drzava', $row->{'country'}, $row->{contry} );
84                 $row->{'city'}    = lookup($f, 'mjesto', 'post_ozn', 'naz_mjesto', $row->{'city'}, $row->{city} );
85
86                 $row->{'B_country'} = lookup($f, 'drzava', 'ozn_drzava', 'naz_drzava', $row->{'B_country'}, $row->{B_country} );
87                 $row->{'B_city'}    = lookup($f, 'mjesto', 'post_ozn', 'naz_mjesto', $row->{'B_city'}, $row->{B_city} );
88
89                 $row->{'B_email'}  = lookup($f, 'clanost', 'ozn_vrclan||ozn_clan', 'email', $row->{'cardnumber'}, undef);
90                 $row->{'emailpro'} = lookup($f, 'clanost', 'ozn_vrclan||ozn_clan', 'email_k', $row->{'cardnumber'}, undef);
91
92                 $row->{'email'}    = lookup($u, 'users', 'jmbag', 'email', substr($row->{cardnumber},1), undef); # $row->{B_email} || $row->{emailpro} )
93
94                 $row->{'userid'}    = lookup($u, 'users', 'jmbag', 'nick', substr($row->{cardnumber},1), $row->{cardnumber});
95
96                 $row->{sex} =~ s/\x{17D}/F/;
97
98                 $row->{city} ||= '?'; # not null
99
100                 $row->{borrowernotes} = lookup($f, 'clanorg', 'ozn_vrclan||ozn_clan', 'napom_clan', $row->{'cardnumber'}, undef);
101
102                 $row->{title} = lookup($f, 'titula', 'ozn_titula', 'opis_titula', $row->{title}, $row->{title});
103
104                 $row->{dateexpiry} ||= '01.01.2020'; # next revision
105
106                 my $jmbg = delete $row->{jmbg};
107
108                 insert 'borrowers' => $row;
109
110                 insert 'borrower_attributes' => {
111                         borrowernumber => $k->{mysql_insertid},
112                         code => 'JMBG',
113                         attribute => $jmbg,
114                 } if $jmbg;
115
116         }
117 }
118
119 sub sql {
120         my ($db,$sql) = @_;
121         foreach (split(/;/,$sql)) {
122                 next if m/^\s*$/;
123                 warn "# sql $_";
124                 $db->do($_);
125         }
126 }
127
128 if ( $import->{borrowers} ) {
129
130 sql $k => qq{
131 delete from borrowers;
132 alter table borrowers auto_increment = 1;
133 delete from borrower_attributes;
134 alter table borrower_attributes auto_increment = 1;
135 };
136
137
138 borrowers qq{
139 select
140   'S' as categorycode,
141   'SRE' as branchcode,
142   'S' || mbr_stud as cardnumber,
143   prez_stud as surname,
144   ime_stud as firstname,
145   djevprezime as othernames,
146   spol as sex,
147   dat_rodj as dateofbirth,
148 --  ime_otac as ??,
149 --  ime_majka as ??,
150   ozn_drzava_preb as country,
151   post_ozn_preb as zipcode,
152   post_ozn_preb as city,
153   adr_preb as address,
154   ozn_drzava_stan as B_country,
155   post_ozn_stan as B_zipcode,
156   post_ozn_stan as B_city,
157   adr_stan as B_address,
158   tel_stud as phone,
159   dat_prava_do as dateexpiry,
160 --  aktivan as ??,
161   jmbg_stud as jmbg
162 from studk
163 };
164
165 borrowers qq{
166 select
167   'D' as categorycode,
168   'SRE' as branchcode,
169   'D' || sif_djel as cardnumber,
170   ime_djel as firstname,
171   prez_djel as surname,
172   ozn_titula as title,
173 --  sif_orgjed (REF orgjed) as B_address,
174 --  sif_strsp_djel as ??,
175   tel_djel as phonepro,
176   dat_prekid_ro as dateexpiry,
177 --  tel_poduz as ??,
178   fax_poduz as fax,
179   ozn_drzava as country,
180   post_ozn as zipcode,
181   post_ozn as city,
182   adr_stan as address,
183   tel_stan as phone,
184   jmbg_djel as jmbg
185 from djelat
186 };
187
188 borrowers qq{
189 select
190   'O' as categorycode,
191   'SRE' as branchcode,
192   'O' || mbr_clan as cardnumber,
193   ime_clan as firstname,
194   prez_clan as surname,
195   ozn_titula as title,
196   zvanje_clan as ethnicity, -- XXX we are not allowerd by low to collect ethnicity
197 --  krat_poduz (REF poduz) as B_address,
198   tel_poduz as B_phone,
199 --  fax_poduz as ??,
200   ozn_drzava as country,
201   post_ozn as zipcode,
202   post_ozn as city,
203   adr_stan as address,
204   tel_stan as phone,
205 --  aktivan as ??,
206   jmbg_clan as jmbg
207 from clost
208 };
209
210 my $sth_syspref = $k->prepare(qq{ update systempreferences set value=? where variable=? });
211 my $BorrowersTitles = join('|', @{ $k->selectcol_arrayref(qq{ select distinct title from borrowers where title != '' }) });
212 $sth_syspref->execute( $BorrowersTitles => 'BorrowersTitles' );
213 warn "# BorrowersTitles [$BorrowersTitles]";
214
215 } # import->{borrowers}
216
217
218 if ( $import->{issues} ) {
219
220 $k->do(qq{ update items set barcode=substr(barcode,1,12)*1 where length(barcode) = 13 }); # convert barcodes back for lookups to work
221
222 sub issues {
223         my ($table,$sql) = @_;
224         my $sth = $f->prepare($sql);
225         $sth->execute;
226
227         $insert = undef;
228
229         while (my $row = $sth->fetchrow_hashref ) {
230                 $row->{borrowernumber} = lookup($k, 'borrowers', 'cardnumber' => 'borrowernumber', $row->{borrowernumber});
231                 $row->{itemnumber}     = lookup($k, 'items', 'barcode' => 'itemnumber', $row->{itemnumber});
232
233                 my $stat = {
234                         datetime => $row->{returndate} || $row->{issuedate},
235                         branch   => $row->{branchcode},
236                         value    => 0,
237                         type     => $row->{returndate} ? 'return' : 'issue',
238                 };
239                 $stat->{$_} = $row->{$_} foreach (qw( itemnumber borrowernumber ));
240
241                 $row->{date_due} ||= '31.12.2011';
242                 insert $table => $row;
243
244                 insert statistics => $stat;
245         }
246 }
247
248 my $posud_sql = qq{
249 select
250         ozn_vrclan||ozn_clan as borrowernumber,
251         sif_primj as itemnumber,
252         datum_do as date_due,
253         'SRE' as branchcode, -- FIXME
254         datum_vra as returndate,
255         datum_pos as issuedate,
256         datum_pos||' '||vrijeme_pos as timestamp
257 from posud
258 };
259
260 sql $k => qq{
261 delete from old_issues;
262 alter table old_issues auto_increment = 1;
263 delete from issues;
264 alter table issues auto_increment = 1;
265 };
266 issues 'old_issues' => qq{$posud_sql where datum_vra != ''};
267 issues 'issues'     => qq{$posud_sql where datum_vra == ''};
268
269 sql $k => qq{
270 update items
271 join issues on items.itemnumber=issues.itemnumber
272 set onloan = date_due, datelastborrowed = issuedate
273 ;
274 update items set datelastseen = datelastborrowed
275 ;
276 create temporary table old_returndate as
277 select itemnumber,max(returndate) as returndate
278 from old_issues
279 group by itemnumber,returndate
280 ;
281 update items
282 join old_returndate on items.itemnumber=old_returndate.itemnumber
283 set datelastseen = returndate
284 where returndate > datelastseen or datelastseen is null
285 ;
286 create temporary table old_issuedate as
287 select itemnumber,max(issuedate) as issuedate
288 from old_issues
289 group by itemnumber,issuedate
290 ;
291 update items
292 join old_issuedate on items.itemnumber=old_issuedate.itemnumber
293 set datelastborrowed = issuedate
294 where datelastborrowed is null
295 ;
296 update old_issues set timestamp = returndate
297 };
298
299 }; # import->{issues}
300
301
302 if ( $import->{reserves} ) {
303
304 sql $k => qq{
305 delete from reserves;
306 alter table reserves auto_increment = 1;
307 delete from old_reserves;
308 alter table old_reserves auto_increment = 1;
309 };
310
311 sub reserves {
312         my ($table, $sql) = @_;
313         my $sth = $f->prepare($sql);
314         $sth->execute;
315
316         $insert = undef;
317
318         while (my $row = $sth->fetchrow_hashref ) {
319
320                 $row->{found} =
321                         $row->{found}      ? 'F' : 
322                         $row->{itemnumber} ? 'W' : undef;
323
324                 $row->{borrowernumber} = lookup($k, 'borrowers', 'cardnumber' => 'borrowernumber', $row->{borrowernumber});
325                 $row->{biblionumber}   = lookup($k, 'biblioitems', 'collectionvolume' => 'biblionumber', $row->{biblionumber});
326                 $row->{itemnumber}     = lookup($k, 'items', 'barcode' => 'itemnumber', $row->{itemnumber});
327
328                 insert $table => $row;
329         }
330 }
331
332 my $sql_reserves = qq{
333 select
334         ozn_vrclan||ozn_clan as borrowernumber,
335         datum_rezerv as reservedate,
336         sif_naslov as biblionumber,
337         'a' as constrainttype,
338         'SRE' as branchcode,
339         datum_obavijest as notificationdate,
340         datum_ponist as cancellationdate,
341         2 - prior_rezerv as priority,
342         datum_posud as found, -- F|W
343         datum_rezerv||' '||vrijeme_rezerv as timestamp,
344         sif_primj as itemnumber,
345         datum_obavijest as waitingdate,
346         vrijedi_do as expirationdate,
347         0 as lowestPriority
348 from rezerv
349 };
350
351 reserves 'old_reserves' => qq{$sql_reserves where datum_opoziv != '' or  datum_ponist != '' or  datum_posud != ''};
352 reserves 'reserves'     => qq{$sql_reserves where datum_opoziv == '' and datum_ponist == '' and datum_posud == ''};
353
354 } # $import->{reserves}
355
356
357 if ( $import->{barcode} ) { # XXX must be last!
358
359 my $sth        = $k->prepare(qq{ select itemnumber,barcode from items where length(barcode) < 13 });
360 my $sth_update = $k->prepare(qq{ update items set barcode=? where itemnumber=? });
361
362 $sth->execute;
363 warn "update ", $sth->rows, " barcodes";
364
365 my $ean = CheckDigits('ean');
366
367 while( my $row = $sth->fetchrow_hashref ) {
368         $sth_update->execute( $ean->complete( sprintf('%012d', $row->{barcode}) ), $row->{itemnumber} );
369 }
370
371 } # import->{barcode}
372
373
374
375
376 $k->commit;