Упрощена работа с локалью, базовый url и токен приложения вынесены в build.gradle, добавлен конфиг для разработки и тестирования, исправлена проблема с переходом на экран сканера если локаль не выбиралась в настройках
This commit is contained in:
@@ -14,17 +14,16 @@ import 'package:checker/screens/purchase_success.dart';
|
||||
|
||||
/// Экран проведения покупки.
|
||||
class PurchaseScreen extends StatefulWidget {
|
||||
|
||||
PurchaseScreen(this.user, this.card);
|
||||
|
||||
final String user;
|
||||
final String card;
|
||||
|
||||
@override State createState() => new PurchaseScreenState<PurchaseScreen>(user, card);
|
||||
@override
|
||||
State createState() => new PurchaseScreenState<PurchaseScreen>(user, card);
|
||||
}
|
||||
|
||||
class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
|
||||
/// Объект, помогающий вручную изменять введенный пользователем текст.
|
||||
/// Используется для форматирования введенных пользователем данных
|
||||
/// (удаляет запрещенные символы до их отображаения).
|
||||
@@ -35,7 +34,8 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
this.card = card;
|
||||
}
|
||||
|
||||
@override Widget build(BuildContext ctx) {
|
||||
@override
|
||||
Widget build(BuildContext ctx) {
|
||||
if (helper == null) {
|
||||
helper = new SqliteHelper();
|
||||
helper.open().then((_) {
|
||||
@@ -43,7 +43,7 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
platform.invokeMethod('getFlavor').then((flavor) {
|
||||
app = flavor;
|
||||
setState(() {
|
||||
getLoyalty(user['loyalty_url']);
|
||||
requestLoyalty(user['loyalty_url']);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -57,17 +57,24 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
String card = '';
|
||||
String loyalty = '';
|
||||
|
||||
@override Widget getScreenContent() {
|
||||
return new Column(
|
||||
children: <Widget>[new Expanded(child: new ListView(children: <Widget>[
|
||||
getValueWithDescription(StringsLocalization.buyer(), user['first_name'] == null ? '' : user['first_name']),
|
||||
getValueWithDescription(StringsLocalization.card(), card),
|
||||
getValueWithDescription(StringsLocalization.reward(), loyalty),
|
||||
getHintLabel(),
|
||||
getInputField(),
|
||||
wrapButton(getScreenMargins(36.0), getCompleteButton()),
|
||||
wrapButton(getScreenMargins(24.0), getScanButton(context, StringsLocalization.scan(), Resources.getPrimaryColor(app)))
|
||||
]))]);
|
||||
@override
|
||||
Widget getScreenContent() {
|
||||
return new Column(children: <Widget>[
|
||||
new Expanded(
|
||||
child: new ListView(children: <Widget>[
|
||||
getValueWithDescription(StringsLocalization.buyer(),
|
||||
user['first_name'] == null ? '' : user['first_name']),
|
||||
getValueWithDescription(StringsLocalization.card(), card),
|
||||
getValueWithDescription(StringsLocalization.reward(), loyalty),
|
||||
getHintLabel(),
|
||||
getInputField(),
|
||||
wrapButton(getScreenMargins(36.0), getCompleteButton()),
|
||||
wrapButton(
|
||||
getScreenMargins(24.0),
|
||||
getScanButton(context, StringsLocalization.scan(),
|
||||
Resources.getPrimaryColor(app)))
|
||||
]))
|
||||
]);
|
||||
}
|
||||
|
||||
getScreenMargins(double top) {
|
||||
@@ -76,37 +83,39 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
}
|
||||
|
||||
getCompleteButton() {
|
||||
return buildRaisedButton(StringsLocalization.completePurchase(), () => onPurchaseClick());
|
||||
return buildRaisedButton(
|
||||
StringsLocalization.completePurchase(), () => onPurchaseClick());
|
||||
}
|
||||
|
||||
Widget getScanButton(BuildContext context, String title, Color textColor) {
|
||||
return new Container(
|
||||
height: buttonHeight,
|
||||
child: new FlatButton(
|
||||
child: new Text(
|
||||
title,
|
||||
style: new TextStyle(color: textColor)),
|
||||
child: new Text(title, style: new TextStyle(color: textColor)),
|
||||
onPressed: () => startScanner(context, app, helper)),
|
||||
decoration: new BoxDecoration(
|
||||
border: new Border.all(color: Resources.getButtonColor(app), width: 1.0),
|
||||
border: new Border.all(
|
||||
color: Resources.getButtonColor(app), width: 1.0),
|
||||
borderRadius: new BorderRadius.all(new Radius.circular(4.0))));
|
||||
}
|
||||
|
||||
@override String getTitle() {
|
||||
@override
|
||||
String getTitle() {
|
||||
return StringsLocalization.carryingPurchase();
|
||||
}
|
||||
|
||||
@override getHintString() {
|
||||
@override
|
||||
getHintString() {
|
||||
return StringsLocalization.sum();
|
||||
}
|
||||
|
||||
@override getTextWidget() {
|
||||
@override
|
||||
getTextWidget() {
|
||||
return new TextField(
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: new InputDecoration.collapsed(
|
||||
hintText: getHintString(),
|
||||
hintStyle: new TextStyle(color: greyTextColor, fontSize: 16.0)
|
||||
),
|
||||
hintStyle: new TextStyle(color: greyTextColor, fontSize: 16.0)),
|
||||
controller: controller,
|
||||
onSubmitted: (String text) {
|
||||
setState(() {
|
||||
@@ -118,33 +127,11 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
getLoyalty(String url) async {
|
||||
|
||||
requestLoyalty(String url) async {
|
||||
if (await platform.invokeMethod('isOnline')) {
|
||||
|
||||
String token = await helper.getToken();
|
||||
String locale = await helper.getLocale();
|
||||
|
||||
var headers = {
|
||||
'DM-Authorization': 'dmapptoken $appToken',
|
||||
'Authorization': 'dmtoken ${token}',
|
||||
'Accept-Language': locale
|
||||
};
|
||||
|
||||
httpClient.get(url, headers: headers).then((response) {
|
||||
|
||||
print(response.body);
|
||||
|
||||
Map bonuses = JSON.decode(response.body);
|
||||
String type = bonuses['type'];
|
||||
getLoyaltyRequest(url, helper).then((response) {
|
||||
setState(() {
|
||||
if (type == 'amount') {
|
||||
this.loyalty = '${user['discount']}%';
|
||||
} else {
|
||||
List amountToBonus = bonuses['amount_to_bonus'];
|
||||
double loyaltyVal = (double.parse(amountToBonus[1]) / amountToBonus[0]) * 100;
|
||||
this.loyalty = '${loyaltyVal.toStringAsFixed(0)}%';
|
||||
}
|
||||
setBonuses(JSON.decode(response.body));
|
||||
});
|
||||
}).catchError((error) {
|
||||
print(error.toString());
|
||||
@@ -152,15 +139,15 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Переделать? чтобы работало хорошо
|
||||
String _cleanupNumber(String text){
|
||||
// TODO: Переделать, если потребуется
|
||||
String _cleanupNumber(String text) {
|
||||
String tmp = text
|
||||
.replaceAll(' ', '')
|
||||
.replaceAll('-', '')
|
||||
.replaceAll(',', '.')
|
||||
.replaceAll('..', '.');
|
||||
|
||||
while(tmp.indexOf('..') != -1){
|
||||
while (tmp.indexOf('..') != -1) {
|
||||
tmp = tmp.replaceAll('..', '.');
|
||||
}
|
||||
return tmp;
|
||||
@@ -172,17 +159,17 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
|
||||
try {
|
||||
sumTotal = num.parse(text);
|
||||
} catch(exception) {
|
||||
} catch (exception) {
|
||||
print(exception);
|
||||
try {
|
||||
int idx = text.indexOf('.');
|
||||
String integerPart = text.substring(0, idx);
|
||||
String fractionalPart = text.substring(idx + 1, text.length);
|
||||
if(fractionalPart.length > 2) {
|
||||
if (fractionalPart.length > 2) {
|
||||
fractionalPart = fractionalPart.substring(0, 2);
|
||||
}
|
||||
return '${integerPart}.${fractionalPart}';
|
||||
} catch(exception){
|
||||
} catch (exception) {
|
||||
print(exception);
|
||||
}
|
||||
}
|
||||
@@ -193,23 +180,26 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
String val = _parseSum(controller.text);
|
||||
helper.getCurrency().then((currency) {
|
||||
print(currency.toString());
|
||||
showDialog(context: context, child: new AlertDialog(
|
||||
title: new Text(StringsLocalization.confirmation()),
|
||||
content: new Text(StringsLocalization.confirmPurchase(val, currency)),
|
||||
actions: <Widget>[
|
||||
new FlatButton(
|
||||
child: new Text(StringsLocalization.no()),
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
new FlatButton(
|
||||
child: new Text(StringsLocalization.yes()),
|
||||
onPressed: () {
|
||||
purchase(val);
|
||||
},
|
||||
)
|
||||
]));
|
||||
showDialog(
|
||||
context: context,
|
||||
child: new AlertDialog(
|
||||
title: new Text(StringsLocalization.confirmation()),
|
||||
content:
|
||||
new Text(StringsLocalization.confirmPurchase(val, currency)),
|
||||
actions: <Widget>[
|
||||
new FlatButton(
|
||||
child: new Text(StringsLocalization.no()),
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
new FlatButton(
|
||||
child: new Text(StringsLocalization.yes()),
|
||||
onPressed: () {
|
||||
purchase(val);
|
||||
},
|
||||
)
|
||||
]));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -219,11 +209,7 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
purchaseInProgress = true;
|
||||
|
||||
String token = await helper.getToken();
|
||||
String locale = await helper.getLocale();
|
||||
helper.getMerchantID().then((result) {
|
||||
|
||||
String url = user['purchases_url'];
|
||||
|
||||
helper.getCurrency().then((currency) {
|
||||
var body = {
|
||||
'doc_id': result,
|
||||
@@ -232,14 +218,8 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
'sum_total': sumTotal
|
||||
};
|
||||
|
||||
var headers = {
|
||||
'DM-Authorization': 'dmapptoken $appToken',
|
||||
'Authorization': 'dmtoken ${token}',
|
||||
'Accept-Language': locale
|
||||
};
|
||||
|
||||
httpClient.post(url, body: body, headers: headers).then((response) {
|
||||
|
||||
getPurchaseRequest(user['purchases_url'], body, token)
|
||||
.then((response) {
|
||||
print(response.body);
|
||||
Map parsedMap = JSON.decode(response.body);
|
||||
|
||||
@@ -247,11 +227,18 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
|
||||
if (parsedMap.containsKey('errors')) {
|
||||
List<String> errors = parsedMap['errors'];
|
||||
Scaffold.of(context).showSnackBar(new SnackBar(content: new Text(errors[0])));
|
||||
Scaffold
|
||||
.of(context)
|
||||
.showSnackBar(new SnackBar(content: new Text(errors[0])));
|
||||
} else {
|
||||
pushRouteReplacement(context, new PurchaseSuccessScreen(sumTotal, user['first_name'] == null ? '' : user['first_name'], helper, app));
|
||||
pushRouteReplacement(
|
||||
context,
|
||||
new PurchaseSuccessScreen(
|
||||
sumTotal,
|
||||
user['first_name'] == null ? '' : user['first_name'],
|
||||
helper,
|
||||
app));
|
||||
}
|
||||
|
||||
}).catchError((error) {
|
||||
purchaseInProgress = false;
|
||||
print(error.toString());
|
||||
@@ -261,4 +248,14 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setBonuses(Map bonuses) {
|
||||
if (bonuses['type'] == 'amount') {
|
||||
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)}%';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user