From ff0573d65d9db99cb319a82302f8f918710f0fd8 Mon Sep 17 00:00:00 2001 From: Ivan Murashov Date: Mon, 24 Jul 2017 19:45:04 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9D=D0=B5=D0=B1=D0=BE=D0=BB=D1=8C=D1=88?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/activate_token.dart | 83 ++++++++++++++++++++--------------------- lib/main.dart | 5 +-- lib/purchase.dart | 4 ++ lib/registration.dart | 50 +++++++++---------------- lib/splash.dart | 14 +++---- 5 files changed, 69 insertions(+), 87 deletions(-) diff --git a/lib/activate_token.dart b/lib/activate_token.dart index bfc10a1..d3f5b58 100644 --- a/lib/activate_token.dart +++ b/lib/activate_token.dart @@ -11,12 +11,12 @@ class FinishRegistrationScreen extends StatefulWidget { class _RegistrationScreenState extends BaseState { - bool _tokenActive = true; + bool _tokenActive = false; String _merchantID = ''; _RegistrationScreenState() { if (textFieldValue == "") { - _getSavedMerchantID(); + getSavedMerchantID(); } } @@ -37,17 +37,39 @@ class _RegistrationScreenState extends BaseState { getLogo(), getHintLabel(), getDecoratedTextWidget(), - _getMessage(), + getMessage(), buildButton(new EdgeInsets.only(top: 36.0, left: buttonVerticalMargin, right: buttonVerticalMargin), - buildRaisedButton(context, _tokenActive ? 'ЗАВЕРШИТЬ РЕГИСТРАЦИЮ' : 'ОБНОВИТЬ СТАТУС АКТИВАЦИИ',() => startScanner(context))) + buildRaisedButton(context, _tokenActive ? 'ЗАВЕРШИТЬ РЕГИСТРАЦИЮ' : 'ОБНОВИТЬ СТАТУС АКТИВАЦИИ', () => handleTap())) ]); } + handleTap() { + if (_tokenActive) { + startScanner(context); + } else { + checkToken(context).then((response) { + + print(response.body); + Map parsedMap = JSON.decode(response.body); + + // Обновить экран, заменить сообщение о необходимости активации токена, на сообщние о том, что токен активен. + setState(() { + _tokenActive = parsedMap['active']; + }); + + }).catchError((error) { + print(error.toString()); + return false; + }); + } + } + @override Widget getTextWidget() { return new Row(children: [new Text(_merchantID != null ? _merchantID : '', style: new TextStyle(color: Colors.black, fontSize: 16.0))]); } - _getSavedMerchantID() { + /// Достаем сохраненный в SharedPreferences merchantID. + getSavedMerchantID() { platform.invokeMethod('getMerchantID').then((result) { setState(() { _merchantID = result; @@ -56,54 +78,29 @@ class _RegistrationScreenState extends BaseState { }); } - _getMessage() { + /// Метод возвращает контейнер с текстом сообщения и бэкграундом. + getMessage() { return new Container(height: _tokenActive ? 72.0 : 108.0, decoration: _getDecoraionForMessageField(), margin: new EdgeInsets.only(top: 20.0, left: 12.0, right: 12.0), padding: new EdgeInsets.only(bottom: 22.0, left: 14.0, right: 14.0), - child: new Center(child: new Text(_getMessageText(), - textAlign: TextAlign.center, style: new TextStyle(height: 1.5, fontWeight: FontWeight.bold, fontSize: 14.0, color: _tokenActive ? tokenActiveTextColor : tokenActivateTextColor)))); + child: new Center(child: getMessageTextWidget())); } - _getMessageText() { + /// Метод возвращает виджет с текстом сообщения, всеми его привязками и стилями. + getMessageTextWidget() { + return new Text(getMessageString(), textAlign: TextAlign.center, + style: new TextStyle(height: 1.5, fontWeight: FontWeight.bold, fontSize: 14.0, + color: _tokenActive ? tokenActiveTextColor : tokenActivateTextColor)); + } + + /// Получаем текст сообщения, в зависимости от статуса активации. + getMessageString() { return _tokenActive ? 'Программа активирована' : 'Запрос на активацию программы отправлен, дождитесь подтверждения активации администратором'; } + /// Фоновое изображение для сообщения. Decoration _getDecoraionForMessageField() { return new BoxDecoration(image: new DecorationImage( image: new ExactAssetImage(_tokenActive ? active_token_bg_png : activate_token_bg_png), fit: _tokenActive ? BoxFit.fitWidth : BoxFit.fill)); } - - /// Метод возвращает кнопку, которая запускает отправку токена кассы на сервер. - _getButton(BuildContext context) { - double buttonHeight = 42.0; - double topMargin = 8.0; - return new Container(margin: new EdgeInsets.only(top: topMargin), height: buttonHeight, - child: new RaisedButton(child: new Text(, - style: new TextStyle(fontSize: 14.0, color: Colors.white)), - onPressed: () { - - startScanner(context); - - - // if (_tokenActive) { - // startScanner(context); - // } else { - // checkToken(context).then((response) { - - // print(response.body); - // Map parsedMap = JSON.decode(response.body); - - // // Обновить экран, заменить сообщение о необходимости активации токена, на сообщние о том, что токен активен. - // setState(() { - // _tokenActive = parsedMap['active']; - // }); - - // }).catchError((error) { - // print(error.toString()); - // return false; - // }); - // } - }, - color: primaryColor)); - } } \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index 0115fc9..da2e52e 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -28,14 +28,13 @@ const String active_token_bg_png = 'assets/active_token_message_background.png'; const Color primaryColor = const Color(0xffeb0004); const Color greyTextColor = const Color(0xffa5a5a5); const Color textBorderColor = const Color(0xffcfd8dc); -const Color textFieldBackground = const Color(0xffefefef); const Color tokenActiveTextColor = const Color(0xff1f5a1f); const Color tokenActivateTextColor = const Color(0xff4e3a19); const Color greenBackground = const Color(0xff8ae28a); // Dimens const double verticalMargin = 28.0; -const double buttonVerticalMargin = 64.0; +const double buttonVerticalMargin = 42.0; const double buttonHeight = 48.0; const double iconHeight = 20.0; @@ -81,7 +80,7 @@ startScanner(BuildContext context) async { logout(BuildContext context) { - String url = intUrl + 'tokens/' + 'khooi' + '?_dmapptoken=' + intToken; + String url = intUrl + 'tokens/' + token + '?_dmapptoken=' + intToken; print(url); httpClient.delete(url).then((response) { print(response.body); diff --git a/lib/purchase.dart b/lib/purchase.dart index 332ed01..2b9a021 100644 --- a/lib/purchase.dart +++ b/lib/purchase.dart @@ -14,6 +14,10 @@ class PurchaseScreen extends StatefulWidget { class PurchaseScreenState extends BaseState { + PurchaseScreenState() { + + } + String integerPart = '', fractionalPart = ''; @override String getTitle() { diff --git a/lib/registration.dart b/lib/registration.dart index 2df96ad..55e0efe 100644 --- a/lib/registration.dart +++ b/lib/registration.dart @@ -48,7 +48,7 @@ class _RegistrationScreenState extends BaseState { return textFieldValue.length > 0 && textFieldValue.length < 25; } - /// Показать индикатор, запросить токен. + /// Показать progressBar, запросить токен. _registerShop(BuildContext context) { setState(() { loading = true; @@ -56,14 +56,6 @@ class _RegistrationScreenState extends BaseState { }); } - /// Экран зависает на 1 сек, после этого выполняется переход на экран потверждения токена. - _registerDemo(BuildContext context) { - new Future.delayed(const Duration(milliseconds: 1000), () { - loading = false; - pushRoute(context, new FinishRegistrationScreen()); - }); - } - /// Получение от платформы id установки, формирование запроса на получение токена, сохранение токена. _register(BuildContext context) async { @@ -76,33 +68,27 @@ class _RegistrationScreenState extends BaseState { 'pos': pos, }; - pushRoute(context, new FinishRegistrationScreen()); - - // httpClient.post(url, body: body).then((response) { + httpClient.post(url, body: body).then((response) { setState(() { error = null; + loading = false; }); - // print(response.body); - // Map parsedMap = JSON.decode(response.body); - // setState(() { - // loading = false; - // }); - // if (response.statusCode == 201) { - // token = parsedMap['token']; - // platform.invokeMethod('saveToken', {'token' : token}); - // platform.invokeMethod('saveMerchantID', {'merchantID' : merchantID}); - // pushRoute(context, new FinishRegistrationScreen()); - // } else { - // setState(() { - // error = parsedMap['errors'][0]; - // }); - // } - // }).catchError((error) { - // setState(() { - // error = 'Отсутствует интернет соединение'; - // }); - // }); + print(response.body); + Map parsedMap = JSON.decode(response.body); + if (response.statusCode == 201) { + token = parsedMap['token']; + platform.invokeMethod('saveToken', {'token' : token}); + platform.invokeMethod('saveMerchantID', {'merchantID' : textFieldValue}); + pushRoute(context, new FinishRegistrationScreen()); + } else { + setState(() { + error = parsedMap['errors'][0]; + }); + } + }).catchError((error) { + print(error.toString()); + }); } } \ No newline at end of file diff --git a/lib/splash.dart b/lib/splash.dart index 3bb6419..ac8128f 100644 --- a/lib/splash.dart +++ b/lib/splash.dart @@ -12,28 +12,23 @@ class SplashScreen extends StatelessWidget { @override Widget build(BuildContext context) { - - // Splash скрин зависает мимнимум на 1 секунду. - // После этого начинается проверка токена. - new Future.delayed(const Duration(milliseconds: 1000), () { - pushRoute(context, new PurchaseScreen()); - // _showNextScreen(context); + // Появляется splash screen, проверяется токен. + new Future.delayed(const Duration(milliseconds: 500), () { + showNextScreen(context); }); return new Image.asset(splash_png, fit: BoxFit.cover); } /// Запуск следующего экрана приложения. - _showNextScreen(BuildContext context) async { + showNextScreen(BuildContext context) async { - const platform = const MethodChannel('com.dinect.checker/instance_id'); token = await platform.invokeMethod('getToken'); print('token: $token'); // В случае, если в приложении отсутствует токен, // необходимо запустить регистрацию кассы. - if (token == null) { pushRoute(context, new RegistrationScreen()); } else { @@ -41,6 +36,7 @@ class SplashScreen extends StatelessWidget { checkToken(context).then((response) { print(response.body); + Map parsedMap = JSON.decode(response.body); bool active = parsedMap['active'];