Skip to content

Commit

Permalink
feat: openfoodfacts#954 - actually saves nutrients on the BE and refr…
Browse files Browse the repository at this point in the history
…eshes the local DB

Please run some tests on DEV env to limit the potential impact on PROD!

New file:
* `rainforest-alliance.90x90.svg`: unrelated asset cache refresh

Impacted files:
* `knowledge_panels_builder.dart`: added an optional callback for page refresh after data saving; calls that callback after saving nutrients
* `new_product_page.dart`: added a callback parameter for page refresh
* `nutrition_page_loaded.dart`: actually saves the nutrients on the BE and refreshes the local database
  • Loading branch information
monsieurtanuki committed Feb 12, 2022
1 parent 376d826 commit 6651e8b
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 26 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ import 'package:smooth_app/widgets/loading_dialog.dart';
///
/// Panels display large data like all health data or environment data.
class KnowledgePanelsBuilder {
const KnowledgePanelsBuilder();
const KnowledgePanelsBuilder({this.setState});

/// Would for instance refresh the product page.
final VoidCallback? setState;

/// Builds all panels.
///
Expand Down Expand Up @@ -120,15 +123,18 @@ class KnowledgePanelsBuilder {
await LoadingDialog.error(context: context);
return;
}
await Navigator.push<Widget>(
final bool? refreshed = await Navigator.push<bool>(
context,
MaterialPageRoute<Widget>(
MaterialPageRoute<bool>(
builder: (BuildContext context) => NutritionPageLoaded(
product,
orderedNutrients,
),
),
);
if (refreshed ?? false) {
setState?.call();
}
// TODO(monsieurtanuki): refresh the data if changed
},
),
Expand Down
4 changes: 3 additions & 1 deletion packages/smooth_app/lib/pages/product/new_product_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,9 @@ class _ProductPageState extends State<ProductPage> {
List<Widget> knowledgePanelWidgets = <Widget>[];
if (snapshot.hasData) {
// Render all KnowledgePanels
knowledgePanelWidgets = const KnowledgePanelsBuilder().buildAll(
knowledgePanelWidgets =
KnowledgePanelsBuilder(setState: () => setState(() {}))
.buildAll(
snapshot.data!,
product: _product,
context: context,
Expand Down
82 changes: 60 additions & 22 deletions packages/smooth_app/lib/pages/product/nutrition_page_loaded.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import 'package:openfoodfacts/model/OrderedNutrient.dart';
import 'package:openfoodfacts/model/OrderedNutrients.dart';
import 'package:openfoodfacts/openfoodfacts.dart';
import 'package:openfoodfacts/utils/UnitHelper.dart';
import 'package:provider/provider.dart';
import 'package:smooth_app/database/dao_product.dart';
import 'package:smooth_app/database/local_database.dart';
import 'package:smooth_app/database/product_query.dart';
import 'package:smooth_app/generic_lib/buttons/smooth_action_button.dart';
import 'package:smooth_app/generic_lib/dialogs/smooth_alert_dialog.dart';
Expand Down Expand Up @@ -84,6 +87,7 @@ class _NutritionPageLoadedState extends State<NutritionPageLoaded> {
@override
Widget build(BuildContext context) {
final AppLocalizations appLocalizations = AppLocalizations.of(context)!;
final LocalDatabase localDatabase = context.read<LocalDatabase>();
final List<Widget> children = <Widget>[];
children.add(_switchNoNutrition(appLocalizations));
if (!_unspecified) {
Expand All @@ -100,7 +104,10 @@ class _NutritionPageLoadedState extends State<NutritionPageLoaded> {
}
children.add(_addNutrientButton(appLocalizations));
}
children.add(_addCancelSaveButtons(appLocalizations));
children.add(_addCancelSaveButtons(
appLocalizations,
localDatabase,
));

return Scaffold(
appBar: AppBar(title: Text(appLocalizations.nutrition_page_title)),
Expand Down Expand Up @@ -434,7 +441,11 @@ class _NutritionPageLoadedState extends State<NutritionPageLoaded> {
label: Text(appLocalizations.nutrition_page_add_nutrient),
);

Widget _addCancelSaveButtons(final AppLocalizations appLocalizations) => Row(
Widget _addCancelSaveButtons(
final AppLocalizations appLocalizations,
final LocalDatabase localDatabase,
) =>
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expand All @@ -447,14 +458,14 @@ class _NutritionPageLoadedState extends State<NutritionPageLoaded> {
if (!_formKey.currentState!.validate()) {
return;
}
await _save();
await _save(localDatabase);
},
child: Text(appLocalizations.save),
),
],
);

Future<void> _save() async {
Future<void> _save(final LocalDatabase localDatabase) async {
final Map<String, dynamic> map = <String, dynamic>{};
String? servingSize;
for (final String key in _controllers.keys) {
Expand All @@ -473,28 +484,24 @@ class _NutritionPageLoadedState extends State<NutritionPageLoaded> {
}
}
final Nutriments nutriments = Nutriments.fromJson(map);
widget.product.nutriments =
nutriments; // TODO(monsieurtanuki): here we impact directly the product share with the previous screen, not nice!
widget.product.servingSize = servingSize;

final Status? status = await LoadingDialog.run<Status>(
future: Future<Status>.delayed(const Duration(seconds: 2), () => Status()
/* TODO(monsieurtanuki): put back the actual call
OpenFoodAPIClient.saveProduct(
ProductQuery.getUser(),
widget.product,
*/
),
// minimal product: we only want to save the nutrients
final Product inputProduct = Product(
barcode: widget.product.barcode,
nutriments: nutriments,
servingSize: servingSize,
);

final bool? savedAndRefreshed = await LoadingDialog.run<bool>(
future: _saveAndRefresh(inputProduct, localDatabase),
context: context,
title: '${AppLocalizations.of(context)!.nutrition_page_update_running}'
' (in fact just waiting 2 seconds)',
title: AppLocalizations.of(context)!.nutrition_page_update_running,
);
if (status == null) {
if (savedAndRefreshed == null) {
// probably the end user stopped the dialog
return;
}
if (status.error != null) {
await LoadingDialog.error(context: context, title: status.error);
if (!savedAndRefreshed) {
await LoadingDialog.error(context: context);
return;
}
await showDialog<void>(
Expand All @@ -508,6 +515,37 @@ class _NutritionPageLoadedState extends State<NutritionPageLoaded> {
],
),
);
Navigator.of(context).pop();
Navigator.of(context).pop(true);
}

/// Saves a product on the BE and refreshes the local database
Future<bool> _saveAndRefresh(
final Product inputProduct,
final LocalDatabase localDatabase,
) async {
try {
final Status status = await OpenFoodAPIClient.saveProduct(
ProductQuery.getUser(),
inputProduct,
);
if (status.error != null) {
return false;
}
final ProductQueryConfiguration configuration = ProductQueryConfiguration(
inputProduct.barcode!,
fields: ProductQuery.fields,
language: ProductQuery.getLanguage(),
country: ProductQuery.getCountry(),
);
final ProductResult result =
await OpenFoodAPIClient.getProduct(configuration);
if (result.product != null) {
await DaoProduct(context.read<LocalDatabase>()).put(result.product!);
return true;
}
} catch (e) {
//
}
return false;
}
}

0 comments on commit 6651e8b

Please sign in to comment.