blib/lib/oEdtk/Outmngr.pm untested

filter: Statementstmt 0.0% 0 / 658 Branchbran 0.0% 0 / 168 Conditioncond 0.0% 0 / 131 MC/DCmcdc 0.0% 0 / 75 Subroutinesub 0.0% 0 / 39 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 1095 CC 85 SCAR 53.9
CC
85
Cov
0%
omgr_export
600.0
_omgr_insert
462.0
omgr_stats
110.0
CRAP 218.3
1 package oEdtk::Outmngr;
2  
3 use strict;
4 use warnings;
5  
6 use File::Basename;
7 use Sys::Hostname;
8 use Text::CSV;
9 use Date::Calc qw(Today Gmtime Week_of_Year Add_Delta_Days Day_of_Week);
10 use List::Util qw(max sum);
11 use oEdtk::Config qw(config_read);
12 use oEdtk::DBAdmin qw(db_connect db_backup_agent create_table_OUTMNGR @INDEX_COLS);
13 use oEdtk::logger qw(logger);
14 use POSIX qw(strftime);
15 use DBI;
16  
17 # use Sys::Hostname;
18  
19 use Exporter;
20 our $VERSION = 2.1126; # release number : Y.YSSS -> Year, Sequence
21 our @ISA = qw(Exporter);
22 our @EXPORT_OK = qw(
23 omgr_check_acquit
24 omgr_check_doclibs
25 omgr_check_seqlot_ref
26 omgr_depot_poste
27 omgr_export
28 omgr_import
29 omgr_lot_pending
30 omgr_purge_fs
31 omgr_stats
32 omgr_stats_referent
33 omgr_track_folds
34 omgr_track_report
35 );
36  
37 # The default lot.
38 use constant DEFLOT => 'DEF';
39 use constant DEFFIL => 'DEF';
40  
41 # Description of the processings applied to our document batches, with
42 # the list of fields updated at each step.
43 #
44 # 1. Insert each index line into the $cfg->{'EDTK_DBI_OUTMNGR'} table, filling in
45 # a number of extra fields, using the information
46 # taken from the EDTK_REFIDDOC and EDTK_SUPPORTS tables.
47 # ED_PORTADR, ED_CATDOC, ED_REFIMP, ED_TYPED, ED_FORMATP, ED_PGORIEN,
48 # ED_FORMDEF, ED_PAGEDEF, ED_FORMS, ED_NUMPGPLI
49 #
50 # 2. Once all the lines have been inserted, we can now perform
51 # additional computations and enrich our entries again.
52 # ED_NBPGPLI, ED_NBPGDOC, ED_MODEDI
53 #
54 # 3. We can now select a batch for our documents. We try
55 # each batch in turn, in the priority order defined in the
56 # EDTK_LOTS table. If the batch matches entries, we assign those entries to the
57 # matching batch.
58 # ED_IDLOT
59 #
60 # 4. Once a batch has been assigned, we infer a manufacturer from the
61 # EDTK_LOTS table. Depending on that manufacturer, we select a list
62 # of possible production lines, in the priority order defined in the
63 # EDTK_FILIERES table. As in step 3, we try to match our entries
64 # against each of these lines, according to their constraints.
65 # ED_IDFILIERE
66 #
67 # 5. Once the production line has been determined, we know whether we will print
68 # double-sided or single-sided; we can therefore compute new
69 # additional fields.
70 # ED_PDSPLI, ED_NBFPLI
71 #
72 # 6. Finally we can export our entries to create our final batches to send
73 # to the manufacturer. To do so, we select the (idlot,idfiliere) pairs
74 # unique in our $cfg->{'EDTK_DBI_OUTMNGR'} table, and for each of these pairs, we try
75 # to satisfy the minimum and maximum folded-item/page count constraints. If
76 # possible, we assign a unique shipment batch number to the documents.
77 # ED_SEQLOT
78  
79 # READ AND PROCESS AN INDEX FILE, STORING IT IN THE DATABASE, WHILE COMPUTING SOME VALUES.
80 sub omgr_import {
81 my ( $app, $in, $corp ) = @_;
82  
83 # Retrieve the database connection parameters.
84 my $cfg = config_read('EDTK_DB');
85  
86 my $pdbh = db_connect( $cfg, 'EDTK_DBI_PARAM' );
87 my $dbh = db_connect( $cfg, 'EDTK_DBI_DSN', { AutoCommit => 0, RaiseError => 1 } );
88  
89 # Create the $cfg->{'EDTK_DBI_OUTMNGR'} table if we're using SQLite.
90 if ( $dbh->{'Driver'}->{'Name'} eq 'SQLite' ) {
91 create_table_OUTMNGR( $dbh, $cfg->{'EDTK_DBI_OUTMNGR'} );
92 }
93  
94 eval {
95 my ( $idldoc, $numencs, $encpds ) = _omgr_insert( $dbh, $pdbh, $app, $in, $corp );
96 _omgr_lot( $dbh, $pdbh, $idldoc );
97 _omgr_filiere( $dbh, $pdbh, $app, $idldoc, $numencs, $encpds );
98 $dbh->commit;
99 };
100 if ($@) {
101 &logger( 3, "ERROR: $@\n" );
102 eval { $dbh->rollback };
103 die "ERROR: rollback done before dying in omgr_import\n";
104 }
105  
106 $dbh->disconnect;
107 $pdbh->disconnect;
108 }
109  
110 sub omgr_track_folds {
111  
112 # EDIT LIST AND STATUS FROM START TO END
113 # LIST OF BATCHES PRODUCED UP TO MAILING
114 my $dbh = shift;
115 my $cfg = config_read( 'EDTK_DB', 'EDTK_STATS' );
116 my $nb_j_historique = shift || $cfg->{'EDTK_STATS_DAYS_FROM'} || 10;
117 &logger( 6, "INFO: omgr_track_folds for last $nb_j_historique days\n" );
118 my ($sql);
119  
120 # QUERY FOR THE BUSINESS-TRACKING MAIL
121 ###########################################################################
122 # SELECT A.ED_REFIDDOC, COUNT (DISTINCT A.ED_IDLDOC||TO_CHAR(A.ED_SEQDOC,'FM0000000')) AS NB_DOCS,
123 # A.ED_DTEDTION, COUNT (DISTINCT A.ED_SEQLOT||TO_CHAR(A.ED_IDPLI,'FM0000000')) AS NB_PLIS,
124 # B.ED_DTPOST, B.ED_DTPOST2, COUNT (DISTINCT A.ED_SEQLOT) AS NB_LOTS,
125 # NVL(B.ED_STATUS, NVL(A.ED_STATUS, 'PENDING...')) AS STATUS
126 # FROM EDTK_INDEX A, EDTK_ACQ B
127 # WHERE A.ED_SEQLOT=B.ED_SEQLOT (+)
128 # AND (A.ED_DTEDTION IS NULL OR A.ED_DTEDTION > TO_CHAR(SYSDATE-20, 'IYYYMMDD'))
129 # GROUP BY C.ED_MAIL_REFERENT, A.ED_REFIDDOC, A.ED_DTEDTION, B.ED_DTPOST, B.ED_DTPOST2, B.ED_STATUS, A.ED_STATUS
130 # ORDER BY C.ED_MAIL_REFERENT, A.ED_REFIDDOC;
131  
132 # SELECT A.ED_REFIDDOC, COUNT (DISTINCT A.ED_IDLDOC||TO_CHAR(A.ED_SEQDOC,'FM0000000')) AS NB_DOCS,
133 # A.ED_DTEDTION, COUNT (DISTINCT A.ED_SEQLOT||TO_CHAR(A.ED_IDPLI,'FM0000000')) AS NB_PLIS,
134 # B.ED_DTPOST, B.ED_DTPOST2, COUNT (DISTINCT A.ED_SEQLOT) AS NB_LOTS,
135 # NVL(B.ED_STATUS, NVL(A.ED_STATUS, 'PENDING...')) AS STATUS,
136 # C.ED_MAIL_REFERENT
137 # FROM EDTK_INDEX A, EDTK_ACQ B, EDTK_REFIDDOC C
138 # WHERE A.ED_SEQLOT=B.ED_SEQLOT (+)
139 # AND A.ED_REFIDDOC=C.ED_REFIDDOC
140 # AND (A.ED_DTEDTION IS NULL OR A.ED_DTEDTION > TO_CHAR(SYSDATE-20, 'IYYYMMDD'))
141 # GROUP BY C.ED_MAIL_REFERENT, A.ED_REFIDDOC, A.ED_DTEDTION, B.ED_DTPOST, B.ED_DTPOST2, B.ED_STATUS, A.ED_STATUS
142 # ORDER BY C.ED_MAIL_REFERENT, A.ED_REFIDDOC, A.ED_DTEDTION;
143  
144 $sql =
145 "SELECT A.ED_CORP, A.ED_REFIDDOC,"
146 . " NVL(B.ED_STATUS, NVL(A.ED_STATUS, 'PENDING...')) AS STATUS,"
147 . " COUNT (DISTINCT A.ED_IDLDOC||TO_CHAR(A.ED_SEQDOC,'FM0000000')) AS NB_DOCS,"
148 . " A.ED_DTEDTION, "
149 . " COUNT (DISTINCT A.ED_SEQLOT) AS NB_LOTS,"
150 . " COUNT (DISTINCT A.ED_SEQLOT||TO_CHAR(A.ED_IDPLI,'FM0000000')) AS NB_PLIS,"
151 . " B.ED_DTPOST, B.ED_DTPOST2, "
152 . " C.ED_MAIL_REFERENT AS REFERENT"
153 . " FROM "
154 . $cfg->{'EDTK_STATS_OUTMNGR'}
155 . " A, EDTK_ACQ B, EDTK_REFIDDOC C"
156 . " WHERE A.ED_SEQLOT=B.ED_SEQLOT (+)"
157 . " AND A.ED_REFIDDOC=C.ED_REFIDDOC"
158 . " AND (A.ED_DTEDTION IS NULL OR A.ED_DTEDTION > TO_CHAR(SYSDATE-?, 'IYYYMMDD'))"
159 . " GROUP BY C.ED_MAIL_REFERENT, A.ED_CORP, A.ED_REFIDDOC, A.ED_DTEDTION, B.ED_DTPOST, B.ED_DTPOST2, B.ED_STATUS, A.ED_STATUS"
160 . " ORDER BY C.ED_MAIL_REFERENT, A.ED_CORP, A.ED_REFIDDOC, STATUS, A.ED_DTEDTION";
161  
162 my $sth = $dbh->prepare($sql);
163 $sth->execute($nb_j_historique);
164  
165 my $rows = $sth->fetchall_arrayref();
166  
167 my $fmt = "%10s %-20s %-10s %7s %9s %7s %7s %8s %8s";
168 my @head = (
169 "CORP", "REFIDDOC", "STATUS", "NB_DOCS", "DTEDITION", "NB_LOTS",
170 "NB_PLIS", "DTPOST", "DTPOST2"
171 );
172 _filled_rows($rows);
173  
174 @$rows = ( \$fmt, \@head, @$rows );
175 return $rows;
176 }
177  
178 sub omgr_track_report {
179 my $dbh = shift;
180 my $cfg = config_read( 'EDTK_DB', 'EDTK_STATS' );
181  
182 my ($sql);
183  
184 #select A.ED_REFIDDOC,
185 # (CASE A.ED_MODEDI WHEN 'R' THEN 2 ELSE 1 END * SUM(A.ED_NBFPLI)) AS NB_FACES,
186 # COUNT (DISTINCT A.ED_SEQLOT||TO_CHAR(A.ED_IDPLI,'FM0000000')) AS NB_PLIS_SENT,
187 # B.ED_STATUS, B.ED_LOTNAME, A.ED_SEQLOT, C.ED_IDMANUFACT,
188 # B.ED_NBFACES AS NB_FACES_MANUFACT, B.ED_NBPLIS AS NB_PLIS_MANUFACT, B.ED_DTPOST
189 # FROM EDTK_INDEX A, EDTK_ACQ B, EDTK_LOTS C
190 # WHERE A.ED_SEQLOT = B.ED_SEQLOT AND B.ED_STATUS != 'SENT' AND A.ED_IDLOT = C.ED_IDLOT (+)
191 # GROUP BY C.ED_IDMANUFACT, A.ED_REFIDDOC, A.ED_SEQLOT, A.ED_MODEDI, B.ED_STATUS, B.ED_DTPOST, B.ED_LOTNAME, B.ED_NBFACES, B.ED_NBPLIS;
192 $sql =
193 "SELECT A.ED_REFIDDOC, "
194 . " (CASE A.ED_MODEDI WHEN 'R' THEN 2 ELSE 1 END * SUM(A.ED_NBFPLI)) AS NB_FACES, "
195 . " COUNT (DISTINCT A.ED_SEQLOT||TO_CHAR(A.ED_IDPLI,'FM0000000')) AS NB_PLIS, "
196 . " B.ED_STATUS, B.ED_LOTNAME, A.ED_SEQLOT, C.ED_IDMANUFACT, "
197 . " B.ED_NBFACES AS NB_FACES_MANUFACT, B.ED_NBPLIS AS NB_PLIS_MANUFACT, B.ED_DTPOST "
198 . "FROM "
199 . $cfg->{'EDTK_STATS_OUTMNGR'}
200 . " A, EDTK_ACQ B, EDTK_LOTS C "
201 . "WHERE A.ED_SEQLOT = B.ED_SEQLOT AND B.ED_STATUS != 'SENT' AND A.ED_IDLOT = C.ED_IDLOT (+) "
202 . "GROUP BY C.ED_IDMANUFACT, A.ED_REFIDDOC, A.ED_SEQLOT, A.ED_MODEDI, B.ED_STATUS, B.ED_DTPOST, B.ED_LOTNAME, B.ED_NBFACES, B.ED_NBPLIS ";
203  
204 my $sth = $dbh->prepare($sql);
205 $sth->execute();
206  
207 my $rows = $sth->fetchall_arrayref();
208  
209 my $fmt = "%15s %6s %6s %7s %16s %7s %16s %14s %14s %8s ";
210 my @head = (
211 "REFIDDOC", "FACES", "PLIS", "STATUS",
212 "LOTNAME", "SEQLOT", "MANUFACTURER", "MANUFACT_FACES",
213 "MANUFACT_PLIS", "DTPOST"
214 );
215 _filled_rows($rows);
216  
217 # return @tlist;
218 @$rows = ( \$fmt, \@head, @$rows );
219 return $rows;
220 }
221  
222 sub omgr_track_no_omgr() {
223  
224 # select B.ed_refiddoc, count (DISTINCT A.ED_SOURCE) as NBREQUEST, A.ED_message
225 # from edtk_tracking A, edtk_refiddoc B, edtk_index C
226 # where B.ed_refiddoc = A.ed_app
227 # AND A.ED_JOB_EVT = 'J'
228 # and B.ed_massmail = 'C'
229 # and A.ED_SNGL_ID = C.ED_IDLDOC (+)
230 # and C.ED_dtedtion is null
231 # and (A.ed_sngl_id like '202%')
232 # group by B.ed_refiddoc, A.ED_message
233 # order by B.ed_refiddoc, A.ED_message
234 # ;
235  
236 1;
237 }
238  
239 sub omgr_check_acquit {
240 my $dbh = shift;
241 my $cfg = config_read( 'EDTK_DB', 'EDTK_STATS' );
242 my $nb_j_historique = shift || $cfg->{'EDTK_STATS_DAYS_FROM'} || 100;
243  
244 # from the acknowledgment database, check:
245 # 1 - check the number of pages per seqlot
246 # 2 - check the number of folded items per seqlot
247 # 3 - fill in the status in acq
248 # 4 - fill in the check date
249  
250 #SELECT A.ED_SEQLOT,
251 # COUNT (DISTINCT A.ED_SEQLOT||TO_CHAR(A.ED_IDPLI,'FM0000000')) AS NB_PLIS, B.ED_NBPLIS,
252 # FROM EDTK_INDEX A, EDTK_ACQ B
253 # WHERE A.ED_SEQLOT=B.ED_SEQLOT
254 # AND ((B.ED_DTCHECK IS NULL OR B.ED_DTPRINT > TO_CHAR(SYSDATE-20, 'IYYYMMDD')) OR (B.ED_STATUS IS NULL OR B.ED_STATUS != 'SENT'))
255 # GROUP BY A.ED_SEQLOT, A.ED_MODEDI, B.ED_NBPLIS;
256 my ( $sql, $num );
257 $sql = "SELECT A.ED_SEQLOT, "
258 . " COUNT (DISTINCT A.ED_SEQLOT||TO_CHAR(A.ED_IDPLI,'FM0000000')) AS NB_PLIS, B.ED_NBPLIS"
259  
260 # see $sqlnbfpli
261 # . ", (CASE A.ED_MODEDI WHEN 'R' THEN 2 ELSE 1 END * SUM(A.ED_NBFPLI)) AS NB_FACES, B.ED_NBFACES"
262 . " FROM "
263 . $cfg->{'EDTK_STATS_OUTMNGR'}
264 . " A, EDTK_ACQ B"
265 . " WHERE A.ED_SEQLOT=B.ED_SEQLOT"
266 . " AND ((B.ED_DTCHECK IS NULL OR B.ED_DTPRINT > TO_CHAR(SYSDATE-?, 'IYYYMMDD')) OR (B.ED_STATUS IS NULL OR B.ED_STATUS != 'SENT'))"
267 . " GROUP BY A.ED_SEQLOT, A.ED_MODEDI, B.ED_NBPLIS";
268 my $sth = $dbh->prepare($sql);
269 $sth->execute($nb_j_historique);
270  
271 while ( my $seqlot = $sth->fetchrow_hashref() ) {
272  
273 # # WE UPDATE EACH SEQLOT
274 $sql =
275 "UPDATE EDTK_ACQ "
276 . " SET ED_DTCHECK = TO_CHAR(SYSDATE, 'IYYYMMDD'), ED_STATUS = "
277 . " CASE "
278 . " WHEN ED_NBPLIS = ? THEN "
279 . " CASE WHEN (ED_DTPOST IS NOT NULL) THEN 'SENT' "
280 . " ELSE 'GOOD' "
281 . " END "
282 . " ELSE 'LACK' " . " END "
283 . " WHERE ED_SEQLOT = ? ";
284 $num += $dbh->do( $sql, undef, $seqlot->{'NB_PLIS'}, $seqlot->{'ED_SEQLOT'} );
285 }
286 return $num;
287 }
288  
289 sub _omgr_insert {
290  
291 # - INJECT THE COMPO INDEX PAGE/PAGE DATA INTO THE DATABASE
292 # - COMPLETE THE INDEX WITH THE INFO FROM THE REFIDDOC AND SUPPORTS SETUP TABLES
293 # - COMPUTE THE PAGE/SUPPORT QUANTITIES
294 # TODO REVIEW THE INSERT HANDLING XXXXXXXXXX
295 my ( $dbh, $pdbh, $app, $in, $corp ) = @_;
296 my $cfg = config_read('EDTK_DB');
297  
298 ################################################################################
299 # TO MANAGE THE INDEX DYNAMICALLY, THE READ OPERATIONS BELOW SHOULD
300 # either be part of the index read loop, or be replaced by links
301 ################################################################################
302 #
303 # Retrieve the document application parameters.
304 my $doc = $pdbh->selectrow_hashref(
305 "SELECT * FROM EDTK_REFIDDOC WHERE ED_REFIDDOC = ? " . "AND (ED_CORP = ? OR ED_CORP = '%')",
306 undef, $app, $corp
307 );
308 die( "ERROR: die in _omgr_insert, message is " . $pdbh->errstr . "\n" ) if $pdbh->err;
309 if ( !defined($doc) ) {
310 die "ERROR: Could not find document \"$app\" in EDTK_REFIDDOC\n";
311 }
312  
313 # Retrieve the support for the first page and the following ones.
314 my $p1 = $pdbh->selectrow_hashref( 'SELECT * FROM EDTK_SUPPORTS WHERE ED_REFIMP = ?',
315 undef, $doc->{'ED_REFIMP_P1'} );
316 die( "ERROR: die in _omgr_insert, message is " . $pdbh->errstr . "\n" ) if $pdbh->err;
317 if ( !defined($p1) ) {
318 die "ERROR: Could not find support \"$doc->{'ED_REFIMP_P1'}\" in EDTK_SUPPORTS\n";
319 }
320  
321 my $ps = $pdbh->selectrow_hashref( 'SELECT * FROM EDTK_SUPPORTS WHERE ED_REFIMP = ?',
322 undef, $doc->{'ED_REFIMP_PS'} );
323 die( "ERROR: die in _omgr_insert, message is " . $pdbh->errstr . "\n" ) if $pdbh->err;
324 if ( !defined($ps) ) {
325 die "ERROR: Could not find support \"$doc->{'ED_REFIMP_PS'}\" in EDTK_SUPPORTS\n";
326 }
327  
328 # Retrieve the list of inserts to join for this document,
329 # and deduce the extra weight to add to each folded item
330 my @encrefs = split( /,/, $doc->{'ED_REFIMP_REFIDDOC'} || "" );
331 my $now = strftime( "%Y%m%d", localtime() );
332 my $sth = $pdbh->prepare('SELECT * FROM EDTK_SUPPORTS WHERE ED_REFIMP = ?')
333 or die( "ERROR: die in _omgr_insert, message is " . $pdbh->errstr );
334 my $encpds = 0;
335 my @needed = ();
336  
337 foreach my $encref (@encrefs) {
338  
339 # THE ERROR IS HERE: WE SHOULD ADD INDEX LINES PER INSERT WITH TYPIMP = E duplicated for each insert starting from the last line of the document xxxxxx
340 my $enc = $pdbh->selectrow_hashref( $sth, undef, $encref )
341 or die( "ERROR: in omgr for encref $encref " . $pdbh->errstr . "\n" );
342  
343 #&logger(7, "DEBUG: looking for encart ".$enc->{'ED_REFIMP'}." for $now\n");
344 if ( defined( $enc->{'ED_DEBVALID'} )
345 && length( $enc->{'ED_DEBVALID'} ) > 0
346 && $enc->{'ED_DEBVALID'} ne '99999999' )
347 {
348 next if $now < $enc->{'ED_DEBVALID'};
349 }
350 if ( defined( $enc->{'ED_FINVALID'} ) && length( $enc->{'ED_FINVALID'} ) > 0 ) {
351 next if $now > $enc->{'ED_FINVALID'};
352 }
353 $encpds += $enc->{'ED_POIDSUNIT'};
354 push( @needed, $encref );
355 }
356 my $listerefenc = join( ', ', @needed )
357 || "none"
358 ; # xxx TODO think about the mailing impact, hard-coded or configurable in the supports table ?
359 #&logger(7, "DEBUG: selected listerefenc => $listerefenc\n");
360  
361 # TO MANAGE THE INDEX DYNAMICALLY, THE READ OPERATIONS ABOVE SHOULD
362 # either be part of the index read loop, or be replaced by links
363 ################################################################################
364  
365 # LOOP THROUGH THE INDEX FILE, GATHERING ENTRIES AND COUNTING THE NUMBER OF PAGES, ETC...
366 my $numpgpli = 0;
367 my $seqpgdoc = 0;
368 my $idldoc = undef;
369 open( my $fh, '<', $in ) or die "ERROR: Cannot open index file \"$in\": $!\n";
370 my $prevseq = -1;
371 my $count = 0;
372  
373 my $csv = Text::CSV->new( { binary => 1, sep_char => ';' } );
374 while (<$fh>) {
375  
376 # Parse the CSV data and extract all the fields.
377  
378 $csv->parse($_);
379 my @data = $csv->fields();
380  
381 # Truncate the CP field if necessary.
382 # If the postal code is longer than 10 characters, it is truncated to 10 by keeping the first 4 followed by the last 6
383 if ( length( $data[4] ) > 10 ) {
384 &logger( 4, "INFO: \"$data[4]\" truncated to 10 characters\n" );
385 $data[4] = substr( $data[4], 0, 4 ) . substr( $data[4], -6 );
386 }
387  
388 # Truncate the name of city field if necessary.
389 if ( length( $data[5] ) > 30 ) {
390 &logger( 4, "INFO: \"$data[5]\" truncated to 30 characters\n" );
391 $data[5] =~ s/^(.{30}).*$/$1/;
392 }
393  
394 # Truncate the name field if necessary.
395 if ( length( $data[7] ) > 38 ) {
396 &logger( 4, "INFO: \"$data[7]\" truncated to 38 characters\n" );
397 $data[7] =~ s/^(.{38}).*$/$1/;
398 }
399  
400 my $first = $prevseq != $data[3]; # Is this the first page?
401 $idldoc = $data[1] unless defined $idldoc;
402  
403 # XXX These two values are identical for now because we have only one document
404 # per folded item, but this will not hold once batching is implemented.
405 if ($first) {
406 $numpgpli = 1;
407 $seqpgdoc = 1;
408 }
409 else {
410 $numpgpli++;
411 $seqpgdoc++;
412 }
413  
414 # ECM columns (D-S52) come from the index-format header, not from the fork:
415 # the fork read ED_CLEGED5/ED_IDPMSIR from the wrong fields (it put ED_IDLOT
416 # into ED_IDPMSIR). ed_idjob is NOT NULL in both key modes
417 # (EDTK_DB_PK_IDJOB), so its value always comes from the ini.
418 my $entry = {
419 ED_REFIDDOC => $data[0],
420 ED_IDLDOC => $idldoc,
421 ED_IDSEQPG => $data[2],
422 ED_SEQDOC => $data[3],
423 ED_CPDEST => $data[4],
424 ED_VILLDEST => $data[5],
425 ED_IDDEST => $data[6],
426 ED_NOMDEST => $data[7],
427 ED_IDEMET => $data[8],
428 ED_DTEDTION => $data[9],
429 ED_TYPPROD => $data[10],
430 ED_PORTADR => $doc->{'ED_PORTADR'}, # check whether we can handle it like ED_TYPPROD
431 ED_ADRLN1 => $data[12],
432 ED_CLEGED1 => $data[13],
433 ED_ADRLN2 => $data[14],
434 ED_CLEGED2 => $data[15],
435 ED_ADRLN3 => $data[16],
436 ED_CLEGED3 => $data[17],
437 ED_ADRLN4 => $data[18],
438 ED_CLEGED4 => $data[19],
439 ED_ADRLN5 => $data[20],
440 ED_CORP => $data[21],
441 ED_DOCLIB => $data[22],
442 ED_REFIMP => $data[23],
443 ED_ADRLN6 => $data[24],
444 ED_SOURCE => $data[25],
445 ED_OWNER => $data[26],
446 ED_HOST => $data[27],
447 ED_IDIDX => $data[28],
448 ED_CATDOC => $data[29] || $doc->{'ED_CATDOC'},
449 ED_CODRUPT => $data[30],
450 ED_IDJOB => ( $cfg->{'EDTK_DB_IDJOB_DEFAULT'} // '' ),
451 ED_TYPDOC => $data[31],
452 ED_IDCOLL => $data[32],
453 ED_IDMNT => $data[33],
454 ED_IDPMSIR => $data[34],
455 ED_CLEGED5 => $data[44],
456 ED_SEQPGDOC => $seqpgdoc,
457 ED_POIDSUNIT => $first ? $p1->{'ED_POIDSUNIT'} : $ps->{'ED_POIDSUNIT'},
458 ED_NBENC => scalar @needed, # this is a hack incompatible with folded-item batching
459 ED_ENCPDS => $encpds, # this is a hack incompatible with folded-item batching
460 ED_BAC_INSERT => $first ? $p1->{'ED_BAC_INSERT'} : $ps->{'ED_BAC_INSERT'},
461 ED_TYPED => $doc->{'ED_TYPED'},
462 ED_MODEDI => $doc->{'ED_MODEDI'},
463 ED_FORMATP => $doc->{'ED_FORMATP'},
464 ED_PGORIEN => $doc->{'ED_PGORIEN'},
465  
466 # ED_FORMDEF => $doc->{'ED_FORMDEF'},
467 # ED_PAGEDEF => $doc->{'ED_PAGEDEF'},
468 # ED_FORMS => $doc->{'ED_FORMS'},
469 #ED_IDPLI =>
470 ED_NBDOCPLI => 1, # XXX Will differ from 1 once we do batching
471 ED_NUMPGPLI => $numpgpli,
472 ED_LISTEREFENC => $listerefenc,
473 ED_TYPOBJ => 'I' # XXX We are missing data for this field
474 };
475  
476 # We only fill the pre-printed field if it is not set in the index.
477 if ( length( $entry->{'ED_REFIMP'} ) == 0 ) {
478 $entry->{'ED_REFIMP'} = $first ? $doc->{'ED_REFIMP_P1'} : $doc->{'ED_REFIMP_PS'};
479 }
480  
481 my @cols = keys(%$entry);
482 my $sql =
483 "INSERT INTO "
484 . $cfg->{'EDTK_DBI_OUTMNGR'} . " ("
485 . join( ',', @cols )
486 . ") VALUES ("
487 . join( ',', ('?') x @cols ) . ")";
488 my $sth = $dbh->prepare_cached($sql);
489  
490 # &logger(7, "INFO: insert Query = $sql\n");
491 # &logger(7, "INFO: insert values = ". dump (%$entry) . "\n"); # bug inserting some values into Postgres
492  
493 eval { $sth->execute( values(%$entry) ); };
494 if ($@) {
495 &logger( 3, "ERROR: $@\n" );
496 eval { $dbh->rollback };
497 die "ERROR: rollback done before dying in omgr_insert\n";
498 }
499  
500 $prevseq = $entry->{'ED_SEQDOC'};
501 $count++;
502 }
503 close($fh);
504  
505 # Update ED_NBPGDOC.
506 my $sql =
507 'UPDATE '
508 . $cfg->{'EDTK_DBI_OUTMNGR'}
509 . ' i SET ED_NBPGDOC = '
510 . '(SELECT COUNT(*) FROM '
511 . $cfg->{'EDTK_DBI_OUTMNGR'}
512 . ' WHERE ED_IDLDOC = ? AND ED_SEQDOC = i.ED_SEQDOC) WHERE ED_IDLDOC = ?';
513 $dbh->do( $sql, undef, $idldoc, $idldoc );
514  
515 # Initialize ED_NBPGPLI to ED_NBPGDOC; will differ if we do batching.
516 $sql =
517 'UPDATE '
518 . $cfg->{'EDTK_DBI_OUTMNGR'}
519 . ' i SET ED_NBPGPLI = ED_NBPGDOC '
520 . 'WHERE ED_IDLDOC = ?';
521 $dbh->do( $sql, undef, $idldoc );
522  
523 # Now that ED_NBPGPLI is computed we can update ED_MODEDI.
524 $sql =
525 "UPDATE "
526 . $cfg->{'EDTK_DBI_OUTMNGR'} . " SET "
527 . "ED_MODEDI = "
528 . "CASE ED_MODEDI WHEN 'S' THEN 'R' ELSE CASE ED_NBPGPLI WHEN 1 THEN 'R' ELSE 'V' END END "
529 . "WHERE ED_IDLDOC = ?";
530 $dbh->do( $sql, undef, $idldoc );
531 &logger( 6, "INFO: Imported $count pages\n" );
532 return ( $idldoc, scalar @needed, $encpds );
533 }
534  
535 sub _omgr_lot {
536  
537 # MATCHING INDEX DOCUMENTS AGAINST THE BATCH TABLE => BATCH ASSIGNMENT
538 my ( $dbh, $pdbh, $idldoc ) = @_;
539 my $cfg = config_read('EDTK_DB');
540  
541 # Select the appropriate batches.
542 my $sql =
543 'SELECT ED_IDLOT, ED_REFIDDOC, ED_CPDEST, ED_FILTER, ED_GROUPBY, ED_IDMANUFACT, ED_IDGPLOT '
544 . 'FROM EDTK_LOTS ORDER BY ED_PRIORITE';
545 my $sth = $pdbh->prepare($sql);
546 $sth->execute();
547 while ( my $lot = $sth->fetchrow_hashref() ) {
548  
549 # We try to match documents with this batch.
550 $sql = 'UPDATE ' . $cfg->{'EDTK_DBI_OUTMNGR'} . ' SET ED_IDLOT = ? ';
551  
552 #XXX ADD REFENC / BATCH HANDLING: ADD ED_REFENC TO ED_LISTREFENC
553 # if (defined $lot->{'ED_REFENC'}) {
554 # add ED_REFENC to ED_LISTREFENC
555 # }
556  
557 my $where = ' WHERE ED_IDLOT IS NULL AND ED_IDLDOC = ? ';
558 if ( $lot->{'ED_REFIDDOC'} =~ /\%/ ) {
559 $where .= " AND ED_REFIDDOC LIKE ? ";
560 }
561 else {
562 $where .= " AND ED_REFIDDOC = ? ";
563 }
564 my @values = ( $lot->{'ED_IDLOT'}, $idldoc, $lot->{'ED_REFIDDOC'} );
565  
566 if ( defined $lot->{'ED_CPDEST'} ) {
567 $where .= " AND ED_CPDEST LIKE ? ";
568 push( @values, $lot->{'ED_CPDEST'} );
569 }
570 if ( defined $lot->{'ED_FILTER'} and $lot->{'ED_FILTER'} =~ /\=/ ) {
571 $where .= " AND " . $lot->{'ED_FILTER'};
572 }
573  
574 my $num = $dbh->do( $sql . $where, undef, @values );
575  
576 if ( $num > 0 ) {
577 &logger( 6, "INFO: Assigned $num pages to lot \"$lot->{'ED_IDLOT'}\"\n" );
578 }
579 }
580  
581 # Assign the remaining entries to the default batch.
582 my $num = $dbh->do(
583 "UPDATE "
584 . $cfg->{'EDTK_DBI_OUTMNGR'}
585 . " SET ED_IDLOT = ? "
586 . "WHERE ED_IDLDOC = ? AND ED_IDLOT IS NULL",
587 undef, DEFLOT, $idldoc
588 );
589 if ( $num > 0 ) {
590 &logger( 6, "INFO: Assigned $num remaining pages to default lot \"" . DEFLOT . "\"\n" );
591 }
592 }
593  
594 sub _get_next_filiere {
595 my ( $pdbh, $filiere ) = @_;
596  
597 # Retrieve the assignment parameters of the production line.
598 my ( $ed_priorite, $ed_idmanufact, $ed_typed, $ed_modedi, $ed_idgplot, $ed_nbbacprn ) =
599 $pdbh->selectrow_array(
600 'select ED_PRIORITE, ED_IDMANUFACT, ED_TYPED, ED_MODEDI, ED_IDGPLOT, ED_NBBACPRN from EDTK_FILIERES where ED_IDFILIERE =? ',
601 undef, $filiere
602 ) or die( "ERROR: in _get_next_filiere, message is " . $pdbh->errstr );
603  
604 # Retrieve the first element of the ordered list of production lines.
605 my $next_filiere = $pdbh->selectrow_array(
606 'select ED_IDFILIERE from EDTK_FILIERES where ED_IDMANUFACT =? and ED_TYPED =? and ED_MODEDI =? and ED_NBBACPRN >=? and ED_ACTIF =? and ED_IDFILIERE !=? and ED_PRIORITE >? and (ED_IDGPLOT = ? or ED_IDGPLOT = ?) order by ED_PRIORITE',
607 undef,
608 $ed_idmanufact,
609 $ed_typed,
610 $ed_modedi,
611 $ed_nbbacprn,
612 'O',
613 $filiere,
614 $ed_priorite,
615 $ed_idgplot,
616 '%'
617 );
618  
619 $next_filiere ||= DEFFIL;
620  
621 #&logger(7, "DEBUG: next_filiere is $next_filiere\n");
622 return $next_filiere;
623 }
624  
625 sub _omgr_filiere {
626 my ( $dbh, $pdbh, $app, $idldoc, $numencs, $encpds ) = @_;
627 my $cfg = config_read('EDTK_DB');
628  
629 # Retrieve the document application parameters.
630 my $doc =
631 $pdbh->selectrow_hashref( 'SELECT * FROM EDTK_REFIDDOC WHERE ED_REFIDDOC = ?', undef, $app )
632 or die( "ERROR: die in _omgr_filiere, message is " . $pdbh->errstr );
633  
634 # # Retrieve the list of inserts to join to this document,
635 # # and deduce the extra weight to add to each folded item.
636 # my @encarts = split(/,/, $doc->{'ED_REFIMP_REFIDDOC'});
637 # my $encpds = 0;
638 # my $sth = $pdbh->prepare('SELECT ED_POIDSUNIT FROM EDTK_SUPPORTS '
639 # . 'WHERE ED_REFIMP = ?')
640 # or die "ERROR: select on supports failed " . $pdbh->errstr;
641 # foreach my $encart (@encarts) {
642 # my $pref = $pdbh->selectrow_arrayref($sth, undef, $encart)
643 # or die "ERROR: on support weight " . $pdbh->errstr;
644 # $encpds += $pref->[0];
645 # }
646  
647 # Retrieve the support for the first page and the following ones.
648 my $p1 = $pdbh->selectrow_hashref( 'SELECT * FROM EDTK_SUPPORTS WHERE ED_REFIMP = ?',
649 undef, $doc->{'ED_REFIMP_P1'} )
650 or die( "ERROR: die in _omgr_filiere, message is " . $pdbh->errstr );
651 my $ps = $pdbh->selectrow_hashref( 'SELECT * FROM EDTK_SUPPORTS WHERE ED_REFIMP = ?',
652 undef, $doc->{'ED_REFIMP_PS'} )
653 or die( "ERROR: die in _omgr_filiere, message is " . $pdbh->errstr );
654  
655 # Look for all entries that have an assigned batch
656 # but no production line yet, see EDTK LOTS
657 my $sql =
658 'SELECT DISTINCT ED_IDLOT FROM '
659 . $cfg->{'EDTK_DBI_OUTMNGR'}
660 . ' WHERE ED_IDLDOC = ? AND ED_IDLOT IS NOT NULL AND ED_IDFILIERE IS NULL';
661 my $lotids = $dbh->selectcol_arrayref( $sql, undef, $idldoc );
662  
663 foreach my $lotid (@$lotids) {
664 my $lot =
665 $pdbh->selectrow_hashref( 'SELECT * FROM EDTK_LOTS WHERE ED_IDLOT = ?', undef, $lotid )
666 or die( "ERROR: die in _omgr_filiere, message is " . $pdbh->errstr );
667  
668 # Now we try to match the documents with each of the production lines.
669 my $sql =
670 "SELECT * FROM EDTK_FILIERES WHERE ED_ACTIF = 'O' "
671 . "AND (ED_IDMANUFACT IS NULL OR ED_IDMANUFACT = '' OR ED_IDMANUFACT = ?) "
672 . "ORDER BY ED_PRIORITE ASC";
673 my $sth = $pdbh->prepare($sql)
674 or die( "ERROR: die in _omgr_filiere, message is " . $pdbh->errstr );
675 $sth->execute( $lot->{'ED_IDMANUFACT'} );
676  
677 # THE MINIMUM/MAXIMUM PAGE AND FOLDED-ITEM COUNT CONSTRAINTS ARE CHECKED
678 # ONLY WHEN EXPORTING THE BATCHES IN OMGR_EXPORT() TO ALLOW
679 # BATCHING.
680 while ( my $fil = $sth->fetchrow_hashref() ) {
681  
682 # backward compatibility
683 if ( defined $fil->{'ED_IDGPLOT'} && length( $fil->{'ED_IDGPLOT'} ) > 0 ) {
684 if ( $lot->{'ED_IDGPLOT'} ne $fil->{'ED_IDGPLOT'} and $fil->{'ED_IDGPLOT'} ne "%" )
685 {
686 next;
687 }
688 }
689  
690 if ( defined $fil->{'ED_NBENCMAX'} && length( $fil->{'ED_NBENCMAX'} ) > 0 ) {
691 next if $numencs > $fil->{'ED_NBENCMAX'};
692 }
693  
694 # The formula that lets us compute the number of sheets in a folded item.
695 # to be evolved for batching xxxxx
696 my $sqlnbfpli = "$numencs + "
697 . ( $fil->{'ED_MODEDI'} eq 'V' ? 'CEIL(ED_NBPGPLI / 2)' : 'ED_NBPGPLI' );
698  
699 # The formula computing the total folded-item weight, and the associated values.
700 # xxxx the formula is wrong because $sqlnbfpli already counts the inserts
701 # xxxx we should sum the weights of the front-side objects of the folded item (provided we really have 1 line / element)
702 my $sqlpdspli =
703 "$encpds + $p1->{'ED_POIDSUNIT'} + $ps->{'ED_POIDSUNIT'} * ($sqlnbfpli - 1)";
704  
705 my $sql =
706 "UPDATE "
707 . $cfg->{'EDTK_DBI_OUTMNGR'}
708 . " SET ED_IDFILIERE = ?, "
709 . "ED_FORMFLUX = ?, ED_NBFPLI = $sqlnbfpli, ED_PDSPLI = $sqlpdspli "
710 . "WHERE ED_IDLDOC = ? AND ED_IDLOT = ? AND ED_IDFILIERE IS NULL "
711 . "AND ED_MODEDI LIKE ? AND ED_TYPED LIKE ? ";
712 my @vals = (
713 $fil->{'ED_IDFILIERE'},
714 $fil->{'ED_FORMFLUX'}, $idldoc, $lotid, $fil->{'ED_MODEDI'}, $fil->{'ED_TYPED'}
715 );
716 if ( defined $fil->{'ED_POIDS_PLI'} && length( $fil->{'ED_POIDS_PLI'} ) > 0 ) {
717 $sql .= " AND $sqlpdspli <= ?";
718 push( @vals, $fil->{'ED_POIDS_PLI'} );
719 }
720 if ( defined $fil->{'ED_FEUILPLI'} && length( $fil->{'ED_FEUILPLI'} ) > 0 ) {
721 $sql .= " AND $sqlnbfpli <= ?";
722 push( @vals, $fil->{'ED_FEUILPLI'} );
723 }
724 my $num = $dbh->do( $sql, undef, @vals );
725 if ( $num > 0 ) {
726 &logger( 6,
727 "INFO: Assigned $num pages to production line \"$fil->{'ED_IDFILIERE'}\" "
728 . "($fil->{'ED_DESIGNATION'})\n" );
729 }
730 }
731 }
732 }
733  
734 sub omgr_export {
735 my (%conds) = @_;
736  
737 my $cfg = config_read('EDTK_DB');
738 my $dbh = db_connect( $cfg, 'EDTK_DBI_DSN', { AutoCommit => 0, RaiseError => 1 } );
739 omgr_check_doclibs($dbh);
740  
741 my $pdbh = db_connect( $cfg, 'EDTK_DBI_PARAM' );
742  
743 # _omgr_filiere2($dbh, $pdbh, $app, $idldoc, $numencs, $encpds);
744  
745 my $basedir = $cfg->{'EDTK_DIR_OUTMNGR'};
746  
747 my @done = ();
748 eval {
749 # Turn the optional user filters into a WHERE clause.
750 my $user_where = join( ' AND ', map { "$_ = ?" } keys(%conds) );
751  
752 # This query selects the (idlot,idfiliere) pairs containing unassigned folded items.
753 my $idsql =
754 'SELECT DISTINCT ED_IDLOT, ED_IDFILIERE, ED_CORP FROM '
755 . $cfg->{'EDTK_DBI_OUTMNGR'}
756 . ' WHERE ED_IDLOT IS NOT NULL AND ED_IDFILIERE IS NOT NULL AND ED_SEQLOT IS NULL';
757 if ( length($user_where) > 0 ) {
758 $idsql .= " AND $user_where";
759 }
760 my $ids = $dbh->selectall_arrayref( $idsql, undef, values(%conds) );
761  
762 foreach (@$ids) { # we must take the production-line priority order into account
763 my ( $idlot, $idfiliere, $idcorp ) = @$_;
764  
765 CHECK_FIL:
766 {
767 &logger( 6, "INFO: Considering OMGR tuple : $idlot, $idfiliere, $idcorp\n" );
768  
769 # The WHERE clause that we reuse in most queries so as to
770 # process only the entries we care about.
771 my $where =
772 'WHERE ED_IDLOT = ? AND ED_IDFILIERE = ? AND ED_CORP = ? AND ED_SEQLOT IS NULL';
773 if ( length($user_where) > 0 ) {
774 $where .= " AND $user_where";
775 }
776 my @wvals = ( $idlot, $idfiliere, $idcorp, values(%conds) );
777  
778 my $fil =
779 $pdbh->selectrow_hashref( 'SELECT * FROM EDTK_FILIERES WHERE ED_IDFILIERE = ?',
780 undef, $idfiliere );
781 my $lot = $pdbh->selectrow_hashref( 'SELECT * FROM EDTK_LOTS WHERE ED_IDLOT = ?',
782 undef, $idlot );
783  
784 # Lock the $cfg->{'EDTK_DBI_OUTMNGR'} table to make sure entries are not
785 # added between when we do our computations and when we run the UPDATE.
786 $dbh->do(
787 'LOCK TABLE ' . $cfg->{'EDTK_DBI_OUTMNGR'} . ' IN SHARE ROW EXCLUSIVE MODE' );
788  
789 # If the batch defines a column for the ED_GROUPBY value, we must split
790 # the shipment batches according to that column. Moreover, we always split
791 # by issuing entity, paper format, production type and insert list.
792 my @gcols = ( 'ED_CORP', 'ED_FORMATP', 'ED_TYPPROD', 'ED_LISTEREFENC' );
793  
794 if ( defined( $lot->{'ED_GROUPBY'} ) && length( $lot->{'ED_GROUPBY'} ) > 0 ) {
795 push( @gcols, split( /,/, $lot->{'ED_GROUPBY'} ) );
796 }
797 my $groups = $dbh->selectall_arrayref(
798 "SELECT DISTINCT "
799 . join( ', ', @gcols )
800 . " FROM "
801 . $cfg->{'EDTK_DBI_OUTMNGR'}
802 . " $where",
803 { Slice => {} },
804 @wvals
805 );
806  
807 foreach my $gvals (@$groups) {
808 my $where2 = $where; # check that we really use it ...
809 my @wvals2 = @wvals;
810  
811 if ( keys(%$gvals) > 0 ) {
812  
813 # check if every value is defined and could be used (ED_LISTEREFENC could be defined or not)
814 ## which can produce this message : Issuing rollback() for database handle being DESTROY'd without explicit disconnect()
815 foreach my $key ( keys(%$gvals) ) {
816 if ( defined $$gvals{$key} ) { }
817 else { delete $$gvals{$key} }
818 }
819  
820 push( @wvals2, values(%$gvals) );
821 $where2 .= ' AND ' . join( ' AND ', map { "$_ = ?" } keys(%$gvals) );
822 }
823  
824 # Compute the number of folded items of each size.
825 my $innersql = 'SELECT DISTINCT ED_IDLDOC, ED_SEQDOC, ED_NBPGPLI FROM '
826 . $cfg->{'EDTK_DBI_OUTMNGR'};
827  
828 my $sql = "SELECT COUNT(*), i.ED_NBPGPLI FROM ($innersql $where2) i "
829 . "GROUP BY i.ED_NBPGPLI ORDER BY i.ED_NBPGPLI DESC";
830 my $res = $dbh->selectall_arrayref( $sql, undef, @wvals2 );
831 next if @$res == 0;
832  
833 # Compute the total number of folded items and pages available to us.
834 my $availplis = sum( map { $$_[0] } @$res );
835 my $availpgs = sum( map { $$_[0] * $$_[1] } @$res );
836  
837 # Will we need to run the processing again for this (idlot/idfiliere) pair
838 # and for the group defined by the @gcols columns?
839 my $more = 0;
840  
841 # The maximum number of folded items/pages we can take (either the
842 # production-line limit, or everything available).
843 if ( defined( $fil->{'ED_MAXPLIS'} ) && $availplis > $fil->{'ED_MAXPLIS'} ) {
844 $availplis = $fil->{'ED_MAXPLIS'};
845 $more = 1;
846 }
847  
848 if ( defined( $fil->{'ED_MAXFEUIL_L'} ) ) {
849 my $maxpgs = $fil->{'ED_MAXFEUIL_L'};
850 if ( $fil->{'ED_MODEDI'} eq 'V' ) {
851 $maxpgs *= 2;
852 }
853 if ( $availpgs > $maxpgs ) {
854 $availpgs = $maxpgs;
855 $more = 1;
856 }
857 }
858  
859 my @plis = ();
860 my $selplis = 0;
861 my $selpgs = 0;
862 foreach (@$res) {
863 my ( $numplis, $nbpgpli ) = @$_;
864  
865 # If we can no longer add folded items or pages, we stop.
866 last if $availplis == 0 || $availpgs == 0;
867  
868 # There are not enough pages available to add a
869 # folded item of this size, so we try with smaller folded items.
870 next if $availpgs < $nbpgpli;
871  
872 my $nbplis = int( $availpgs / $nbpgpli );
873 if ( $nbplis > $availplis ) {
874 $nbplis = $availplis;
875 }
876 if ( $nbplis > $numplis ) {
877 $nbplis = $numplis;
878 }
879 my $nbpgs = $nbplis * $nbpgpli;
880  
881 push( @plis, [ $nbplis, $nbpgpli ] );
882 $availplis -= $nbplis;
883 $availpgs -= $nbpgs;
884 $selplis += $nbplis;
885 $selpgs += $nbpgs;
886 }
887  
888 # Check that we selected enough pages and folded items to
889 # meet the lower limits of the production line, if any.
890 my $min_feuilles = $fil->{'ED_MINFEUIL_L'} || 1;
891 if ( $selpgs < $min_feuilles ) {
892 &logger( 5,
893 "INFO: Not enough pages for production line \"$idfiliere\" : "
894 . "got $selpgs, need $min_feuilles\n" );
895 $more = 1; # TODO check that we really need it
896 # _get_next_filiere($pdbh, $idfiliere);
897 # reset the production line with an eval restart or by completing the @$ids list? xxxxxxxxxxxxx
898 # see 388
899 my $sql =
900 "UPDATE "
901 . $cfg->{'EDTK_DBI_OUTMNGR'}
902 . " SET ED_IDFILIERE = ? "
903 . "WHERE ED_IDLOT = ? AND ED_IDFILIERE = ? AND ED_CORP = ? AND ED_SEQLOT IS NULL ";
904 my $next_filiere = _get_next_filiere( $pdbh, $idfiliere );
905 my @vals = ( $next_filiere, $idlot, $idfiliere, $idcorp );
906 my $num = $dbh->do( $sql, undef, @vals );
907 $dbh->commit
908 ; # see whether we can avoid it to benefit from rollback when a retry is needed
909 #&logger(7, "DEBUG: downgrade production line to $next_filiere for $num pages\n");
910 $idfiliere = $next_filiere;
911 redo CHECK_FIL;
912 }
913 my $minplis = $fil->{'ED_MINPLIS'} || 1;
914 if ( $selplis < $minplis ) {
915 &logger( 5,
916 "INFO: Not enough folded items for production line \"$idfiliere\" : "
917 . "got $selplis, need $minplis\n" );
918 $more = 1; # TODO check that we really need it
919 # _get_next_filiere($pdbh, $idfiliere);
920 # reset the production line with an eval restart or by completing the @$ids list? xxxxxxxxxxxxx
921 # see 388
922 my $sql =
923 "UPDATE "
924 . $cfg->{'EDTK_DBI_OUTMNGR'}
925 . " SET ED_IDFILIERE = ? "
926 . "WHERE ED_IDLOT = ? AND ED_IDFILIERE = ? AND ED_CORP = ? AND ED_SEQLOT IS NULL ";
927 my $next_filiere = _get_next_filiere( $pdbh, $idfiliere );
928 my @vals = ( $next_filiere, $idlot, $idfiliere, $idcorp );
929 my $num = $dbh->do( $sql, undef, @vals );
930 $dbh->commit
931 ; # see whether we can avoid it to benefit from rollback when a retry is needed
932 &logger( 6,
933 "INFO: downgrade production line to $next_filiere for $num pages\n" );
934 $idfiliere = $next_filiere;
935 redo CHECK_FIL;
936 }
937  
938 my $seqlot = _get_seqlot($dbh);
939 my $name =
940 "$gvals->{'ED_CORP'}.$lot->{'ED_IDMANUFACT'}.$seqlot.$lot->{'ED_LOTNAME'}.$fil->{'ED_IDFILIERE'}";
941  
942 # Prepare the sort order for this production line.
943 my $order;
944 if ( defined $fil->{'ED_SORT'} && length( $fil->{'ED_SORT'} ) > 0 ) {
945 $order = $fil->{'ED_SORT'};
946 if ( defined $fil->{'ED_DIRECTION'}
947 && length( $fil->{'ED_DIRECTION'} ) > 0 )
948 {
949 $order .= " $fil->{'ED_DIRECTION'}";
950 }
951 }
952 else {
953 $order = "ED_IDLDOC, ED_SEQDOC";
954 }
955  
956 # Today's date.
957 my $dtlot = sprintf( "%04d%02d%02d", Today() );
958  
959 foreach (@plis) {
960 my ( $nbplis, $nbpgpli ) = @$_;
961  
962 #&logger(7, "DEBUG: Assigning $nbplis of $nbpgpli pages each to lot $seqlot\n");
963 # This query selects the first N unassigned folded items
964 # of a given size, the folded items being identified only by
965 # a document batch id + a folded-item id.
966 $innersql =
967 "SELECT j.ED_IDLDOC, j.ED_SEQDOC FROM ("
968 . "SELECT i.ED_IDLDOC, i.ED_SEQDOC, ROW_NUMBER() "
969 . "OVER (ORDER BY PGNUM) AS PLINUM FROM "
970 . "(SELECT "
971 . $cfg->{'EDTK_DBI_OUTMNGR'}
972 . ".*, ROW_NUMBER() OVER (ORDER BY $order) AS PGNUM " . "FROM "
973 . $cfg->{'EDTK_DBI_OUTMNGR'}
974 . " $where2 AND ED_NBPGPLI = ?) i "
975 . "WHERE ED_SEQPGDOC = 1) j WHERE PLINUM <= ?";
976  
977 # Assign the batch to all the selected folded items. We also take the
978 # opportunity to set the batch creation date.
979 $sql =
980 "UPDATE "
981 . $cfg->{'EDTK_DBI_OUTMNGR'}
982 . " SET ED_SEQLOT = ?, ED_DTLOT = ? "
983 . "WHERE (ED_IDLDOC, ED_SEQDOC) IN ($innersql)";
984 my $count =
985 $dbh->do( $sql, undef, $seqlot, $dtlot, @wvals2, $nbpgpli, $nbplis );
986 my $pages = $nbplis * $nbpgpli;
987 if ( $count != $pages ) {
988 die "ERROR: Unexpected UPDATE row count ($count != $pages)\n";
989 }
990 }
991 &logger( 6, "INFO: Assigned $selpgs pages to lot \"$name\"\n" );
992  
993 # Compute the folded-item ids. XXX Should be done differently...
994 $sql =
995 "SELECT ED_IDLDOC, ED_SEQDOC, "
996 . "DENSE_RANK() OVER (ORDER BY ED_IDLDOC, ED_SEQDOC) AS ED_IDPLI " . "FROM "
997 . $cfg->{'EDTK_DBI_OUTMNGR'}
998 . " WHERE ED_SEQLOT = ? ORDER BY $order";
999 my $rows = $dbh->selectall_arrayref( $sql, { Slice => {} }, $seqlot );
1000  
1001 $sql =
1002 'UPDATE '
1003 . $cfg->{'EDTK_DBI_OUTMNGR'}
1004 . ' SET ED_IDPLI = ? '
1005 . 'WHERE ED_IDLDOC = ? AND ED_SEQDOC = ? AND ED_SEQLOT = ?';
1006 my $sth = $dbh->prepare($sql);
1007 foreach my $row (@$rows) {
1008 $sth->execute(
1009 $row->{'ED_IDPLI'}, $row->{'ED_IDLDOC'},
1010 $row->{'ED_SEQDOC'}, $seqlot
1011 );
1012 }
1013  
1014 # Retrieve the list of print items needed for this batch.
1015 $sql =
1016 'SELECT DISTINCT ED_REFIMP FROM '
1017 . $cfg->{'EDTK_DBI_OUTMNGR'}
1018 . ' WHERE ED_SEQLOT = ?';
1019 my @refimps = $dbh->selectrow_array( $sql, undef, $seqlot );
1020  
1021 # Compute the total number of sheets in the batch.
1022 $sql =
1023 "SELECT SUM(i.ED_NBFPLI) "
1024 . " FROM (SELECT DISTINCT ED_IDLDOC, ED_SEQDOC, ED_NBFPLI "
1025 . " FROM "
1026 . $cfg->{'EDTK_DBI_OUTMNGR'}
1027 . " WHERE ED_SEQLOT = ?) i ";
1028 my ($nbfeuillot) = $dbh->selectrow_array( $sql, undef, $seqlot );
1029 my $nbfaceslot = $nbfeuillot;
1030 if ( $fil->{'ED_MODEDI'} ne 'R' ) { $nbfaceslot *= 2; }
1031  
1032 # Extract the data.
1033 my $lotdir = "$basedir/$name";
1034 mkdir("$lotdir") or die "ERROR: Cannot create directory \"$lotdir\": $!\n";
1035 my $file = "$name.idx";
1036 &logger( 6, "INFO: Creating index file \"$file\"\n" );
1037 $sql =
1038 "SELECT * FROM "
1039 . $cfg->{'EDTK_DBI_OUTMNGR'}
1040 . " WHERE ED_SEQLOT = ? ORDER BY $order";
1041 $sth = $dbh->prepare($sql);
1042 $sth->execute($seqlot);
1043  
1044 open( my $fh, '>', "$lotdir/$file" )
1045 or die( "ERROR: die in omgr_export, message is " . $! );
1046  
1047 # Generate the header line.
1048 my $csv = Text::CSV->new( { binary => 1, eol => "\n", quote_space => 0 } );
1049 $csv->print( $fh, [ map { $$_[0] } @INDEX_COLS ] );
1050 my $doclib;
1051 while ( my $row = $sth->fetchrow_hashref() ) {
1052  
1053 # Gather the values in the same order as @INDEX_COLS.
1054 my @fields = map { $row->{ $$_[0] } } @INDEX_COLS;
1055 $csv->print( $fh, \@fields );
1056  
1057 $doclib = $row->{'ED_DOCLIB'} unless defined $doclib;
1058 }
1059 close($fh);
1060  
1061 # Generate a job ticket file.
1062 $file = "$name.job";
1063 &logger( 6, "INFO: Creating job ticket file \"$file\"\n" );
1064 my @jobfields = (
1065 [ 'ED_PRIORITE', $lot->{'ED_PRIORITE'} ],
1066 [ 'ED_REFIDDOC', $lot->{'ED_REFIDDOC'} ],
1067 [ 'ED_IDLOT', $idlot ],
1068 [ 'ED_SEQLOT', $seqlot ],
1069 [ 'ED_CORP', $gvals->{'ED_CORP'} ],
1070 [ 'ED_GROUPBY', $lot->{'ED_GROUPBY'} ],
1071 [ 'ED_CPDEST', $lot->{'ED_CPDEST'} ],
1072 [ 'ED_REFENC', $lot->{'ED_REFENC'} ],
1073 [ 'ED_LOTNAME', $lot->{'ED_LOTNAME'} ],
1074 [ 'ED_IDMANUFACT', $lot->{'ED_IDMANUFACT'} ],
1075 [ 'ED_IDFILIERE', $idfiliere ],
1076 [ 'ED_DESIGNATION', $fil->{'ED_DESIGNATION'} ],
1077 [ 'ED_MODEDI', $fil->{'ED_MODEDI'} ],
1078 [ 'ED_TYPED', $fil->{'ED_TYPED'} ],
1079 [ 'ED_NBBACPRN', $fil->{'ED_NBBACPRN'} ],
1080 [ 'ED_MINFEUIL_L', $fil->{'ED_MINFEUIL_L'} ],
1081 [ 'ED_MAXFEUIL_L', $fil->{'ED_MAXFEUIL_L'} ],
1082 [ 'ED_FEUILPLI', $fil->{'ED_FEUILPLI'} ],
1083 [ 'ED_MINPLIS', $fil->{'ED_MINPLIS'} ],
1084 [ 'ED_MAXPLIS', $fil->{'ED_MAXPLIS'} ],
1085 [ 'ED_POIDS_PLI', $fil->{'ED_POIDS_PLI'} ],
1086 [ 'ED_REF_ENV', $fil->{'ED_REF_ENV'} ],
1087 [ 'ED_FORMFLUX', $fil->{'ED_FORMFLUX'} ],
1088 [ 'ED_POSTCOMP', $fil->{'ED_POSTCOMP'} ],
1089 [ 'ED_NBFACESLOT', $nbfaceslot ],
1090 [ 'ED_NBFEUILLOT', $nbfeuillot ],
1091 [ 'ED_NBPLISLOT', $selplis ],
1092 [ 'ED_FORMATP', $gvals->{'ED_FORMATP'} ],
1093 [ 'ED_CONSIGNE', $lot->{'ED_CONSIGNE'} ],
1094 [ 'ED_LISTEREFENC', $gvals->{'ED_LISTEREFENC'} || "" ],
1095 [ 'ED_LISTEREFIMP', join( ', ', @refimps ) || "" ]
1096 , # if I put this field last, I crash latex...
1097 [ 'ED_DTLOT', $dtlot ]
1098  
1099 );
1100 open( $fh, '>', "$lotdir/$file" )
1101 or die( "ERROR: die in omgr_export, message is " . $! );
1102 $csv->print( $fh, [ map { $$_[0] } @jobfields ] );
1103 $csv->print( $fh, [ map { $$_[1] } @jobfields ] );
1104 close($fh);
1105  
1106 # Add this lot to the list of created ones.
1107 $dbh->commit;
1108 push( @done, [ $name, $doclib ] );
1109  
1110 # Loop the processing again if we reached the maximum limits in
1111 # pages/folded items and we must process other batches.
1112 redo if $more;
1113 }
1114 }
1115 }
1116 };
1117 if ($@) {
1118 &logger( 3, "ERROR: $@\n" );
1119 eval { $dbh->rollback };
1120 die "ERROR: die after outmngr rollback !\n";
1121 }
1122 return @done;
1123 }
1124  
1125 sub omgr_depot_poste {
1126 my ( $dbh, $seqlot, $dt_depot ) = @_;
1127 my $cfg = config_read('EDTK_DB');
1128  
1129 $dt_depot =~ /^\d{8}$/ or die "ERROR: $dt_depot should be formated as yyyymmdd\n";
1130  
1131 my $sql = 'UPDATE ' . $cfg->{'EDTK_DBI_OUTMNGR'} . ' SET ED_STATUS = ? WHERE ED_SEQLOT like ?';
1132 $dbh->do( $sql, undef, $dt_depot, $seqlot ) or die "ERROR: can't update $seqlot with $dt_depot";
1133 }
1134  
1135 # True if $value looks like a document id (idldoc). Since S70/D1 it is a
1136 # 36-char UUID; the legacy 16-digit YWWWDHHMMSSPPPP.r form is still
1137 # accepted. Mirror of oEdtk::Main::oe_is_IDLDOC -- duplicated because
1138 # Main requires Outmngr (a use of Main here would be a cycle).
1139 sub _is_IDLDOC {
1140 my $value = shift;
1141 return 0 unless defined $value;
1142 return $value =~ /^[0-9A-Fa-f]{8}(?:-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$/
1143 || $value =~ /^\d{16}$/;
1144 }
1145  
1146 sub _omgr_purge_db {
1147 my ( $dbh, $value ) = @_;
1148 my $cfg = config_read('EDTK_STATS');
1149 my $type = "";
1150 my $sql;
1151  
1152 if ( $value =~ /^\d{6,7}$/ ) { # 381123 or 1381123
1153 $type = "SEQLOT";
1154 &logger( 6, "INFO: delete $type $value from EDTK_STATS_OUTMNGR\n" );
1155 $sql = 'DELETE FROM ' . $cfg->{'EDTK_STATS_OUTMNGR'} . ' WHERE ED_SEQLOT = ?';
1156 $dbh->do( $sql, undef, $value )
1157 or die "ERROR: delete $type $value from EDTK_STATS_OUTMNGR\n";
1158  
1159 #} elsif (length ($value) == 16) { # 1282152443057128
1160 }
1161 elsif ( _is_IDLDOC($value) ) { # 1282152443057128 or a 36-char UUID
1162 $type = "SNGL_ID"; # EDTK_STATS_TRACKING
1163 &logger( 6, "INFO: delete $type $value from EDTK_STATS_TRACKING\n" );
1164 $sql = 'DELETE FROM ' . $cfg->{'EDTK_STATS_TRACKING'} . ' WHERE ED_SNGL_ID = ?';
1165 $dbh->do( $sql, undef, $value )
1166 or die "ERROR: delete $type $value from EDTK_STATS_TRACKING\n";
1167  
1168 &logger( 6, "INFO: delete $type $value from EDTK_STATS_OUTMNGR\n" );
1169 $sql = 'DELETE FROM ' . $cfg->{'EDTK_STATS_OUTMNGR'} . ' WHERE ED_IDLDOC = ?';
1170 $dbh->do( $sql, undef, $value )
1171 or die "ERROR: delete $type $value from EDTK_STATS_OUTMNGR\n";
1172  
1173 }
1174 else {
1175 die "ERROR: $value doesn't seem to be SNGL_ID or SEQLOT";
1176 }
1177 }
1178  
1179 sub omgr_check_seqlot_ref {
1180 my ( $dbh, $value, $idseqpg ) = @_;
1181 my $cfg = config_read('EDTK_STATS');
1182 my $type = "SEQLOT";
1183 my $sql;
1184 $sql =
1185 "SELECT COUNT (DISTINCT A.ED_IDLDOC||TO_CHAR(A.ED_SEQDOC,'FM0000000')) AS NBDOCS,"
1186 . " A.ED_REFIDDOC, A.ED_IDLDOC,"
1187 . " COUNT (DISTINCT A.ED_IDLDOC||TO_CHAR(A.ED_IDSEQPG,'FM0000000')) AS NBPGS,"
1188 . " A.ED_SEQLOT,"
1189 . " COUNT (DISTINCT A.ED_IDLDOC||A.ED_SEQLOT||TO_CHAR(A.ED_IDPLI,'FM0000000')) AS NBPLIS,"
1190 . " NVL(B.ED_STATUS, NVL(A.ED_STATUS, 'PENDING...')) AS STATUS,"
1191 . " B.ED_DTPOST AS DTPOST, B.ED_DTPOST2 AS DTPOST2"
1192 . " FROM "
1193 . $cfg->{'EDTK_STATS_OUTMNGR'}
1194 . " A, EDTK_ACQ B"
1195 . " WHERE A.ED_SEQLOT=B.ED_SEQLOT (+)";
1196  
1197 if ( $value =~ /^\d{6,7}$/ ) { # 381123 or 1381123
1198 $type = "SEQLOT";
1199 $sql .= " AND A.ED_SEQLOT = ?"
1200 . " GROUP BY A.ED_REFIDDOC, A.ED_IDLDOC, A.ED_SEQLOT, B.ED_STATUS, A.ED_STATUS, B.ED_DTPOST, B.ED_DTPOST2 ";
1201 $idseqpg = 0;
1202  
1203 }
1204 elsif ( _is_IDLDOC($value) ) { # 1282152443057128 or a 36-char UUID
1205 $type = "IDLDOC";
1206 $sql .= " AND A.ED_IDLDOC = ?";
1207 if ( defined $idseqpg && $idseqpg > 0 ) {
1208 $sql .= " AND A.ED_IDSEQPG = ?";
1209 }
1210 $sql .=
1211 " GROUP BY A.ED_REFIDDOC, A.ED_IDLDOC, A.ED_SEQLOT, B.ED_STATUS, A.ED_STATUS, B.ED_DTPOST, B.ED_DTPOST2 ";
1212  
1213 }
1214 else {
1215 die "ERROR: $value doesn't seem to be SEQLOT OR IDLDOC\n";
1216 }
1217  
1218 my $sth = $dbh->prepare($sql);
1219 if ( defined $idseqpg && $idseqpg > 0 ) {
1220 $sth->execute( $value, $idseqpg );
1221 }
1222 else {
1223 $sth->execute($value);
1224 }
1225  
1226 my $rows = $sth->fetchall_arrayref();
1227 if ( $#$rows < 0 ) {
1228 &logger( 6, "INFO: no associated data.\n" );
1229 exit;
1230 }
1231 my $fmt = "%7s %-16s %-16s %6s %-7s %7s %10s %8s %8s";
1232 my @head = (
1233 "NB_DOCS", "REFIDDOC", "IDLDOC", "NB_PG", "SEQLOT", "NB_PLIS",
1234 "STATUS", "DTPOST", "DTPOST2"
1235 );
1236  
1237 _filled_rows($rows);
1238 @$rows = ( \$fmt, \@head, @$rows );
1239  
1240 return $rows;
1241 }
1242  
1243 sub omgr_stats_referent {
1244 my ( $dbh, $pdbh ) = @_;
1245 my $cfg = config_read('EDTK_STATS');
1246 my ( $sql, $key );
1247  
1248 $sql = "SELECT A.ED_MAIL_REFERENT, A.ED_REFIDDOC ";
1249 $sql .= " FROM EDTK_REFIDDOC A, " . $cfg->{'EDTK_STATS_OUTMNGR'} . " B ";
1250 $sql .= " WHERE A.ED_REFIDDOC = B.ED_REFIDDOC ";
1251 $sql .= " AND A.ED_MASSMAIL != 'N' AND A.ED_MAIL_REFERENT IS NOT NULL ";
1252 $sql .= " AND B.ED_SEQLOT IS NULL AND B.ED_DTLOT IS NULL ";
1253 $sql .= " GROUP BY A.ED_MAIL_REFERENT, A.ED_REFIDDOC ";
1254 $sql .= " ORDER BY A.ED_MAIL_REFERENT ";
1255  
1256 my $sth = $dbh->prepare($sql);
1257 $sth->execute();
1258  
1259 my $rows = $sth->fetchall_arrayref();
1260 return $rows;
1261 }
1262  
1263 # EDTK_STATS_MANUFACT (D-S52): a comma- or space-separated list of ED_IDMANUFACT
1264 # codes, the subcontractors ("faconniers") whose shipments omgr_stats reports.
1265 # When the key is absent or empty, no filter is applied (mainline behaviour). The
1266 # codes (the subcontractor manufacturer ids) live in the ini, never in this code.
1267 sub _stats_manufact {
1268 my ($cfg) = @_;
1269 my $list = $cfg->{'EDTK_STATS_MANUFACT'};
1270 return {} unless defined $list and $list =~ /\S/;
1271 my %codes;
1272 $codes{ uc $_ } = 1 for grep { length } split /[\s,]+/, $list;
1273 return \%codes;
1274 }
1275  
1276 sub omgr_stats {
1277 my ( $dbh, $pdbh, $period, $typeRqt ) = @_;
1278 $typeRqt = $typeRqt || "idlot";
1279 my $cfg = config_read('EDTK_STATS');
1280 my ( $sql, $key );
1281 my $time = time;
1282 my ( $year, $month, $day, $hour, $min, $sec, $doy, $dow, $dst ) = Gmtime($time);
1283 my ( $week, ) = Week_of_Year( $year, $month, $day );
1284  
1285 if ( $period =~ /^day$/i ) {
1286 $key = sprintf( "%1d%02d%1d", $year % 10, $week, $dow );
1287 }
1288 elsif ( $period =~ /^week$/i ) {
1289 $key = sprintf( "%1d%02d", $year % 10, $week );
1290 }
1291 elsif ( $period =~ /^all$/i ) {
1292 $key = "";
1293 }
1294 elsif ( $period =~ /^\d+$/ ) {
1295 $key = $period;
1296 }
1297 else {
1298 &logger( 6, "INFO: implementation awaiting database evolution\n" );
1299 }
1300  
1301 my @head;
1302 if ( $typeRqt !~ /idlot/i ) {
1303 @head = ( "CORP", "LOT", "PLIS", "DOCS", "FEUILLES", "PAGES", "FACES", "FIL." );
1304 $sql = "SELECT ED_CORP, ED_IDLOT, ";
1305 }
1306 else {
1307 @head =
1308 ( "CORP", "LOT", "ID_SEQLOT", "PLIS", "DOCS", "FEUILLES", "PAGES", "FACES", "FIL." );
1309 $sql = "SELECT ED_CORP, ED_IDLOT, ED_SEQLOT, ";
1310 }
1311 $sql .= "COUNT (DISTINCT ED_IDLDOC||TO_CHAR(ED_SEQDOC,'FM0000000')), "
1312 ; # NB PLIS # does not account for possible batching, to review: (DISTINCT TO_CHAR(ED_SEQLOT,'FM0000000')||TO_CHAR(ED_IDPLI,'FM0000000'))
1313 $sql .= "COUNT (DISTINCT ED_IDLDOC||TO_CHAR(ED_SEQDOC,'FM0000000')), "; # NB DOCS
1314 $sql .= "SUM(ED_NBFPLI), "; # NB SHEETS
1315 $sql .= "SUM(ED_NBPGDOC), "; # NB PRINTED FACES
1316 $sql .= "CASE ED_MODEDI WHEN 'R' THEN 1 ELSE 2 END * SUM(ED_NBFPLI) "; # NB FACES
1317  
1318 if ( $typeRqt !~ /idlot/i ) {
1319 $sql .= ", ED_MODEDI ";
1320 $sql .= " FROM " . $cfg->{'EDTK_STATS_OUTMNGR'};
1321 $sql .= " GROUP BY ED_CORP, ED_IDLOT, ED_MODEDI ";
1322 $sql .= " ORDER BY ED_CORP, ED_IDLOT, ED_MODEDI ";
1323 }
1324 else {
1325 $sql .= ", ED_IDFILIERE ";
1326 $sql .= " FROM " . $cfg->{'EDTK_STATS_OUTMNGR'};
1327 $sql .= " WHERE ED_SEQLOT LIKE ? AND ED_SEQPGDOC = 1 ";
1328 $sql .= " GROUP BY ED_CORP, ED_IDLOT, ED_SEQLOT, ED_IDFILIERE, ED_MODEDI ";
1329 $sql .= " ORDER BY ED_CORP, ED_IDFILIERE, ED_SEQLOT ";
1330 }
1331  
1332 my $sth = $dbh->prepare($sql);
1333 if ( $typeRqt !~ /idlot/i ) {
1334 $sth->execute();
1335 }
1336 else {
1337 $sth->execute("$key%");
1338 }
1339  
1340 my $manufact = _stats_manufact($cfg);
1341 my @kept;
1342 my $rows = $sth->fetchall_arrayref();
1343 foreach my $row (@$rows) {
1344 my ( $lot, $idmanufact ) = $pdbh->selectrow_array(
1345 'SELECT ED_LOTNAME, ED_IDMANUFACT FROM EDTK_LOTS WHERE ED_IDLOT = ?',
1346 undef, @$row[1] );
1347 next if keys(%$manufact) and !$manufact->{ uc( defined $idmanufact ? $idmanufact : '' ) };
1348 @$row[1] = $lot;
1349 push @kept, $row;
1350 }
1351  
1352 my $fmt = "%-8s%-16s" . "%9s" x ( @head - 3 ) . " %-6s\n";
1353 @$rows = ( \$fmt, \@head, @kept );
1354  
1355 #my $fmt = shift (@$rows);
1356 #my $head = shift (@$rows);
1357 #printf $$fmt . "\n", @$head;
1358 #
1359 #foreach my $row (@$rows) {
1360 # printf $$fmt . "\n", @$row;
1361 #}
1362  
1363 return $rows;
1364 }
1365  
1366 sub omgr_lot_pending {
1367  
1368 # SEARCH FOR DOCUMENTS PENDING BATCHING
1369 # that is, the documents whose seqlot is null
1370 # Used by index_Purge_DCLIB
1371 my ($dbh) = @_;
1372 my $cfg = config_read('EDTK_DB');
1373  
1374 #-- SEARCH FOR DOCUMENTS PENDING BATCHING --
1375 my $ctrl_sql =
1376 'SELECT ED_CORP, ED_REFIDDOC, ED_IDLDOC, ED_DTEDTION FROM '
1377 . $cfg->{'EDTK_DBI_OUTMNGR'}
1378 . ' WHERE ED_SEQLOT IS NULL'
1379 . ' GROUP BY ED_CORP, ED_REFIDDOC, ED_DTEDTION, ED_IDLDOC'
1380 . ' ORDER BY ED_CORP, ED_REFIDDOC, ED_DTEDTION, ED_IDLDOC';
1381  
1382 my $sth = $dbh->prepare($ctrl_sql);
1383 $sth->execute();
1384  
1385 my $rows = $sth->fetchall_arrayref();
1386 return $rows;
1387 }
1388  
1389 # LOOKS IF NEEDED DOCLIBS ARE IN EDTK_DIR_DOCLIB
1390 sub omgr_check_doclibs {
1391 my ($dbh) = shift;
1392  
1393 my $cfg = config_read('EDTK_DB');
1394 my $dir = $cfg->{'EDTK_DIR_DOCLIB'};
1395 my $host = hostname();
1396  
1397 my $sql =
1398 'SELECT DISTINCT ED_DOCLIB FROM '
1399 . $cfg->{'EDTK_DBI_OUTMNGR'}
1400 . ' WHERE ED_SEQLOT IS NULL AND ED_HOST = ? ';
1401  
1402 # Transform the list of needed doclibs into a hash for speed.
1403 my %needed = map { $_->[0] => 1 } @{ $dbh->selectall_arrayref( $sql, undef, $host ) };
1404  
1405 foreach my $key ( keys %needed ) {
1406 if ( -e "$dir/$key" ) {
1407 }
1408 else {
1409 die "ERROR: missing DOCLIB $key for current DSN\n";
1410 }
1411 }
1412  
1413 }
1414  
1415 # PURGE DOCLIBS THAT ARE NO LONGER REFERENCED IN THE DATABASE.
1416 sub omgr_purge_fs {
1417 my ($dbh) = shift;
1418 db_backup_agent($dbh);
1419  
1420 my $cfg = config_read('EDTK_DB');
1421 my $dir = $cfg->{'EDTK_DIR_DOCLIB'};
1422 my @doclibs = glob("$dir/*.pdf");
1423 my $weeks_kept = 0;
1424  
1425 unless ( defined( $cfg->{'EDTK_DCLIB_PURGE_WEEKS_KEPT'} )
1426 && $cfg->{'EDTK_DCLIB_PURGE_WEEKS_KEPT'} > 0 )
1427 {
1428 &logger( 6, "INFO: EDTK_DCLIB_PURGE_WEEKS_KEPT not defined for optimization purge.\n" );
1429 }
1430 else {
1431 $weeks_kept = $cfg->{'EDTK_DCLIB_PURGE_WEEKS_KEPT'};
1432 }
1433  
1434 my ( $year, $month, $day ) = Today();
1435 ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, ( -7 * $weeks_kept ) );
1436 my $search_date = sprintf( "%04d%02d%02d", $year, $month, $day );
1437  
1438 my $sql =
1439 "SELECT DISTINCT ED_DOCLIB FROM "
1440 . $cfg->{'EDTK_DBI_OUTMNGR'}
1441 . " WHERE ED_SEQLOT IS NULL OR ED_DTEDTION > '"
1442 . $search_date . "' ";
1443  
1444 # Transform the list of needed doclibs into a hash for speed.
1445 &logger( 6, "INFO: omgr_purge_fs identifies needed doclibs to safe them.\n" );
1446 my %needed = map { $_->[0] => 1 } @{ $dbh->selectall_arrayref($sql) };
1447  
1448 my @torm = ();
1449 foreach my $path (@doclibs) {
1450 my $file = basename($path);
1451 if ( $file =~ /^DCLIB_/ ) {
1452 if ( !$needed{$file} ) {
1453 push( @torm, $path );
1454 }
1455 }
1456 else {
1457 &logger( 3, "INFO: Unexpected filename : \"$file\"\n" );
1458 }
1459 }
1460  
1461 &logger( 6, "INFO: omgr_purge_fs done.\n" );
1462 return @torm;
1463 }
1464  
1465 # PRIVATE, NON-EXPORTED FUNCTIONS BELOW.
1466 ########################################
1467  
1468 # Compute a new and unique lot sequence.
1469 sub _get_seqlot {
1470 my $dbh = shift;
1471  
1472 # SQLite has no SEQUENCE and no to_char(): read the counter table set up by
1473 # create_lot_sequence (0..999, wrapping) and build the ISO week + day-of-week
1474 # prefix in Perl. This is what lets SQLite serve as the main database in tests.
1475 if ( $dbh->{'Driver'}->{'Name'} =~ m/SQLite/i ) {
1476 my ( $year, $month, $day ) = Today();
1477 my ($week) = Week_of_Year( $year, $month, $day );
1478 my $prefix = sprintf( "%02d%d", $week, Day_of_Week( $year, $month, $day ) );
1479 $dbh->do("update edtk_idlot_seq set id_val = ( id_val + 1 ) % 1000")
1480 or &logger( 3, "SQL execute failed " . $dbh->errstr );
1481 my ($seq) = $dbh->selectrow_array("select id_val from edtk_idlot_seq");
1482 $seq = 0 unless defined $seq;
1483 return sprintf( "%s%03d", $prefix, $seq );
1484 }
1485  
1486 my $sql;
1487 if ( $dbh->{'Driver'}->{'Name'} eq 'Oracle' ) {
1488  
1489 # sysdate produces the seqlot so the iso year fits on 1 character I
1490 # http://www.techonthenet.com/oracle/functions/to_char.php
1491 $sql = "SELECT to_char(sysdate, 'IIWD') || "
1492 . "to_char(EDTK_IDLOT.NEXTVAL, 'FM000') FROM dual";
1493  
1494 }
1495 else {
1496 # http://developer.postgresql.org/pgdocs/postgres/functions-formatting.html
1497 $sql =
1498 "SELECT to_char(current_date, 'IIWID') || " . "to_char(nextval('EDTK_IDLOT'), 'FM000')";
1499 }
1500 my ($seqlot) = $dbh->selectrow_array($sql);
1501 return $seqlot;
1502 }
1503  
1504 sub _filled_rows(\@) { ## no critic (ProhibitSubroutinePrototypes)
1505  
1506 # to make sure each cell holds at least a blank and avoid printf warnings when merging with an undefined cell
1507 my $refRows = shift;
1508  
1509 foreach my $row (@$refRows) {
1510 for ( my $i = 0 ; $i <= $#$row ; $i++ ) {
1511 $$row[$i] = $$row[$i] || ""; # IN THE CASE OF SEQLOT IT MAY NOT BE SET YET
1512 }
1513 }
1514  
1515 return @{$refRows};
1516 }
1517  
1518 sub _print_All_rTab {
1519  
1520 # PRINT ALL THE DATA OF A TABLE PASSED BY REFERENCE
1521 # display the table in columns
1522 my $rTab = shift;
1523  
1524 for ( my $i = 0 ; $i <= $#{$rTab} ; $i++ ) {
1525 my $cols = $#{ $$rTab[$i] };
1526 print "\n$i:\t";
1527  
1528 for ( my $j = 0 ; $j <= $cols ; $j++ ) {
1529 print "$$rTab[$i][$j]" if ( defined $$rTab[$i][$j] );
1530 }
1531 }
1532 print "\n";
1533 1;
1534 }
1535  
1536 END {
1537  
1538 }
1539  
1540 1;
1541  
1542 =head1 NAME
1543  
1544 oEdtk::Outmngr - output management for printed document batches
1545  
1546 =head1 SYNOPSIS
1547  
1548 use oEdtk::Outmngr qw(omgr_import omgr_export);
1549  
1550 omgr_import($app, $index_file, $corp); # insert the index, assign lot/filiere
1551 my @lots = omgr_export(%conds); # batch and export the print lots
1552  
1553 =head1 DESCRIPTION
1554  
1555 Output Management. It inserts the composition index into the Outmngr database,
1556 assigns each document a lot and a production line, batches and exports print
1557 lots (writing the C<.idx> and C<.job> files per lot), and provides the
1558 statistics, purge and acknowledgment tooling around that pipeline. The
1559 processing steps (insert and enrich, assign the lot, infer the manufacturer,
1560 export) are described in the module source.
1561  
1562 =head1 FUNCTIONS
1563  
1564 =head2 omgr_import
1565  
1566 omgr_import($app, $in, $corp);
1567  
1568 Read an index file into the C<EDTK_DBI_OUTMNGR> database, then assign the lot
1569 and the production line (rolling back on error).
1570  
1571 =head2 omgr_export
1572  
1573 my @lots = omgr_export(%conds);
1574  
1575 Group the pending documents under the batch constraints, build the batch
1576 sequence, and write the C<.idx> and C<.job> files for each lot. Returns the
1577 list of name and doclib pairs.
1578  
1579 =head2 omgr_check_acquit
1580  
1581 omgr_check_acquit($dbh, $nb_j_historique);
1582  
1583 Reconcile the acknowledgment status and counts in the C<EDTK_ACQ> tables;
1584 returns the number of rows updated.
1585  
1586 =head2 omgr_check_seqlot_ref
1587  
1588 omgr_check_seqlot_ref($dbh, $value, $idseqpg);
1589  
1590 Report, per batch or per document id, the status of its documents, pages and
1591 plis.
1592  
1593 =head2 omgr_check_doclibs
1594  
1595 omgr_check_doclibs($dbh);
1596  
1597 Die when a needed document library is missing from C<EDTK_DIR_DOCLIB>.
1598  
1599 =head2 omgr_depot_poste
1600  
1601 omgr_depot_poste($dbh, $seqlot, $dt_depot);
1602  
1603 Set the posting date (C<ED_STATUS>) for a batch.
1604  
1605 =head2 omgr_lot_pending
1606  
1607 omgr_lot_pending($dbh);
1608  
1609 List the documents that are still pending batching.
1610  
1611 =head2 omgr_purge_fs
1612  
1613 omgr_purge_fs($dbh);
1614  
1615 List the document-library PDFs that are safe to purge (older than the keep
1616 window).
1617  
1618 =head2 omgr_stats
1619  
1620 omgr_stats($dbh, $pdbh, $period, $typeRqt);
1621  
1622 Report batch, pli, document, sheet and face statistics for a period, optionally
1623 filtered by manufacturer.
1624  
1625 =head2 omgr_stats_referent
1626  
1627 omgr_stats_referent($dbh, $pdbh);
1628  
1629 Report the mailing referent and document listing.
1630  
1631 =head2 omgr_track_folds
1632  
1633 omgr_track_folds($dbh, $nb_j_historique);
1634  
1635 Produce the batch status tracking report.
1636  
1637 =head2 omgr_track_report
1638  
1639 omgr_track_report($dbh);
1640  
1641 Produce the per-referent and manufacturer faces and plis report.
1642  
1643 The internal subs C<_omgr_insert>, C<_omgr_lot>, C<_get_next_filiere>,
1644 C<_omgr_filiere>, C<_omgr_purge_db>, C<_stats_manufact>, C<_get_seqlot>,
1645 C<_is_IDLDOC>, C<_filled_rows> and C<_print_All_rTab>, and the empty
1646 C<omgr_track_no_omgr> stub, are not part of the public API.
1647  
1648 =head1 AUTHOR
1649  
1650 The oEdtk team.
1651  
1652 =cut