Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 192
0.00% covered (danger)
0.00%
0 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
ExecutiveReportChartService
0.00% covered (danger)
0.00%
0 / 192
0.00% covered (danger)
0.00%
0 / 10
6320
0.00% covered (danger)
0.00%
0 / 1
 lastScaleFilter
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 renderSeries
0.00% covered (danger)
0.00%
0 / 129
0.00% covered (danger)
0.00%
0 / 1
2162
 encodePng
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 missingPrerequisite
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
56
 niceScale
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
42
 text
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 dashedLine
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 formatAxis
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 truncate
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 fontPath
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2
3namespace App\Services;
4
5use Illuminate\Support\Facades\Log;
6
7/**
8 * Renders the weekly commercial report's "year week by week" trend charts as PNG.
9 *
10 * Why a raster image and not markup: the report is an email. Mail clients strip
11 * SVG and never run JS, and a 50-point line with a reference line and per-point
12 * labels is not expressible in the table/CSS subset Outlook's Word engine
13 * understands. The caller pairs each PNG with a plain-HTML figure strip so a
14 * client with images disabled still shows the numbers.
15 *
16 * The visual target is Duarte's reference (2026-07-31): blue trend line, variance
17 * percentages horizontal above/below each point, a 0-based axis on round ticks,
18 * S-prefixed week labels, and vertical bands marking annotated and in-progress
19 * weeks. Chart titles live in the HTML, not in the image.
20 */
21class ExecutiveReportChartService
22{
23    /** Supersampling factor — draw big, scale down, get anti-aliased output. */
24    private const SCALE = 2;
25
26    private const WIDTH = 1160;
27
28    private const HEIGHT = 380;
29
30    private const PAD_LEFT = 76;
31
32    private const PAD_RIGHT = 26;
33
34    /** Headroom for the band captions ("En curso", note names) above the plot. */
35    private const PAD_TOP = 34;
36
37    /** Room below the plot for the S-week ruler. */
38    private const PAD_BOTTOM = 48;
39
40    /** Target gridline count; with the 12% headroom below this reproduces the
41     * reference's 0/200/…/1600 and €0.0M/…/€7.0M axes exactly. */
42    private const TARGET_TICKS = 8;
43
44    private const HEADROOM = 1.12;
45
46    /**
47     * Which imagescale filter actually succeeded on the last render.
48     *
49     * Exposed for the chart doctor: a host where IMG_BICUBIC is rejected still
50     * produces charts, just softer ones, and that difference is otherwise
51     * invisible until somebody compares two environments byte-for-byte.
52     */
53    private static ?string $lastScaleFilter = null;
54
55    public static function lastScaleFilter(): ?string
56    {
57        return self::$lastScaleFilter;
58    }
59
60    private const COLORS = [
61        'bg' => [255, 255, 255],
62        'line' => [61, 111, 214],   // trend — royal blue, per the reference
63        'grid' => [232, 230, 226],
64        'axis' => [138, 138, 142],
65        'baseline' => [190, 188, 184],
66        'avg' => [90, 89, 86],      // dashed year-average reference
67        'pos' => [26, 138, 74],     // report green
68        'neg' => [217, 72, 43],     // report red
69        'openband' => [236, 236, 234],
70        'opentext' => [107, 106, 103],
71        'noteband' => [247, 228, 224],
72        'notetext' => [165, 58, 42],
73    ];
74
75    /**
76     * @param  array  $points  list of ['week'=>int,'value'=>float,'pct'=>?float,'in_progress'=>bool,'note'=>?string]
77     * @param  string  $kind  'eur' | 'num' — drives y-axis label formatting
78     * @return string raw PNG bytes, or '' when rendering is unavailable
79     */
80    public function renderSeries(array $points, float $average, string $kind): string
81    {
82        // Fail loudly and specifically. When this returns '' the caller drops the
83        // <img> and the section renders as a bare title plus the figure strip —
84        // which looks exactly like "the chart is not showing in the email", with
85        // nothing in the logs to say why. Each prerequisite is reported separately
86        // so the cause is obvious from one log line.
87        $missing = $this->missingPrerequisite();
88        if ($missing !== null) {
89            Log::channel('cron_send_executive_report')->error(
90                'ExecutiveReportChartService: cannot render charts — '.$missing.
91                '. The report will be sent with the HTML figure strip only.'
92            );
93
94            return '';
95        }
96
97        if ($points === []) {
98            return '';
99        }
100
101        $s = self::SCALE;
102        $w = self::WIDTH * $s;
103        $h = self::HEIGHT * $s;
104
105        $im = imagecreatetruecolor($w, $h);
106        $c = [];
107        foreach (self::COLORS as $name => $rgb) {
108            $c[$name] = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
109        }
110        imagefill($im, 0, 0, $c['bg']);
111
112        $plotL = self::PAD_LEFT * $s;
113        $plotR = $w - (self::PAD_RIGHT * $s);
114        $plotT = self::PAD_TOP * $s;
115        $plotB = $h - (self::PAD_BOTTOM * $s);
116        $plotW = $plotR - $plotL;
117        $plotH = $plotB - $plotT;
118
119        $font = $this->fontPath();
120        $fontBold = $this->fontPath(true);
121
122        // ---- y scale on round numbers -----------------------------------
123        $values = array_map(fn ($p) => (float) $p['value'], $points);
124        $peak = max(max($values), $average);
125        [$axisMax, $step] = $this->niceScale($peak);
126
127        $n = count($points);
128        $stepX = $n > 1 ? $plotW / ($n - 1) : 0;
129        $xOf = fn (int $i) => (int) round($n > 1 ? $plotL + ($i * $stepX) : $plotL + ($plotW / 2));
130        $yOf = fn (float $v) => (int) round($axisMax > 0 ? $plotB - (($v / $axisMax) * $plotH) : $plotB);
131
132        // ---- vertical bands (drawn first, underneath everything) ---------
133        // A band is one week-column wide and carries its caption above the plot:
134        // grey for the unfinished week, salmon for an annotated one.
135        $halfStep = (int) round($stepX / 2);
136        foreach ($points as $i => $p) {
137            $isOpen = ! empty($p['in_progress']);
138            $note = $p['note'] ?? null;
139
140            if (! $isOpen && ($note === null || $note === '')) {
141                continue;
142            }
143
144            $x = $xOf($i);
145            $from = max($plotL, $x - $halfStep);
146            // The open week runs to the right edge — there is nothing after it,
147            // and stopping short would imply a week that does not exist.
148            $to = $isOpen ? $plotR : min($plotR, $x + $halfStep);
149
150            imagefilledrectangle($im, $from, $plotT, $to, $plotB, $isOpen ? $c['openband'] : $c['noteband']);
151
152            $caption = $isOpen ? 'En curso' : $this->truncate((string) $note, 16);
153            $colour = $isOpen ? $c['opentext'] : $c['notetext'];
154            // Right-align the last band's caption so it cannot overflow the
155            // canvas the way a centred label would at the right edge.
156            $centre = (int) round(($from + $to) / 2);
157            [$anchor, $align] = $isOpen
158                ? [$plotR, 'right']
159                : [$centre, 'center'];
160
161            $this->text($im, $fontBold, 9 * $s, 0, $anchor, $plotT - (8 * $s), $colour, $caption, $align);
162        }
163
164        // ---- gridlines, ticks and y labels -------------------------------
165        for ($v = 0.0; $v <= $axisMax + 0.0001; $v += $step) {
166            $y = $yOf($v);
167            imageline($im, $plotL, $y, $plotR, $y, $v == 0.0 ? $c['baseline'] : $c['grid']);
168            // Short tick outside the axis, as in the reference.
169            imageline($im, $plotL - (4 * $s), $y, $plotL, $y, $c['axis']);
170            $this->text($im, $font, 9 * $s, 0, $plotL - (9 * $s), $y + (3 * $s), $c['axis'], $this->formatAxis($v, $kind), 'right');
171        }
172
173        // Left axis rule.
174        imageline($im, $plotL, $plotT, $plotL, $plotB, $c['baseline']);
175
176        // ---- year-average reference line (unlabelled, per the reference) --
177        if ($average > 0) {
178            $avgY = $yOf($average);
179            $this->dashedLine($im, $plotL, $avgY, $plotR, $avgY, $c['avg'], 7 * $s, 5 * $s, 2 * $s);
180        }
181
182        // ---- week ruler ("S2", "S3", …) ----------------------------------
183        // Every week when they fit; thinned out once the labels would collide,
184        // so the axis never becomes an unreadable smear late in the year.
185        $rulerY = $plotB + (20 * $s);
186        $everyNth = $stepX > 0 ? (int) max(1, ceil((22 * $s) / $stepX)) : 1;
187        foreach ($points as $i => $p) {
188            if ($i % $everyNth !== 0 && $i !== $n - 1) {
189                continue;
190            }
191            $this->text($im, $font, 9 * $s, 0, $xOf($i), $rulerY, $c['axis'], 'S'.$p['week'], 'center');
192        }
193
194        // ---- the trend line ----------------------------------------------
195        imagesetthickness($im, 3 * $s);
196        for ($i = 1; $i < $n; $i++) {
197            imageline($im, $xOf($i - 1), $yOf((float) $points[$i - 1]['value']), $xOf($i), $yOf((float) $points[$i]['value']), $c['line']);
198        }
199        imagesetthickness($im, 1);
200
201        // ---- points ------------------------------------------------------
202        $r = (int) round(4 * $s);
203        foreach ($points as $i => $p) {
204            imagefilledellipse($im, $xOf($i), $yOf((float) $p['value']), $r * 2, $r * 2, $c['line']);
205        }
206
207        // ---- variance labels ---------------------------------------------
208        // Positive above the point, negative below it, horizontal.
209        //
210        // The spec wants a percentage on every week, so a label that will not fit
211        // beside its neighbour is pushed onto a further-out row rather than
212        // dropped — two adjacent weeks of the same sign are common, and silently
213        // losing every second one leaves the chart looking arbitrary. Cursors are
214        // tracked per band per row.
215        $lastRight = ['up' => [], 'down' => []];
216        foreach ($points as $i => $p) {
217            if ($p['pct'] === null) {
218                continue;
219            }
220
221            $pct = (float) $p['pct'];
222            $rounded = (int) round(abs($pct));
223            $positive = $pct >= 0;
224            // A variance that rounds to nothing is "0%", not "−0%" / "+0%" —
225            // a signed zero reads as a rounding artefact, which it is.
226            $label = $rounded === 0
227                ? '0%'
228                : ($positive ? '+' : '−').number_format($rounded, 0, ',', '.').'%';
229
230            $size = 9 * $s;
231            $box = imagettfbbox($size, 0, $fontBold, $label);
232            $lw = $box !== false ? abs($box[2] - $box[0]) : 0;
233
234            $x = $xOf($i);
235            $y = $yOf((float) $p['value']);
236
237            // Preferred side: above when up, below when down. Flip if the label
238            // would leave the plot — a point sitting near zero has no room
239            // beneath it, and clamping instead would drop the text into the week
240            // ruler.
241            $above = $positive;
242            if (! $above && $y + (21 * $s) > $plotB - (2 * $s)) {
243                $above = true;
244            } elseif ($above && $y - (12 * $s) < $plotT + (9 * $s)) {
245                $above = false;
246            }
247
248            $band = $above ? 'up' : 'down';
249            // Nudge the end labels inward so the first and last do not spill over
250            // the axis gutter (where they collide with the y-axis values) or off
251            // the right edge.
252            $left = max($plotL, min($x - (int) round($lw / 2), $plotR - $lw));
253            $x = $left + (int) round($lw / 2);
254
255            // Walk outward until a row has clear space.
256            $row = 0;
257            $maxRows = 3;
258            while ($row < $maxRows && $left < ($lastRight[$band][$row] ?? PHP_INT_MIN) + (6 * $s)) {
259                $row++;
260            }
261            if ($row >= $maxRows) {
262                continue; // genuinely nowhere to put it
263            }
264
265            $offset = (12 * $s) + ($row * 13 * $s);
266            $labelY = $above ? $y - $offset : $y + (9 * $s) + $offset;
267
268            // Never let a staggered label run off the top of the canvas.
269            if ($labelY < 11 * $s) {
270                continue;
271            }
272
273            $lastRight[$band][$row] = $left + $lw;
274
275            $this->text($im, $fontBold, $size, 0, $x, $labelY, $positive ? $c['pos'] : $c['neg'], $label, 'center');
276        }
277
278        // ---- downscale for anti-aliasing ---------------------------------
279        // Not every libgd build handles IMG_BICUBIC on a canvas this size; some
280        // return false. Degrade through cheaper filters rather than losing the
281        // chart, and if scaling is impossible at all, emit the 2x image — an
282        // oversized chart still renders correctly in the email, since the <img>
283        // is width-constrained by CSS.
284        $out = false;
285        foreach (['IMG_BICUBIC' => IMG_BICUBIC, 'IMG_BILINEAR_FIXED' => IMG_BILINEAR_FIXED, 'IMG_NEAREST_NEIGHBOUR' => IMG_NEAREST_NEIGHBOUR] as $name => $filter) {
286            $out = @imagescale($im, self::WIDTH, self::HEIGHT, $filter);
287            if ($out !== false) {
288                self::$lastScaleFilter = $name;
289                // Anything other than bicubic means this host's libgd rejected the
290                // preferred filter — the chart still renders but is visibly softer,
291                // so make it observable rather than a silent quality regression.
292                if ($name !== 'IMG_BICUBIC') {
293                    Log::channel('cron_send_executive_report')->warning(
294                        'ExecutiveReportChartService: IMG_BICUBIC unavailable on this host; charts downscaled with '.$name.'.'
295                    );
296                }
297                break;
298            }
299        }
300
301        if ($out === false) {
302            Log::channel('cron_send_executive_report')->warning(
303                'ExecutiveReportChartService: imagescale failed for every filter; emitting the unscaled 2x image.'
304            );
305            $out = $im;
306        } else {
307            imagedestroy($im);
308        }
309
310        $png = $this->encodePng($out);
311        imagedestroy($out);
312
313        if ($png === '') {
314            Log::channel('cron_send_executive_report')->error(
315                'ExecutiveReportChartService: imagepng produced no usable PNG data.'
316            );
317        }
318
319        return $png;
320    }
321
322    /**
323     * PNG-encode via a temp file rather than an output buffer.
324     *
325     * ob_start()/ob_get_clean() around imagepng() captures anything else the
326     * process happens to print — a deprecation or warning from php-cli with
327     * display_errors on lands *ahead* of the PNG signature and silently corrupts
328     * every chart. A temp file cannot be polluted that way. The signature is still
329     * checked, so a bad encode returns '' and the caller falls back to the HTML
330     * figure strip instead of attaching a broken image.
331     */
332    private function encodePng($image): string
333    {
334        $tmp = tempnam(sys_get_temp_dir(), 'wcrchart');
335        if ($tmp === false) {
336            return '';
337        }
338
339        try {
340            if (@imagepng($image, $tmp, 9) === false) {
341                return '';
342            }
343
344            $bytes = (string) @file_get_contents($tmp);
345
346            return substr($bytes, 0, 8) === "\x89PNG\r\n\x1a\n" ? $bytes : '';
347        } finally {
348            @unlink($tmp);
349        }
350    }
351
352    /**
353     * Which prerequisite for PNG rendering is absent, or null when all are met.
354     *
355     * GD alone is not enough: the labels go through imagettftext(), which needs GD
356     * compiled with FreeType, plus a readable TTF. A host with GD but no FreeType
357     * silently produces a chart with no text at all.
358     */
359    public function missingPrerequisite(): ?string
360    {
361        if (! function_exists('imagecreatetruecolor')) {
362            return 'the GD extension is not installed (php-gd)';
363        }
364
365        if (! function_exists('imagettftext') || ! function_exists('imagettfbbox')) {
366            return 'GD is installed but built without FreeType, so text cannot be drawn';
367        }
368
369        if (! function_exists('imagescale')) {
370            return 'GD is installed without imagescale(), required for the anti-aliasing downscale';
371        }
372
373        $font = $this->fontPath();
374        if (! is_file($font) || ! is_readable($font)) {
375            return 'the DejaVu font is missing or unreadable at '.$font;
376        }
377
378        return null;
379    }
380
381    /**
382     * Axis maximum and step on a 1 / 2 / 2.5 / 5 / 10 ladder, with headroom so
383     * the peak's label has somewhere to sit.
384     *
385     * @return array{0: float, 1: float} [axisMax, step]
386     */
387    private function niceScale(float $peak): array
388    {
389        if ($peak <= 0) {
390            return [1.0, 0.25];
391        }
392
393        $target = $peak * self::HEADROOM;
394        $rawStep = $target / self::TARGET_TICKS;
395        $magnitude = pow(10, floor(log10($rawStep)));
396        $normalised = $rawStep / $magnitude;
397
398        if ($normalised <= 1) {
399            $factor = 1;
400        } elseif ($normalised <= 2) {
401            $factor = 2;
402        } elseif ($normalised <= 2.5) {
403            $factor = 2.5;
404        } elseif ($normalised <= 5) {
405            $factor = 5;
406        } else {
407            $factor = 10;
408        }
409
410        $step = $factor * $magnitude;
411
412        return [ceil($target / $step) * $step, $step];
413    }
414
415    /**
416     * imagettftext wrapper with horizontal alignment. GD anchors text at the
417     * baseline's left edge, so right/center alignment needs the measured width.
418     */
419    private function text($im, string $font, float $size, int $angle, int $x, int $y, int $color, string $text, string $align = 'left'): void
420    {
421        if ($text === '') {
422            return;
423        }
424
425        if ($align !== 'left') {
426            $box = imagettfbbox($size, $angle, $font, $text);
427            if ($box !== false) {
428                $width = abs($box[2] - $box[0]);
429                $x -= $align === 'right' ? $width : (int) round($width / 2);
430            }
431        }
432
433        imagettftext($im, $size, $angle, $x, $y, $color, $font, $text);
434    }
435
436    /** imagedashedline is deprecated, so step the dashes manually. */
437    private function dashedLine($im, int $x1, int $y1, int $x2, int $y2, int $color, int $dash, int $gap, int $thickness): void
438    {
439        imagesetthickness($im, $thickness);
440        for ($x = $x1; $x < $x2; $x += $dash + $gap) {
441            imageline($im, $x, $y1, min($x + $dash, $x2), $y2, $color);
442        }
443        imagesetthickness($im, 1);
444    }
445
446    /**
447     * Axis labels. Euro series read "€1.2M" and counts read "1600", matching the
448     * reference. Note these use a dot decimal rather than the Spanish comma the
449     * rest of the report uses — that is what the reference shows, and the "M"
450     * suffix keeps it unambiguous.
451     */
452    private function formatAxis(float $v, string $kind): string
453    {
454        if ($kind !== 'eur') {
455            return number_format($v, 0, '.', '');
456        }
457
458        return '€'.number_format($v / 1000000, 1, '.', '').'M';
459    }
460
461    /** Band captions have one week-column of room; keep them from bleeding out. */
462    private function truncate(string $text, int $max): string
463    {
464        if (mb_strlen($text) <= $max) {
465            return $text;
466        }
467
468        return mb_substr($text, 0, $max - 1).'…';
469    }
470
471    /**
472     * Repo-local DejaVu, with dompdf's bundled copy as a fallback so the charts
473     * still render if the resources copy goes missing.
474     */
475    private function fontPath(bool $bold = false): string
476    {
477        $name = $bold ? 'DejaVuSans-Bold.ttf' : 'DejaVuSans.ttf';
478
479        $candidates = [
480            resource_path('fonts/'.$name),
481            base_path('vendor/dompdf/dompdf/lib/fonts/'.$name),
482        ];
483
484        foreach ($candidates as $path) {
485            if (is_file($path)) {
486                return $path;
487            }
488        }
489
490        // Last resort: return the primary path anyway so imagettftext raises a
491        // visible warning rather than silently drawing an empty chart.
492        return $candidates[0];
493    }
494}