#12267 change scan flow

This commit is contained in:
nikitateplyakov
2019-02-11 18:21:52 +08:00
parent d499269940
commit 5975252e8c
13 changed files with 334 additions and 83 deletions

View File

@@ -1,5 +1,6 @@
import 'package:checker/base/base_screen.dart';
import 'package:checker/db.dart';
import 'package:checker/screens/purchase_sum.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
@@ -14,13 +15,16 @@ import 'package:checker/network.dart';
import 'package:checker/base/base_state.dart';
import 'package:checker/screens/purchase_success.dart';
typedef PurchaseResponseCallback = void Function(Map, String, String);
/// Экран проведения покупки.
class PurchaseScreen extends BaseScreen {
PurchaseScreen(helper, app, this.user, this.card) : super(helper, app);
PurchaseScreen(helper, app, this.user, this.card, this.sum) : super(helper, app);
final String user;
final String card;
final String sum;
@override
State createState() => new PurchaseScreenState<PurchaseScreen>(helper, app, user, card);
@@ -30,7 +34,7 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
/// Объект, помогающий вручную изменять введенный пользователем текст.
/// Используется для форматирования введенных пользователем данных
/// (удаляет запрещенные символы до их отображаения).
TextEditingController controller = new TextEditingController();
TextEditingController controller;
TextEditingController bonusController = new TextEditingController();
@@ -43,6 +47,7 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
@override
void initState() {
controller = new TextEditingController(text: widget.sum ?? "");
loading = true;
requestAsyncData(user);
buildFocusNode();
@@ -116,9 +121,9 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
widgetList.add(wrapButton(
getScreenMargins(24.0),
getScanButton(
getCancelScanButton(
context,
StringsLocalization.scan(),
StringsLocalization.cancel(),
Resources.getPrimaryColor(app)
)
));
@@ -185,12 +190,12 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
StringsLocalization.completePurchase(), () => onPurchaseClick());
}
Widget getScanButton(BuildContext context, String title, Color textColor) {
Widget getCancelScanButton(BuildContext context, String title, Color textColor) {
return new Container(
height: buttonHeight,
child: new FlatButton(
child: new Text(title, style: new TextStyle(color: textColor)),
onPressed: () => restartScanner()),
onPressed: () => restartFlow()),
decoration: new BoxDecoration(
border: new Border.all(
color: Resources.getButtonColor(app), width: 1.0),
@@ -249,8 +254,8 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
loading = false;
this.coupons = coupons['results'];
this.loyalityType = loyality['type'];
setBonuses(loyality, showBonus);
});
setBonuses(loyality, showBonus);
}
}
@@ -293,16 +298,26 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
}
onPurchaseClick() {
String val = _parseSum(controller.text);
purchase(val, false, _showPrecalculatedValues);
}
void _showPrecalculatedValues(Map response, String sumTotal, String token) {
String val = _parseSum(controller.text);
helper.getCurrency().then((currency) {
print(currency.toString());
final String totalAmount = response['sum_total'];
final String totalDiscount = response['sum_discount'];
final String discount = (response['discount'] as int).toString();
print(response);
showDialog(
context: context,
builder: (_) => new AlertDialog(
builder: (_) =>
new AlertDialog(
title: new Text(StringsLocalization.confirmation()),
content:
new Text(
StringsLocalization.confirmPurchase(val, currency)
content: Text(
StringsLocalization.purchaseDetails(totalAmount,
totalDiscount, discount, currency)
),
actions: <Widget>[
new FlatButton(
@@ -315,13 +330,42 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
child: new Text(StringsLocalization.yes()),
onPressed: () {
Navigator.of(context).pop();
purchase(val);
purchase(val, true, _paymentConfirmed);
},
)
]));
});
}
void _paymentConfirmed(Map purchase, String sumTotal, String token) async {
var couponsResponse;
try {
couponsResponse = await getCouponsRequest(purchase['coupons_url'], token);
print(couponsResponse.body);
} catch(error) {
purchaseInProgress = false;
print(error.toString());
}
Map coupons = json.decode(couponsResponse.body);
new Future.delayed(const Duration(milliseconds: 200), () {
print('show purchase success!');
var route = new MaterialPageRoute<String>(builder: (BuildContext context) => new PurchaseSuccessScreen(
sumTotal,
user['first_name'] == null ? '' : user['first_name'],
helper,
app,
purchase,
coupons['results']
), fullscreenDialog: true);
Navigator.of(context).push(route).then((token) {
Navigator.of(context).pop(token);
});
});
}
apiErrorAlert(String errorText) {
showDialog(
context: context,
@@ -339,13 +383,13 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
);
}
purchase(String sumTotal) async {
purchase(String sumTotal, bool commit, PurchaseResponseCallback callback) async {
setState(() {
loading = true;
});
if (await platform.invokeMethod('isOnline')) {
if (!purchaseInProgress) {
purchaseInProgress = true;
purchaseInProgress = commit;
String token = await helper.getToken();
var result = await helper.getMerchantID();
@@ -361,10 +405,13 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
var body = {
'doc_id': result,
'curr_iso_code': currency.toString(),
'commit': 'true',
'sum_total': sumTotal,
};
if(commit) {
body['commit'] = 'true';
}
if (bonusController.text.length > 0) {
body['bonus_payment'] = bonusController.text;
}
@@ -392,32 +439,7 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
purchaseInProgress = false;
apiErrorAlert(errors[0]);
} else {
var couponsResponse;
try {
couponsResponse = await getCouponsRequest(purchase['coupons_url'], token);
print(couponsResponse.body);
} catch(error) {
purchaseInProgress = false;
print(error.toString());
}
Map coupons = json.decode(couponsResponse.body);
new Future.delayed(const Duration(milliseconds: 200), () {
print('show purchase success!');
var route = new MaterialPageRoute<String>(builder: (BuildContext context) => new PurchaseSuccessScreen(
sumTotal,
user['first_name'] == null ? '' : user['first_name'],
helper,
app,
purchase,
coupons['results']
), fullscreenDialog: true);
Navigator.of(context).push(route).then((token) {
Navigator.of(context).pop(token);
});
});
callback(purchase, sumTotal, token);
}
}
}
@@ -426,24 +448,47 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
void setBonuses(Map bonuses, bool showBonus) {
print('loyalityType ' + this.loyalityType);
if (bonuses['type'] == 'amount') {
this.loyalty = '${user['discount']}%';
setState(() => this.loyalty = '${user['discount']}%');
} else {
double loyaltyVal = (double.parse(bonuses['amount_to_bonus'][1]) /
bonuses['amount_to_bonus'][0]) * 100;
this.loyalty = '${loyaltyVal.toStringAsFixed(0)}%';
setState(() => this.loyalty = '${loyaltyVal.toStringAsFixed(0)}%');
}
if (showBonus && (this.loyalityType == 'bonus')) {
this.bonus = '${user['bonus']}';
setState(() => this.bonus = '${user['bonus']}');
}
print('loyalty ' + this.loyalty);
print('bonus ' + this.bonus);
}
restartScanner() {
helper.getToken().then((token) {
Navigator.of(context).pop(token);
});
restartFlow() {
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text(StringsLocalization.cancelDialog()),
actions: <Widget>[
new FlatButton(
child: new Text(StringsLocalization.no()),
onPressed: () {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text(StringsLocalization.yes()),
onPressed: () {
Navigator.of(context).pop();
helper.getToken().then((token) {
Navigator.pushAndRemoveUntil(context,
MaterialPageRoute(builder: (context) =>
PurchaseSumScreen(widget.helper, widget.app, token)),
(route) => false);
});
},
)
],
)
);
}
FocusNode bonusFocusNode = new FocusNode();
@@ -456,25 +501,14 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
sumFocusNode.addListener(() {
setState(() {
if (sumFocusNode.hasFocus && bonusFocusNode.hasFocus) {
bonusFocusNode.unfocus();
}
if (sumFocusNode.hasFocus) {
scrollController.animateTo(pos, duration: new Duration(seconds: 1), curve: Curves.ease);
sumFocusNode.unfocus();
}
});
});
bonusFocusNode.addListener(() {
setState(() {
if (bonusFocusNode.hasFocus && sumFocusNode.hasFocus) {
sumFocusNode.unfocus();
}
if (bonusFocusNode.hasFocus) {
scrollController.animateTo(pos, duration: new Duration(seconds: 1), curve: Curves.ease);
}