-
-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathKnowledgePanels.pm
1914 lines (1401 loc) · 66 KB
/
KnowledgePanels.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of Product Opener.
#
# Product Opener
# Copyright (C) 2011-2023 Association Open Food Facts
# Contact: contact@openfoodfacts.org
# Address: 21 rue des Iles, 94100 Saint-Maur des Fossés, France
#
# Product Opener is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=head1 NAME
ProductOpener::KnowledgePanels - Generate product knowledge panels that can be requested through the API
=head1 SYNOPSIS
Apps can request through the API knowledge panels for one product.
They are returned in the same structured format for all panels.
=head1 DESCRIPTION
See https://docs.google.com/document/d/1vJ9gatmv8pCXxyOERmYD16jOKRWJpz1RaQQ5MEcTxms/edit
=cut
package ProductOpener::KnowledgePanels;
use ProductOpener::PerlStandards;
use Exporter qw< import >;
use Log::Any qw($log);
BEGIN {
use vars qw(@ISA @EXPORT_OK %EXPORT_TAGS);
@EXPORT_OK = qw(
&initialize_knowledge_panels_options
&create_knowledge_panels
&create_panel_from_json_template
&add_taxonomy_properties_in_target_languages_to_object
); # symbols to export on request
%EXPORT_TAGS = (all => [@EXPORT_OK]);
}
use vars @EXPORT_OK;
use ProductOpener::Config qw/:all/;
use ProductOpener::Paths qw/%BASE_DIRS ensure_dir_created_or_die/;
use ProductOpener::Store qw/:all/;
use ProductOpener::Tags qw/:all/;
use ProductOpener::Products qw/:all/;
use ProductOpener::Users qw/$User_id/;
use ProductOpener::Food qw/%categories_nutriments_per_country/;
use ProductOpener::Ingredients qw/:all/;
use ProductOpener::Lang qw/f_lang f_lang_in_lc lang lang_in_other_lc/;
use ProductOpener::Display qw/:all/;
use ProductOpener::EnvironmentalScore qw/is_environmental_score_extended_data_more_precise_than_agribalyse/;
use ProductOpener::PackagerCodes qw/%packager_codes/;
use ProductOpener::KnowledgePanelsIngredients qw/create_ingredients_list_panel/;
use ProductOpener::KnowledgePanelsContribution qw/create_contribution_card_panel/;
use ProductOpener::KnowledgePanelsReportProblem qw/create_report_problem_card_panel/;
use ProductOpener::ProductsFeatures qw/feature_enabled/;
use JSON::MaybeXS;
use Encode;
use Data::DeepAccess qw(deep_get);
=head1 FUNCTIONS
=head2 initialize_knowledge_panels_options( $knowledge_panels_options_ref, $request_ref )
Initialize the options for knowledge panels from parameters.
=cut
sub initialize_knowledge_panels_options ($knowledge_panels_options_ref, $request_ref) {
# Activate physical activity knowledge panel only when specified
if (single_param("activate_knowledge_panel_physical_activities")) {
$knowledge_panels_options_ref->{activate_knowledge_panel_physical_activities} = 1;
}
# Specify if we knowledge panels are requested from the app or the website
# in order to allow different behaviours (e.g. showing ingredients before nutrition on the web)
# possible values: "web", "app"
my $knowledge_panels_client = single_param("knowledge_panels_client");
# set a default value if client is not defined to app or web
if ( (not defined $knowledge_panels_client)
or (($knowledge_panels_client ne "web") and ($knowledge_panels_client ne "app")))
{
# Default to app mode
$knowledge_panels_client = 'app';
# but if it's not an api request, we consider it should be web
if (not defined $request_ref->{api}) {
$knowledge_panels_client = "web";
}
}
$knowledge_panels_options_ref->{knowledge_panels_client} = $knowledge_panels_client;
my $included_panels = single_param('knowledge_panels_included') || '';
my %included_panels = map {$_ => 1} split(/,/, $included_panels);
my $excluded_panels = single_param('knowledge_panels_excluded') || '';
my %excluded_panels = map {$_ => 1} split(/,/, $excluded_panels);
$knowledge_panels_options_ref->{knowledge_panels_includes} = sub {
my $panel_id = shift;
# excluded overrides included
return ( (not exists $excluded_panels{$panel_id})
and (not $included_panels or exists $included_panels{$panel_id}));
};
# some info about users
$knowledge_panels_options_ref->{user_logged_in} = defined $User_id;
return;
}
=head2 create_knowledge_panels( $product_ref, $target_lc, $target_cc, $options_ref, $request_ref)
Create all knowledge panels for a product, with strings (descriptions, recommendations etc.)
in a specific language, and return them in an array of panels.
=head3 Arguments
=head4 product reference $product_ref
Loaded from the MongoDB database, Storable files, or the OFF API.
=head4 language code $target_lc (or "data")
Returned panels contain both data and strings intended to be displayed to users.
This parameter sets the desired language for the user facing strings.
If $target_lc is equal to "data", no strings are returned.
=head4 country code $target_cc
Needed for some country specific panels like the Environmental-Score.
=head4 options $options_ref
Defines how some panels should be created (or not created)
- deactivate_[panel_id] : do not create a default panel -- currently unimplemented
- activate_[panel_id] : create an on demand panel -- currently only for physical_activities panel
=head4 request reference $request_ref
Contains the request parameters, including the API request parameters.
=head3 Return values
Panels are returned in the "knowledge_panels_[$target_lc]" hash of the product reference
passed as input.
=cut
sub create_knowledge_panels ($product_ref, $target_lc, $target_cc, $options_ref, $request_ref) {
$log->debug("create knowledge panels for product", {code => $product_ref->{code}, target_lc => $target_lc})
if $log->is_debug();
# Initialize panels
$product_ref->{"knowledge_panels_" . $target_lc} = {};
# Test panel to test the start of the API
# Disabled, kept as reference when we create a "Do you know" panel
if ($product_ref->{code} eq "3017620422003--disabled") {
my $test_panel_ref = {
parent_panel_id => "root",
type => "doyouknow",
level => "trivia",
topics => ["ingredients"],
title_element => [
title => "Do you know why Nutella contains hazelnuts?",
subtitle => "It all started after the second world war...",
],
elements => [
{
element_type => "text",
element => {
text_type => "default",
html =>
"Cocoa beans were expensive and hard to come by after the second world war, so in Piedmont (Italy) where Pietro Ferrero created Nutella, they were replaced with hazelnuts to make <em>gianduja</em>, a mix of hazelnut paste and chocolate."
}
},
{
element_type => "image",
element => {
url => "https://static.openfoodfacts.org/images/attributes/contains-nuts.png",
width => 192,
height => 192
}
}
]
};
$product_ref->{"knowledge_panels_" . $target_lc}{"tags_brands_nutella_doyouknow"} = $test_panel_ref;
}
my $panel_is_requested = $options_ref->{knowledge_panels_includes};
# Create recommendation panels first, as they will be included in cards such has the health card and environment card
if ( $panel_is_requested->('health_card')
and $panel_is_requested->('environment_card')
and feature_enabled('food_recommendations'))
{
create_recommendation_panels($product_ref, $target_lc, $target_cc, $options_ref);
}
my $has_health_card;
if ($panel_is_requested->('health_card')
and feature_enabled('health_card'))
{
$has_health_card = create_health_card_panel($product_ref, $target_lc, $target_cc, $options_ref, $request_ref);
}
my $has_environment_card;
if ($panel_is_requested->('environment_card')) {
$has_environment_card
= create_environment_card_panel($product_ref, $target_lc, $target_cc, $options_ref, $request_ref);
}
my $has_report_problem_card;
if (not $options_ref->{producers_platform} and $panel_is_requested->('report_problem_card')) {
$has_report_problem_card = create_report_problem_card_panel($product_ref, $target_lc, $target_cc, $options_ref);
}
my $has_contribution_card;
if ($panel_is_requested->('contribution_card')) {
$has_contribution_card = create_contribution_card_panel($product_ref, $target_lc, $target_cc, $options_ref);
}
my $has_secondhand_card;
if ($panel_is_requested->('secondhand_card')) {
$has_secondhand_card
= create_secondhand_card_panel($product_ref, $target_lc, $target_cc, $options_ref, $request_ref);
}
# Create the root panel that contains the panels we want to show directly on the product page
create_panel_from_json_template(
"root",
"api/knowledge-panels/root.tt.json",
{
has_health_card => $has_health_card,
has_report_problem_card => $has_report_problem_card,
has_contribution_card => $has_contribution_card,
has_environment_card => $has_environment_card,
has_secondhand_card => $has_secondhand_card,
},
$product_ref,
$target_lc,
$target_cc,
$options_ref
);
return;
}
=head2 convert_multiline_string_to_singleline($line)
Helper function to allow to enter multiline strings in JSON templates.
The function converts the multiline string into a single line string.
New lines are converted to \n, and quotes " and \ are escaped if not escaped already.
=cut
sub convert_multiline_string_to_singleline ($line) {
# Escape " and \ unless they have been escaped already
# negative look behind to not convert \n to \\n or \" to \\" or \\ to \\\\
$line =~ s/(?<!\\)("|\\)/\\$1/g;
# \R will match all Unicode newline sequence
$line =~ s/\R/\\n/sg;
return '"' . $line . '"';
}
=head2 convert_multiline_string_to_singleline_without_line_breaks_and_extra_spaces($line)
Helper function to allow to enter multiline strings in JSON templates.
The function converts the multiline string into a single line string.
Line breaks are converted to spaces, and multiple spaces are converted to a single space.
This function is useful in templates where we use IF statements etc. to generate a single value like a title.
=cut
sub convert_multiline_string_to_singleline_without_line_breaks_and_extra_spaces ($line) {
# Escape " and \ unless they have been escaped already
# negative look behind to not convert \n to \\n or \" to \\" or \\ to \\\\
$line =~ s/(?<!\\)("|\\)/\\$1/g;
$line =~ s/\s+/ /g;
$line =~ s/^\s+//;
$line =~ s/\s+$//;
return '"' . $line . '"';
}
=head2 create_panel_from_json_template ( $panel_id, $panel_template, $panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref )
Creates a knowledge panel from a JSON template.
The template is passed both the full product data + optional panel specific data.
The template is thus responsible for all the display logic (what to display and how to display it).
Some special features that are not included in the JSON format are supported:
1. Relative links are converted to absolute links using the requested country / language subdomain
2. Multiline strings can be included using backticks ` at the start and end of the multiline strings.
- The multiline strings will be converted to a single string.
- Quotes " are automatically escaped unless they are already escaped
Using two backticks at the start and end of the string removes line breaks and extra spaces.
3. Comments can be included by starting a line with //
- Comments will be removed in the resulting JSON, they are only intended to make the source template easier to understand.
4. Trailing commas are removed
- For each loops in templates can result in trailing commas when separating items in a list with a comma
(e.g. if want to generate a list of labels)
=head3 Arguments
=head4 panel id $panel_id
=head4 panel template $panel_template
Relative path to the the template panel file, from the "/templates" directory.
e.g. "api/knowledge-panels/environment/environmental_score/agribalyse.tt.json"
=head4 panel data reference $panel_data_ref (optional, can be an empty hash)
Used to pass data that is necessary for the panel but is not contained in the product data.
=head4 product reference $product_ref
Loaded from the MongoDB database, Storable files, or the OFF API.
=head4 language code $target_lc
Returned attributes contain both data and strings intended to be displayed to users.
This parameter sets the desired language for the user facing strings.
=head4 country code $target_cc
The Environmental-Score depends on the country of the consumer (as the transport bonus/malus depends on it)
=cut
sub create_panel_from_json_template ($panel_id, $panel_template, $panel_data_ref, $product_ref, $target_lc, $target_cc,
$options_ref)
{
my $panel_json;
# We pass several structures to the template:
# - panel: this panel data
# - panels: the hash of all panels created so far (useful for panels that include previously created panels
# only if they have indeed been created)
# - product: the product data
if (
not process_template(
$panel_template,
{
panel => $panel_data_ref,
panels => $product_ref->{"knowledge_panels_" . $target_lc},
product => $product_ref,
knowledge_panels_options => $options_ref,
},
\$panel_json,
{cc => $target_cc}
)
)
{
# The template is invalid
$product_ref->{"knowledge_panels_" . $target_lc}{$panel_id} = {
"template" => $panel_template,
"template_error" => $tt->error() . "",
};
}
else {
# Turn the JSON to valid JSON
# Remove comment lines starting with //
# comments are not allowed in JSON, but they can be useful to have in the templates source
# /m modifier: ^ and $ match the start and end of each line
$panel_json =~ s/^(\s*)\/\/(.*)$//mg;
# Turn relative links to absolute links using the requested country / language subdomain
$panel_json =~ s/href="\//href="$formatted_subdomain\//g;
# Convert multilines strings between backticks `` into single line strings
# In the template, we use multiline strings for readability
# e.g. when we want to generate HTML
# Also escape quotes " to \"
$panel_json
=~ s/\`\`([^\`]*)\`\`/convert_multiline_string_to_singleline_without_line_breaks_and_extra_spaces($1)/seg;
$panel_json =~ s/\`([^\`]*)\`/convert_multiline_string_to_singleline($1)/seg;
# Remove trailing commas at the end of a string delimited by quotes
# Useful when using a foreach loop to generate a list of comma separated elements
# The negative look-behind is used in order not to remove commas after quotes, ] and } and digits
# (e.g. we want to keep the comma in "field1": "value1", "field2": "value2", and in "percent: 8, ")
# Note: this will fail if the string ends with a digit.
# As it is a trailing comma inside a string, it's not a terrible issue, the string will be valid,
# but it will have an unneeded trailing comma.
# The group (\W) at the end is to avoid removing commas before an opening quote (e.g. for "field": true, "other_field": ..)
$panel_json =~ s/(?<!("|'|\]|\}|\d))\s*,\s*"(\W)/"$2/sg;
# Remove trailing commas after the last element of a array or hash, as they will make the JSON invalid
# It makes things much simpler in templates if they can output a trailing comma though
# e.g. in FOREACH loops.
# So we remove them here.
$panel_json =~ s/,(\s*)(\]|\})/$2/sg;
# Transform the JSON in a Perl structure
$panel_json = encode('UTF-8', $panel_json);
eval {
$product_ref->{"knowledge_panels_" . $target_lc}{$panel_id} = decode_json($panel_json);
1;
} or do {
# The JSON generated by the template is invalid
my $json_decode_error = $@;
# Save the JSON file so that it can be more easily debugged, and that we can monitor issues
my $target_dir = "$BASE_DIRS{PUBLIC_FILES}/debug/knowledge_panels/";
my $filename = $panel_id . $product_ref->{code} . ".json";
my $target_file = "$target_dir/" . $filename;
my $url = "/files/debug/knowledge_panels/" . $filename;
ensure_dir_created_or_die($target_dir);
open(my $out, ">:encoding(UTF-8)", $target_file) or die "cannot open $target_file";
print $out $panel_json;
close($out);
$product_ref->{"knowledge_panels_" . $target_lc}{$panel_id} = {
"template" => $panel_template,
"json_error" => $json_decode_error,
"json" => $panel_json,
"json_debug_url" => $static_subdomain . $url
};
}
}
return;
}
=head2 extract_data_from_impact_estimator_best_recipe ($product_ref, $panel_data_ref)
The impact estimator adds a lot of data to products. This function extracts the data we need to display knowledge panels.
=cut
sub extract_data_from_impact_estimator_best_recipe ($product_ref, $panel_data_ref) {
# Copy data from product data (which format may change) to panel data to make it easier to use in the template
$panel_data_ref->{climate_change}
= $product_ref->{environmental_score_extended_data}{impact}{likeliest_impacts}{Climate_change};
$panel_data_ref->{ef_score}
= $product_ref->{environmental_score_extended_data}{impact}{likeliest_impacts}{EF_single_score};
# Compute the index of the recipe with the maximum confidence
my $max_confidence = 0;
my $max_confidence_index;
my $i = 0;
foreach my $confidence (@{$product_ref->{environmental_score_extended_data}{impact}{confidence_score_distribution}})
{
if ($confidence > $max_confidence) {
$max_confidence_index = $i;
$max_confidence = $confidence;
}
$i++;
}
my $best_recipe_ref = $product_ref->{environmental_score_extended_data}{impact}{recipes}[$max_confidence_index];
# list ingredients for max confidence recipe, sorted by quantity
my @ingredients = ();
my @ingredients_by_quantity = sort {$best_recipe_ref->{$b} <=> $best_recipe_ref->{$a}} keys %{$best_recipe_ref};
foreach my $ingredient (@ingredients_by_quantity) {
push @ingredients,
{
id => $ingredient,
quantity => $best_recipe_ref->{$ingredient},
};
}
$product_ref->{environmental_score_extended_data}{impact}{max_confidence_recipe} = \@ingredients;
$panel_data_ref->{environmental_score_extended_data_more_precise_than_agribalyse}
= is_environmental_score_extended_data_more_precise_than_agribalyse($product_ref);
# TODO: compute the complete score, using Agribalyse impacts except for agriculture where we use the estimator impact
return;
}
=head2 compare_impact_estimator_data_to_category_average ($product_ref, $panel_data_ref, $target_cc)
gen_top_tags_per_country.pl computes stats for categories for nutrients, and now also for the
extended environmental_score impacts computed by the impact estimator.
For a specific product, this function finds the most specific category for which we have impact stats to compare with.
=cut
sub compare_impact_estimator_data_to_category_average ($product_ref, $panel_data_ref, $target_cc) {
# Comparison to other products
my $categories_nutriments_ref = $categories_nutriments_per_country{$target_cc};
if (defined $categories_nutriments_ref) {
foreach my $cid (reverse @{$product_ref->{categories_tags}}) {
if ( (defined $categories_nutriments_ref->{$cid})
and (defined $categories_nutriments_ref->{$cid}{nutriments})
and (defined $categories_nutriments_ref->{$cid}{nutriments}{climate_change}))
{
$panel_data_ref->{environmental_score_extended_data_for_category} = {
category_id => $cid,
climate_change => $categories_nutriments_ref->{$cid}{nutriments}{climate_change},
ef_score => $categories_nutriments_ref->{$cid}{nutriments}{ef_score},
};
last;
}
}
}
return;
}
=head2 create_environmental_score_panel ( $product_ref, $target_lc, $target_cc, $options_ref )
Creates a knowledge panel to describe the Environmental-Score, including sub-panels
for the different components of the Environmental-Score.
=head3 Arguments
=head4 product reference $product_ref
Loaded from the MongoDB database, Storable files, or the OFF API.
=head4 language code $target_lc
Returned attributes contain both data and strings intended to be displayed to users.
This parameter sets the desired language for the user facing strings.
=head4 country code $target_cc
The Environmental-Score depends on the country of the consumer (as the transport bonus/malus depends on it)
=cut
sub create_environmental_score_panel ($product_ref, $target_lc, $target_cc, $options_ref, $request_ref) {
$log->debug("create environmental_score panel",
{code => $product_ref->{code}, environmental_score_data => $product_ref->{environmental_score_data}})
if $log->is_debug();
my $cc = $request_ref->{cc};
# 2024/12: If we do not have yet environmental_score_data, we use ecoscore_data
# (or possibly for older revisions)
# TBD: remove this code once all products have been updated (but we won't show the score for old revisions)
if ((not defined $product_ref->{environmental_score_data}) and (defined $product_ref->{ecoscore_data})) {
$product_ref->{environmental_score_data} = $product_ref->{ecoscore_data};
}
if ( (defined $product_ref->{environmental_score_data})
and ($product_ref->{environmental_score_data}{status} eq "known"))
{
my $score = $product_ref->{environmental_score_data}{score};
my $grade = $product_ref->{environmental_score_data}{grade};
my $transportation_warning = undef;
if (defined $product_ref->{environmental_score_data}{scores}{$cc}) {
$score = $product_ref->{environmental_score_data}{scores}{$cc};
$grade = $product_ref->{environmental_score_data}{grades}{$cc};
if ($cc eq "world") {
$transportation_warning
= lang_in_other_lc($target_lc, "environmental_score_warning_transportation_world");
}
}
else {
$transportation_warning = lang_in_other_lc($target_lc, "environmental_score_warning_transportation");
}
$log->debug("create environmental_score panel - known",
{code => $product_ref->{code}, score => $score, grade => $grade})
if $log->is_debug();
# Agribalyse part of the Environmental-Score
my $agribalyse_category_name = $product_ref->{environmental_score_data}{agribalyse}{name_en};
if (defined $product_ref->{environmental_score_data}{agribalyse}{"name_" . $target_lc}) {
$agribalyse_category_name = $product_ref->{environmental_score_data}{agribalyse}{"name_" . $target_lc};
}
# Agribalyse grade
my $agribalyse_score = $product_ref->{environmental_score_data}{agribalyse}{score};
my $agribalyse_grade;
if ($agribalyse_score >= 90) {
$agribalyse_grade = "a-plus";
}
elsif ($agribalyse_score >= 75) {
$agribalyse_grade = "a";
}
elsif ($agribalyse_score >= 60) {
$agribalyse_grade = "b";
}
elsif ($agribalyse_score >= 45) {
$agribalyse_grade = "c";
}
elsif ($agribalyse_score >= 30) {
$agribalyse_grade = "d";
}
elsif ($agribalyse_score >= 15) {
$agribalyse_grade = "e";
}
else {
$agribalyse_grade = "f";
}
my $letter_grade = uc($grade); # A+, A, B, C, D, E, F
my $grade_underscore = $grade;
$grade_underscore =~ s/\-/_/; # a-plus -> a_plus
if ($grade eq "a-plus") {
$letter_grade = "A+";
}
my $agribalyse_letter_grade = uc($agribalyse_grade); # A+, A, B, C, D, E, F
my $agribalyse_grade_underscore = $agribalyse_grade;
$agribalyse_grade_underscore =~ s/\-/_/; # a-plus -> a_plus
if ($agribalyse_grade eq "a-plus") {
$agribalyse_letter_grade = "A+";
}
# cap the score to 100 as we display it /100
if ($score > 100) {
$score = 100;
}
if ($score < 0) {
$score = 0;
}
# We can reuse some strings from the Environmental-Score attribute
my $title = sprintf(lang_in_other_lc($target_lc, "attribute_environmental_score_grade_title"), $letter_grade);
my $subtitle
= lang_in_other_lc($target_lc, "attribute_environmental_score_" . $grade_underscore . "_description_short");
my $panel_data_ref = {
"agribalyse_category_name" => $agribalyse_category_name,
"agribalyse_score" => $agribalyse_score,
"agribalyse_grade" => $agribalyse_grade,
"agribalyse_grade_underscore" => $agribalyse_grade_underscore,
"agribalyse_letter_grade" => $agribalyse_letter_grade,
"name" => lang_in_other_lc($target_lc, "attribute_environmental_score_name"),
"score" => $score,
"grade" => $grade,
"grade_underscore" => $grade_underscore,
"letter_grade" => $letter_grade,
"title" => $title,
"subtitle" => $subtitle,
"transportation_warning" => $transportation_warning,
};
create_panel_from_json_template("environmental_score",
"api/knowledge-panels/environment/environmental_score/environmental_score.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
# Add an Agribalyse panel to show the impact of the different steps for the category on average
create_panel_from_json_template(
"environmental_score_agribalyse",
"api/knowledge-panels/environment/environmental_score/agribalyse.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref
);
create_panel_from_json_template("carbon_footprint",
"api/knowledge-panels/environment/carbon_footprint_food.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
# Add panels for the different bonuses and maluses
foreach my $adjustment ("production_system", "origins_of_ingredients", "threatened_species", "packaging") {
my $adjustment_panel_data_ref = {};
create_panel_from_json_template(
"environmental_score_" . $adjustment,
"api/knowledge-panels/environment/environmental_score/" . $adjustment . ".tt.json",
$adjustment_panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref
);
}
# Add panel for the final Environmental-Score of the product
create_panel_from_json_template("environmental_score_total",
"api/knowledge-panels/environment/environmental_score/total.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
}
# Environmental-Score is not applicable
elsif ( (defined $product_ref->{environmental_score_grade})
and ($product_ref->{environmental_score_grade} eq "not-applicable"))
{
my $panel_data_ref = {};
$panel_data_ref->{subtitle} = f_lang_in_lc(
$target_lc,
"f_attribute_environmental_score_not_applicable_description",
{
category => display_taxonomy_tag_name(
$target_lc,
"categories",
deep_get(
$product_ref, qw/environmental_score_data environmental_score_not_applicable_for_category/
)
)
}
);
create_panel_from_json_template("environmental_score",
"api/knowledge-panels/environment/environmental_score/environmental_score_not_applicable.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
}
# Environmental-Score is unknown
else {
my $panel_data_ref = {};
create_panel_from_json_template("environmental_score",
"api/knowledge-panels/environment/environmental_score/environmental_score_unknown.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
}
# Add panels for environmental Environmental-Score labels
if ( (defined $product_ref->{environmental_score_data})
and (defined $product_ref->{environmental_score_data}{adjustments})
and (defined $product_ref->{environmental_score_data}{adjustments}{production_system})
and (defined $product_ref->{environmental_score_data}{adjustments}{production_system}{labels}))
{
foreach my $labelid (@{$product_ref->{environmental_score_data}{adjustments}{production_system}{labels}}) {
my $label_panel_data_ref = {
label => $labelid,
evaluation => "good",
};
# Add label icon
my $icon_url = get_tag_image($target_lc, "labels", $labelid);
if (defined $icon_url) {
$label_panel_data_ref->{icon_url} = $static_subdomain . $icon_url;
}
# Add properties of interest
foreach my $property (qw(environmental_benefits description)) {
my $property_value = get_inherited_property("labels", $labelid, $property . ":" . $target_lc);
if (!(defined $property_value) && ($target_lc ne "en")) {
# fallback to english
$property_value = get_inherited_property("labels", $labelid, $property . ":" . "en");
}
if (defined $property_value) {
$label_panel_data_ref->{$property} = $property_value;
}
}
create_panel_from_json_template(
"environment_label_" . $labelid,
"api/knowledge-panels/environment/label.tt.json",
$label_panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref
);
}
}
return;
}
=head2 create_environment_card_panel ( $product_ref, $target_lc, $target_cc, $options_ref )
Creates a knowledge panel card that contains all knowledge panels related to the environment.
Created for all products (with at least a packaging panel).
=head3 Arguments
=head4 product reference $product_ref
Loaded from the MongoDB database, Storable files, or the OFF API.
=head4 language code $target_lc
Returned attributes contain both data and strings intended to be displayed to users.
This parameter sets the desired language for the user facing strings.
=head4 country code $target_cc
The Environmental-Score depends on the country of the consumer (as the transport bonus/malus depends on it)
=cut
sub create_environment_card_panel ($product_ref, $target_lc, $target_cc, $options_ref, $request_ref) {
$log->debug("create environment card panel", {code => $product_ref->{code}}) if $log->is_debug();
my $panel_data_ref = {};
# Create Environmental-Score related panels
if ($options{product_type} eq "food") {
create_environmental_score_panel($product_ref, $target_lc, $target_cc, $options_ref, $request_ref);
if (
(defined $product_ref->{environmental_score_data})
and (defined $product_ref->{environmental_score_data}{adjustments})
and (defined $product_ref->{environmental_score_data}{adjustments}{threatened_species})
and (defined $product_ref->{environmental_score_data}{adjustments}{threatened_species}{value}
&& $product_ref->{environmental_score_data}{adjustments}{threatened_species}{value} != 0)
)
{
create_panel_from_json_template("palm_oil", "api/knowledge-panels/environment/palm_oil.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
}
}
# Create panel for carbon footprint (non-food products, for food products, it is added by create_environmental_score_panel)
if ($options{product_type} ne "food") {
create_carbon_footprint_panel($product_ref, $target_lc, $target_cc, $options_ref);
}
# Create panel for packaging components, and packaging materials
create_panel_from_json_template("packaging_recycling",
"api/knowledge-panels/environment/packaging_recycling.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
create_panel_from_json_template("packaging_materials",
"api/knowledge-panels/environment/packaging_materials.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
create_panel_from_json_template("packaging_components",
"api/knowledge-panels/environment/packaging_components.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
# Create panel for manufacturing place
create_manufacturing_place_panel($product_ref, $target_lc, $target_cc, $options_ref);
# Origins of ingredients for the environment card, for food, pet food and beauty products
if (feature_enabled("ingredients")) {
create_panel_from_json_template("origins_of_ingredients",
"api/knowledge-panels/environment/origins_of_ingredients.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
}
# Create the environment_card panel
$panel_data_ref->{packaging_image} = data_to_display_image($product_ref, "packaging", $target_lc);
create_panel_from_json_template("environment_card", "api/knowledge-panels/environment/environment_card.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
return 1;
}
=head2 create_secondhand_card_panel ( $product_ref, $target_lc, $target_cc, $options_ref )
Creates a knowledge panel card that contains all knowledge panels related to the circular economy:
- sharing, buying, selling etc.
Created for products in specific categories, for users in specific countries.
=head3 Arguments
=head4 product reference $product_ref
Loaded from the MongoDB database, Storable files, or the OFF API.
=head4 language code $target_lc
Returned attributes contain both data and strings intended to be displayed to users.
This parameter sets the desired language for the user facing strings.
=head4 country code $target_cc
Used to select secondhand options (e.g. classified ads sites) that are relevant for the user.
=cut
sub create_secondhand_card_panel ($product_ref, $target_lc, $target_cc, $options_ref, $request_ref) {
$log->debug("create secondhand card panel", {code => $product_ref->{code}}) if $log->is_debug();
my $panel_data_ref = {};
# Only available for the product_type "product"
if ($options{product_type} ne "product") {
return 0;
}
# Add the name of the most specific category (last in categories_hierarchy) to the panel data
my $category_id = $product_ref->{categories_hierarchy}[-1];
$panel_data_ref->{category_name} = display_taxonomy_tag_name($target_lc, "categories", $category_id);
# Create paneld for donations
create_panel_from_json_template("donated_products_fr_geev",
"api/knowledge-panels/secondhand/donated_products_fr_geev.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
create_panel_from_json_template("donated_products", "api/knowledge-panels/secondhand/donated_products.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
# Created panels for buying used products
create_panel_from_json_template("used_products_fr_backmarket",
"api/knowledge-panels/secondhand/used_products_fr_backmarket.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
create_panel_from_json_template("used_products", "api/knowledge-panels/secondhand/used_products.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
# Create the secondhand_card panel
create_panel_from_json_template("secondhand_card", "api/knowledge-panels/secondhand/secondhand_card.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
return 1;
}
sub create_carbon_footprint_panel($product_ref, $target_lc, $target_cc, $options_ref) {
# Find the first category that has a carbon_impact_fr_impactco2:en: property
my ($value, $category_id)
= get_inherited_property_from_categories_tags($product_ref, "carbon_impact_fr_impactco2:en");
$log->debug("create carbon footprint panel",
{code => $product_ref->{code}, category_id => $category_id, value => $value})
if $log->is_debug();
if (defined $value) {
my $panel_data_ref = {
category_id => $category_id,
category_name => display_taxonomy_tag_name($target_lc, "categories", $category_id),
co2_kg_per_unit => $value,
unit_name => get_property_with_fallbacks("categories", $category_id, "unit_name:$target_lc"),
link => get_property("categories", $category_id, "carbon_impact_fr_impactco2_link:en"),
};
create_panel_from_json_template("carbon_footprint",
"api/knowledge-panels/environment/carbon_footprint_product.tt.json",
$panel_data_ref, $product_ref, $target_lc, $target_cc, $options_ref);
}
return;
}
=head2 create_manufacturing_place_panel ( $product_ref, $target_lc, $target_cc, $options_ref )
Creates a knowledge panel when we know the location of the manufacturing place,
usually through a packaging code.
=head3 Arguments
=head4 product reference $product_ref
Loaded from the MongoDB database, Storable files, or the OFF API.
=head4 language code $target_lc
Returned attributes contain both data and strings intended to be displayed to users.
This parameter sets the desired language for the user facing strings.
=head4 country code $target_cc
The Environmental-Score depends on the country of the consumer (as the transport bonus/malus depends on it)
=cut
sub create_manufacturing_place_panel ($product_ref, $target_lc, $target_cc, $options_ref) {
$log->debug("create_manufacturing_place_panel", {code => $product_ref->{code}}) if $log->is_debug();
# Go through the product packaging codes, keep the first one with associated geo coordinates