diff --git a/analysis_options.yaml b/analysis_options.yaml index 057b980..4d9f4ef 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,3 +1,27 @@ -analyzer: - enable-experiment: - - non-nullable \ No newline at end of file +include: package:lint/analysis_options.yaml + +# Not happy with the default? Customize the rules depending on your needs. +# Here are some examples: +linter: + rules: + # Make constructors the first thing in every class + sort_constructors_first: true + + # The new tabs vs. spaces. Choose wisely + prefer_single_quotes: true + prefer_double_quotes: false + + # Good packages document everything + public_member_api_docs: false + + # Blindly follow the Flutter code style, which prefers types everywhere + always_specify_types: false + + # Back to the 80s + lines_longer_than_80_chars: true + + # Use parameter order as in json response + always_put_required_named_parameters_first: true + + # Util classes are awesome! + avoid_classes_with_only_static_members: true \ No newline at end of file diff --git a/lib/core/entity/Category.dart b/lib/core/entity/Category.dart deleted file mode 100644 index 4ffbf0c..0000000 --- a/lib/core/entity/Category.dart +++ /dev/null @@ -1,38 +0,0 @@ -const String CategoryTableName = 'goods_category'; -const String CategoryColumnId = 'id'; -const String CategoryColumnParentIn = 'parent_id'; -const String CategoryColumnName = 'name'; -const String CategoryColumnAppCompanyId = 'app_company_id'; -const String CategoryColumnUpdatedAt = 'updated_at'; - -class Category { - int? id; - int? parentId; - String? name; - int? appCompanyId; - String? updatedAt; - - Map toMap() { - var map = { - CategoryColumnParentIn: parentId, - CategoryColumnName: name, - CategoryColumnAppCompanyId: appCompanyId, - CategoryColumnUpdatedAt: updatedAt, - }; - if (id != null) { - map[CategoryColumnId] = id; - } - return map; - } - - Category(); - - Category.fromMap(Map map) { - id = map[CategoryColumnId]; - parentId = map[CategoryColumnParentIn]; - name = map[CategoryColumnName]; - appCompanyId = map[CategoryColumnAppCompanyId]; - updatedAt = map[CategoryColumnUpdatedAt]; - } -} - diff --git a/lib/core/entity/Transaction.dart b/lib/core/entity/Transaction.dart deleted file mode 100644 index 72e31c0..0000000 --- a/lib/core/entity/Transaction.dart +++ /dev/null @@ -1,53 +0,0 @@ -const String TransactionTableName = 'transactions'; -const String TransactionColumnId = 'id'; -const String TransactionColumnUuid = 'uuid'; -const String TransactionColumnType = 'type'; -const String TransactionColumnStatus = 'status'; -const String TransactionColumnData = 'data'; -const String TransactionColumnAppCompanyId = 'appCompanyId'; -const String TransactionColumnCreatedAt = 'createdAt'; - -const int TransactionTypeSell = 1; -const int TransactionTypeBuy = 2; - -const int TransactionStatusPrepare = 0; - - -class Transaction { - int? id; - String? uuid; - int? type; - int? status; - String? data; - int? appCompanyId; - String? createdAt; - - Map toMap() { - var map = { - TransactionColumnUuid: uuid, - TransactionColumnType: type, - TransactionColumnStatus: status, - TransactionColumnData: data, - TransactionColumnAppCompanyId: appCompanyId, - TransactionColumnCreatedAt: createdAt, - }; - if (id != null) { - map[TransactionColumnId] = id; - } - return map; - } - - Transaction(); - - Transaction.fromMap(Map map) { - id = map[TransactionColumnId]; - uuid = map[TransactionColumnUuid]; - type = map[TransactionColumnType]; - status = map[TransactionColumnStatus]; - appCompanyId = map[TransactionColumnAppCompanyId]; - data = map[TransactionColumnData]; - createdAt = map[TransactionColumnCreatedAt]; - } - -} - diff --git a/lib/core/entity/category_entity.dart b/lib/core/entity/category_entity.dart new file mode 100644 index 0000000..d9184d4 --- /dev/null +++ b/lib/core/entity/category_entity.dart @@ -0,0 +1,40 @@ +const String categoryTableName = 'goods_category'; +const String categoryColumnId = 'id'; +const String categoryColumnParentIn = 'parent_id'; +const String categoryColumnName = 'name'; +const String categoryColumnAppCompanyId = 'app_company_id'; +const String categoryColumnUpdatedAt = 'updated_at'; + +class Category { + + Category(); + + Category.fromMap(Map map) { + id = map[categoryColumnId] as int; + parentId = map[categoryColumnParentIn] as int; + name = map[categoryColumnName] as String; + appCompanyId = map[categoryColumnAppCompanyId] as int; + updatedAt = map[categoryColumnUpdatedAt] as String; + } + + int? id; + int? parentId; + String? name; + int? appCompanyId; + String? updatedAt; + + Map toMap() { + final Map map = { + categoryColumnParentIn: parentId, + categoryColumnName: name, + categoryColumnAppCompanyId: appCompanyId, + categoryColumnUpdatedAt: updatedAt, + }; + if (id != null) { + map[categoryColumnId] = id; + } + return map; + } + +} + diff --git a/lib/core/entity/Goods.dart b/lib/core/entity/goods_entity.dart similarity index 66% rename from lib/core/entity/Goods.dart rename to lib/core/entity/goods_entity.dart index 36b7ed9..c52e793 100644 --- a/lib/core/entity/Goods.dart +++ b/lib/core/entity/goods_entity.dart @@ -1,4 +1,4 @@ -const String GoodTableName = 'goods'; +const String goodTableName = 'goods'; const String GoodColumnId = 'id'; const String GoodColumnCategoryId = 'category_id'; const String GoodColumnName = 'name'; @@ -12,6 +12,21 @@ const String GoodColumnUpdatedAt = 'updated_at'; const String GoodColumnAppCompanyId = 'app_company_id'; class Good { + Good(); + Good.fromMap(Map map) { + id = map[GoodColumnId] as int; + articul = map[GoodColumnArticul] as int; + name = (map[GoodColumnName] ?? '') as String ; + price = map[GoodColumnPrice] as num; + categoryId = map[GoodColumnCategoryId] as int; + ean = map[GoodColumnEan] as String; + appCompanyId = map[GoodColumnAppCompanyId] as int; + optPrice = map[GoodColumnOptPrice] as num; + basePrice = map[GoodColumnBasePrice] as num; + divisible = map[GoodColumnDivisible] as int; + updatedAt = map[GoodColumnUpdatedAt] as String; + } + int? id; int? categoryId; String name = ''; @@ -24,8 +39,10 @@ class Good { String? updatedAt; int? appCompanyId; + + Map toMap() { - var map = { + final Map map = { GoodColumnArticul: articul, GoodColumnName: name, GoodColumnPrice: price, @@ -43,19 +60,7 @@ class Good { return map; } - Good(); - Good.fromMap(Map map) { - id = map[GoodColumnId]; - articul = map[GoodColumnArticul]; - name = map[GoodColumnName]; - price = map[GoodColumnPrice]?.toDouble(); - categoryId = map[GoodColumnCategoryId]; - ean = map[GoodColumnEan]; - appCompanyId = map[GoodColumnAppCompanyId]; - optPrice = map[GoodColumnOptPrice]; - basePrice = map[GoodColumnBasePrice]; - divisible = map[GoodColumnDivisible]; - updatedAt = map[GoodColumnUpdatedAt]; - } + + } diff --git a/lib/core/entity/transaction_entity.dart b/lib/core/entity/transaction_entity.dart new file mode 100644 index 0000000..3f96474 --- /dev/null +++ b/lib/core/entity/transaction_entity.dart @@ -0,0 +1,55 @@ +const String transactionTableName = 'transactions'; +const String transactionColumnId = 'id'; +const String transactionColumnUuid = 'uuid'; +const String transactionColumnType = 'type'; +const String transactionColumnStatus = 'status'; +const String transactionColumnData = 'data'; +const String transactionColumnAppCompanyId = 'appCompanyId'; +const String transactionColumnCreatedAt = 'createdAt'; + +const int transactionTypeSell = 1; +const int transactionTypeBuy = 2; + +const int transactionStatusPrepare = 0; + + +class Transaction { + + Transaction(); + + Transaction.fromMap(Map map) { + id = map[transactionColumnId] as int; + uuid = map[transactionColumnUuid] as String; + type = map[transactionColumnType] as int; + status = map[transactionColumnStatus] as int; + appCompanyId = map[transactionColumnAppCompanyId] as int; + data = map[transactionColumnData] as String; + createdAt = map[transactionColumnCreatedAt] as String; + } + + int? id; + String? uuid; + int? type; + int? status; + String? data; + int? appCompanyId; + String? createdAt; + + Map toMap() { + final Map map = { + transactionColumnUuid: uuid, + transactionColumnType: type, + transactionColumnStatus: status, + transactionColumnData: data, + transactionColumnAppCompanyId: appCompanyId, + transactionColumnCreatedAt: createdAt, + }; + if (id != null) { + map[transactionColumnId] = id; + } + return map; + } + + +} + diff --git a/lib/core/models/auth/auth_response.dart b/lib/core/models/auth/auth_response.dart index ebc890d..77cd583 100644 --- a/lib/core/models/auth/auth_response.dart +++ b/lib/core/models/auth/auth_response.dart @@ -17,29 +17,30 @@ class AuthResponse { String? message; bool? operation; - - static AuthResponse? fromMap(Map map) { - if (map == null) return null; - AuthResponse authResponseBean = AuthResponse(); - authResponseBean.userId = map['user_id']; - authResponseBean.companyId = map['company_id']; - authResponseBean.kassaId = map['kassa_id']; - authResponseBean.token = map['token']; - authResponseBean.authAt = map['auth_at']; - authResponseBean.shard = map['shard']; - authResponseBean.message = map['message']; - authResponseBean.operation = map['operation']; + static AuthResponse fromMap(dynamic map) { + final AuthResponse authResponseBean = AuthResponse(); + authResponseBean.userId = map['user_id'] as int; + authResponseBean.companyId = map['company_id'] as int; + authResponseBean.kassaId = map['kassa_id'] as int; + authResponseBean.token = map['token']?.toString(); + authResponseBean.authAt = map['auth_at']?.toString(); + authResponseBean.shard = map['shard'] as int; + authResponseBean.message = map['message']?.toString(); + authResponseBean.operation = map['operation'] as bool; return authResponseBean; } - Map toJson() => { - "user_id": userId, - "company_id": companyId, - "kassa_id": kassaId, - "token": token, - "auth_at": authAt, - "shard": shard, - "message": message, - "operation": operation, - }; -} \ No newline at end of file + Map toJson() { + final Map map = { + 'user_id': userId, + 'company_id': companyId, + 'kassa_id': kassaId, + 'token': token, + 'auth_at': authAt, + 'shard': shard, + 'message': message, + 'operation': operation, + }; + return map; + } +} diff --git a/lib/core/models/dictionary/category_response.dart b/lib/core/models/dictionary/category_response.dart index 86aa2bb..ab63c74 100644 --- a/lib/core/models/dictionary/category_response.dart +++ b/lib/core/models/dictionary/category_response.dart @@ -9,13 +9,13 @@ class CategoryResponse { String? name; String? updatedAt; - static CategoryResponse? fromMap(Map map) { + static CategoryResponse? fromMap(dynamic map) { if (map == null) return null; - CategoryResponse categoryResponseBean = CategoryResponse(); - categoryResponseBean.id = map['id']; - categoryResponseBean.parentId = map['parent_id']; - categoryResponseBean.name = map['name']; - categoryResponseBean.updatedAt = map['updated_at']; + final CategoryResponse categoryResponseBean = CategoryResponse(); + categoryResponseBean.id = map['id'] as int; + categoryResponseBean.parentId = map['parent_id'] as int; + categoryResponseBean.name = map['name'] as String; + categoryResponseBean.updatedAt = map['updated_at'] as String; return categoryResponseBean; } diff --git a/lib/core/models/dictionary/good_response.dart b/lib/core/models/dictionary/good_response.dart index cd9a317..0865f46 100644 --- a/lib/core/models/dictionary/good_response.dart +++ b/lib/core/models/dictionary/good_response.dart @@ -21,32 +21,34 @@ class GoodResponse { int? divisible; String? updatedAt; - static GoodResponse? fromMap(Map map) { - if (map == null) return null; - GoodResponse goodResponseBean = GoodResponse(); - goodResponseBean.id = map['id']; - goodResponseBean.categoryId = map['category_id']; - goodResponseBean.name = map['name']; - goodResponseBean.ean = map['ean']; - goodResponseBean.articul = map['articul']; - goodResponseBean.price = map['price']; - goodResponseBean.optPrice = map['opt_price']; - goodResponseBean.basePrice = map['base_price']; - goodResponseBean.divisible = map['divisible']; - goodResponseBean.updatedAt = map['updated_at']; + static GoodResponse fromMap(dynamic map) { + final GoodResponse goodResponseBean = GoodResponse(); + goodResponseBean.id = map['id'] as int; + goodResponseBean.categoryId = map['category_id'] as int; + goodResponseBean.name = map['name'] as String; + goodResponseBean.ean = map['ean'] as String; + goodResponseBean.articul = map['articul'] as int; + goodResponseBean.price = map['price'] as int; + goodResponseBean.optPrice = map['opt_price'] as int; + goodResponseBean.basePrice = map['base_price'] as int; + goodResponseBean.divisible = map['divisible'] as int; + goodResponseBean.updatedAt = map['updated_at'] as String; return goodResponseBean; } - Map toJson() => { - "id": id, - "category_id": categoryId, - "name": name, - "ean": ean, - "articul": articul, - "price": price, - "opt_price": optPrice, - "base_price": basePrice, - "divisible": divisible, - "updated_at": updatedAt, - }; -} \ No newline at end of file + Map toJson() { + final Map map = { + 'id': id, + 'category_id': categoryId, + 'name': name, + 'ean': ean, + 'articul': articul, + 'price': price, + 'opt_price': optPrice, + 'base_price': basePrice, + 'divisible': divisible, + 'updated_at': updatedAt, + }; + return map; + } +} diff --git a/lib/core/models/flow/product_dao.dart b/lib/core/models/flow/product_dao.dart index 7bfea5b..63dc719 100644 --- a/lib/core/models/flow/product_dao.dart +++ b/lib/core/models/flow/product_dao.dart @@ -1,4 +1,21 @@ +import 'package:satu/core/utils/utils_parse.dart'; + class ProductDao { + ProductDao(); + + ProductDao.fromMap(dynamic map) { + id = map['id'] as int; + categoryId = map['categoryId'] as int; + count = map['count'] as num; + price = map['price'] as num; + productName = cast(map['productName']) ?? ''; + categoryName = cast(map['categoryName']); + eanCode = cast(map['eanCode']); + article = map['article'] as int; + excise = cast(map['excise']); + transactionId = cast(map['transactionId']); + } + int? id; int? categoryId; num? count; @@ -10,9 +27,8 @@ class ProductDao { String? excise; int? transactionId; - Map toMap() { - var map = { + final Map map = { 'id': id, 'categoryId': categoryId, 'count': count, @@ -22,24 +38,8 @@ class ProductDao { 'eanCode': eanCode, 'article': article, 'excise': excise, - 'transactionId' : transactionId, + 'transactionId': transactionId, }; return map; } - - ProductDao(); - - ProductDao.fromMap(Map map) { - id = map['id']; - categoryId = map['categoryId']; - count = map['count']; - price = map['price']; - productName = map['productName']; - categoryName = map['categoryName']; - eanCode = map['eanCode']; - article = map['article']; - excise = map['excise']; - transactionId = map['transactionId']; - } - -} \ No newline at end of file +} diff --git a/lib/core/models/flow/transaction_state.dart b/lib/core/models/flow/transaction_state.dart index 73b0f85..11c140c 100644 --- a/lib/core/models/flow/transaction_state.dart +++ b/lib/core/models/flow/transaction_state.dart @@ -1,3 +1,3 @@ class TransactionState { String? uuid; -} \ No newline at end of file +} diff --git a/lib/core/models/response.dart b/lib/core/models/response.dart index 37398b3..1ed9660 100644 --- a/lib/core/models/response.dart +++ b/lib/core/models/response.dart @@ -1,3 +1,5 @@ +import 'package:satu/core/utils/utils_parse.dart'; + /// list : [] /// message : "" /// operation : true @@ -9,21 +11,22 @@ class Response { Response(); - factory Response.fromMapList(Map map, Function? parser) { + factory Response.fromMapList(dynamic map, Function(dynamic)? parser) { - List list = []; + final List list = []; if (map['list'] != null) { - (map['list'] as List).forEach((element) { - if(parser == null) + (map['list'] as List).forEach((dynamic element) { + if(parser == null) { list.add(element); - else - list.add(parser(element)); + } else { + list.add(parser(element)); + } }); } - Response responseBean = Response(); + final Response responseBean = Response(); responseBean.list = list; - responseBean.message = map['message']; - responseBean.operation = map['operation']; + responseBean.message = cast(map['message']); + responseBean.operation = map['operation'] as bool; return responseBean; } diff --git a/lib/core/redux/actions/sell_actions.dart b/lib/core/redux/actions/sell_actions.dart index 14727c6..e545df2 100644 --- a/lib/core/redux/actions/sell_actions.dart +++ b/lib/core/redux/actions/sell_actions.dart @@ -4,9 +4,9 @@ import 'package:logger/logger.dart'; import 'package:meta/meta.dart'; import 'package:redux/redux.dart'; import 'package:redux_thunk/redux_thunk.dart'; -import 'package:satu/core/entity/Category.dart'; -import 'package:satu/core/entity/Goods.dart'; -import 'package:satu/core/entity/Transaction.dart'; +import 'package:satu/core/entity/category_entity.dart'; +import 'package:satu/core/entity/goods_entity.dart'; +import 'package:satu/core/entity/transaction_entity.dart'; import 'package:satu/core/models/flow/product_dao.dart'; import 'package:satu/core/models/flow/transaction_state.dart'; import 'package:satu/core/redux/state/sell_state.dart'; @@ -38,10 +38,10 @@ ThunkAction counterSellItem({required int transactionId, required num if (uuid != null ) { List> set = await _dbService.queryRowsWithWhere( - TransactionTableName, - '$TransactionColumnAppCompanyId = ? and $TransactionColumnStatus = ? and ${TransactionColumnType} = ? and ${TransactionColumnId} = ?', - [appCompanyId, TransactionStatusPrepare, TransactionTypeSell, transactionId], - orderBy: '$TransactionColumnCreatedAt desc'); + transactionTableName, + '$transactionColumnAppCompanyId = ? and $transactionColumnStatus = ? and ${transactionColumnType} = ? and ${transactionColumnId} = ?', + [appCompanyId, transactionStatusPrepare, transactionTypeSell, transactionId], + orderBy: '$transactionColumnCreatedAt desc'); if (set.isNotEmpty) { transaction = Transaction.fromMap(set.first); } @@ -50,7 +50,7 @@ ThunkAction counterSellItem({required int transactionId, required num ProductDao item = ProductDao.fromMap(jsonDecode(transaction.data!)); item.count = (item.count ?? 0) + counter; transaction.data = jsonEncode(item.toMap()); - _dbService.update(TransactionTableName, transaction.toMap()); + _dbService.update(transactionTableName, transaction.toMap()); } // refresh from db ? after save data await loadSellData(store); @@ -67,10 +67,10 @@ ThunkAction addSellItem({required Good good, String? excise}) { if (uuid != null ) { List> set = await _dbService.queryRowsWithWhere( - TransactionTableName, - '$TransactionColumnAppCompanyId = ? and $TransactionColumnStatus = ? and ${TransactionColumnType} = ?', - [appCompanyId, TransactionStatusPrepare, TransactionTypeSell], - orderBy: '$TransactionColumnCreatedAt desc'); + transactionTableName, + '$transactionColumnAppCompanyId = ? and $transactionColumnStatus = ? and ${transactionColumnType} = ?', + [appCompanyId, transactionStatusPrepare, transactionTypeSell], + orderBy: '$transactionColumnCreatedAt desc'); if (set.isNotEmpty) { for (Map map in set) { Transaction _transaction = Transaction.fromMap(map); @@ -88,7 +88,7 @@ ThunkAction addSellItem({required Good good, String? excise}) { item..count = item.count! + 1; transaction.data = jsonEncode(item.toMap()); transaction.createdAt = DateTime.now().toIso8601String(); - _dbService.update(TransactionTableName, transaction.toMap()); + _dbService.update(transactionTableName, transaction.toMap()); } else { ProductDao item = new ProductDao() ..id = good.id @@ -101,7 +101,7 @@ ThunkAction addSellItem({required Good good, String? excise}) { //category add logic if (good.categoryId != null) { List> set = - await _dbService.queryRowsWithWhere(CategoryTableName, 'id = ?', [good.categoryId]); + await _dbService.queryRowsWithWhere(categoryTableName, 'id = ?', [good.categoryId]); if (set.isNotEmpty) { Category category = Category.fromMap(set.first); item.categoryId = category.id; @@ -117,12 +117,12 @@ ThunkAction addSellItem({required Good good, String? excise}) { transaction = new Transaction() ..uuid = uuid - ..status = TransactionStatusPrepare + ..status = transactionStatusPrepare ..appCompanyId = appCompanyId - ..type = TransactionTypeSell + ..type = transactionTypeSell ..createdAt = DateTime.now().toIso8601String() ..data = jsonEncode(item.toMap()); - await _dbService.insert(TransactionTableName, transaction.toMap()); + await _dbService.insert(transactionTableName, transaction.toMap()); } // refresh from db ? after save data await loadSellData(store); @@ -135,7 +135,7 @@ ThunkAction removeSellItem({required int transactionId}) { int? appCompanyId = store.state.userState!.auth!.companyId; String? uuid = store.state.sellState!.transactionState!.uuid; - int count = await _dbService.delete(TransactionTableName, transactionId); + int count = await _dbService.delete(transactionTableName, transactionId); log.i('removeSellItem ${count} by transactionId:${transactionId}'); // refresh from db ? after save data @@ -149,12 +149,12 @@ Future removeAllSellData(Store store) async { int? appCompanyId = store.state.userState!.auth!.companyId; String? uuid = store.state.sellState!.transactionState!.uuid; await _dbService.deleteByWhere( - TransactionTableName, - '$TransactionColumnAppCompanyId = ? ' - ' and $TransactionColumnStatus = ? ' - ' and ${TransactionColumnType} = ?' - ' and ${TransactionColumnUuid} = ?', - [appCompanyId, TransactionStatusPrepare, TransactionTypeSell, uuid]); + transactionTableName, + '$transactionColumnAppCompanyId = ? ' + ' and $transactionColumnStatus = ? ' + ' and ${transactionColumnType} = ?' + ' and ${transactionColumnUuid} = ?', + [appCompanyId, transactionStatusPrepare, transactionTypeSell, uuid]); await loadSellData(store); } catch (e, stack) { log.e('removeAllSellData', e, stack); @@ -166,10 +166,10 @@ Future loadSellData(Store store) async { log.i('loadSellData'); int? appCompanyId = store.state.userState!.auth!.companyId; List> set = await _dbService.queryRowsWithWhere( - TransactionTableName, - '$TransactionColumnAppCompanyId = ? and $TransactionColumnStatus = ? and ${TransactionColumnType} = ?', - [appCompanyId, TransactionStatusPrepare, TransactionTypeSell], - orderBy: '$TransactionColumnCreatedAt desc'); + transactionTableName, + '$transactionColumnAppCompanyId = ? and $transactionColumnStatus = ? and ${transactionColumnType} = ?', + [appCompanyId, transactionStatusPrepare, transactionTypeSell], + orderBy: '$transactionColumnCreatedAt desc'); List list = []; String? uuid; for (Map map in set) { diff --git a/lib/core/redux/reducers/nav_reducer.dart b/lib/core/redux/reducers/nav_reducer.dart index 6d5315e..c762d03 100644 --- a/lib/core/redux/reducers/nav_reducer.dart +++ b/lib/core/redux/reducers/nav_reducer.dart @@ -3,10 +3,10 @@ import 'package:satu/core/redux/actions/user_actions.dart'; import 'package:satu/core/redux/state/nav_state.dart'; import 'package:satu/core/redux/state/user_state.dart'; -navReducer(NavState prevState, SetNavStateAction action) { - final NavState? payload = action.navState; +NavState navReducer(NavState prevState, SetNavStateAction action) { + final NavState payload = action.navState; return prevState.copyWith( - drawerViewClass: payload?.drawerViewClass!, - selectedTabIndex: payload?.selectedTabIndex!, + drawerViewClass: payload.drawerViewClass, + selectedTabIndex: payload.selectedTabIndex, ); } diff --git a/lib/core/redux/reducers/sell_reducer.dart b/lib/core/redux/reducers/sell_reducer.dart index e1f940b..e63050c 100644 --- a/lib/core/redux/reducers/sell_reducer.dart +++ b/lib/core/redux/reducers/sell_reducer.dart @@ -3,8 +3,8 @@ import 'package:satu/core/redux/actions/user_actions.dart'; import 'package:satu/core/redux/state/sell_state.dart'; import 'package:satu/core/redux/state/user_state.dart'; -sellReducer(SellState prevState, SetSellStateAction action) { - final payload = action.sellState; +SellState sellReducer(SellState prevState, SetSellStateAction action) { + final SellState payload = action.sellState; return prevState.copyWith( items: payload.items, transactionState: payload.transactionState diff --git a/lib/core/redux/reducers/user_reducer.dart b/lib/core/redux/reducers/user_reducer.dart index 73d4a42..c8dbb9b 100644 --- a/lib/core/redux/reducers/user_reducer.dart +++ b/lib/core/redux/reducers/user_reducer.dart @@ -1,8 +1,8 @@ import 'package:satu/core/redux/actions/user_actions.dart'; import 'package:satu/core/redux/state/user_state.dart'; -userReducer(UserState prevState, SetUserStateAction action) { - final payload = action.userState; +UserState userReducer(UserState prevState, SetUserStateAction action) { + final UserState payload = action.userState; return prevState.copyWith( isError: payload.isError, isLoading: payload.isLoading, diff --git a/lib/core/redux/store.dart b/lib/core/redux/store.dart index d344ab9..d48da46 100644 --- a/lib/core/redux/store.dart +++ b/lib/core/redux/store.dart @@ -20,15 +20,15 @@ import 'actions/user_actions.dart'; AppState appReducer(AppState state, dynamic action) { if (action is SetUserStateAction) { /** UserAction **/ - final nextState = userReducer(state.userState!, action); + final UserState nextState = userReducer(state.userState!, action); return state.copyWith(userState: nextState); } else if (action is SetNavStateAction) { /** NavAction **/ - final nextState = navReducer(state.navState!, action); + final NavState nextState = navReducer(state.navState!, action); return state.copyWith(navState: nextState); } else if (action is SetSellStateAction) { /** NavAction **/ - final nextState = sellReducer(state.sellState!, action); + final SellState nextState = sellReducer(state.sellState!, action); return state.copyWith(sellState: nextState); } return state; @@ -42,7 +42,7 @@ class AppState { final SellState? sellState; - AppState({ + const AppState({ this.userState, this.navState, this.sellState diff --git a/lib/core/services/api_service.dart b/lib/core/services/api_service.dart index 1483e75..fc62f3a 100644 --- a/lib/core/services/api_service.dart +++ b/lib/core/services/api_service.dart @@ -11,37 +11,33 @@ class ApiService extends BaseService { static const host = 'satu.aman.com.kz'; static const endpoint = '/api/v1'; - var client = new http.Client(); + http.Client client = http.Client(); //TOKEN - String? _token; - - String? get token => this._token; - - set token(String? value) => this._token = value; + String? token; Future _get(String point, {Map? requestBody, Map? header}) async { - Map headers = { + final Map headers = { HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.cacheControlHeader: "no-cache" }; if (header != null && header.isNotEmpty) { headers.addAll(header); } - String url = '$endpoint$point'; + final String url = '$endpoint$point'; final response = await http.get(Uri.https(host, url), headers: headers); return response.body; } Future _post(String point, {Map? requestBody, Map? header}) async { - Map headers = { + final Map headers = { HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.cacheControlHeader: "no-cache" }; if (header != null && header.isNotEmpty) { headers.addAll(header); } - String url = '$endpoint$point'; + final String url = '$endpoint$point'; if(requestBody!=null) { log.i(jsonEncode(requestBody)); } @@ -51,14 +47,14 @@ class ApiService extends BaseService { } Future login(String username, String password) async { - Map requestBody = {'username': username, 'password': password}; + final Map requestBody = {'username': username, 'password': password}; AuthResponse result; try { - String response = await _post('/login', requestBody: requestBody); - result = AuthResponse.fromMap(json.decode(response))!; + final String response = await _post('/login', requestBody: requestBody); + result = AuthResponse.fromMap(json.decode(response)); } catch (e, stack) { log.e("login", e, stack); - result = new AuthResponse() + result = AuthResponse() ..message = 'Ошибка вызова сервера' ..operation = false; } @@ -66,14 +62,14 @@ class ApiService extends BaseService { } Future authorization(String token) async { - Map requestBody = {'token': token}; + final Map requestBody = {'token': token}; AuthResponse result; try { - String response = await _post('/authorization', requestBody: requestBody); - result = AuthResponse.fromMap(json.decode(response))!; + final String response = await _post('/authorization', requestBody: requestBody); + result = AuthResponse.fromMap(json.decode(response)); } catch (e, stack) { log.e("authorization", e, stack); - result = new AuthResponse() + result = AuthResponse() ..message = 'Ошибка вызова сервера' ..operation = false; } @@ -81,14 +77,14 @@ class ApiService extends BaseService { } Future auth(String token) async { - Map headers = {HttpHeaders.authorizationHeader: 'Bearer $token'}; + final Map headers = {HttpHeaders.authorizationHeader: 'Bearer $token'}; AuthResponse result; try { - String response = await _post('/auth', header: headers); - result = AuthResponse.fromMap(json.decode(response))!; + final String response = await _post('/auth', header: headers); + result = AuthResponse.fromMap(json.decode(response)); } catch (e, stack) { log.e("auth", e, stack); - result = new AuthResponse() + result = AuthResponse() ..message = 'Ошибка вызова сервера' ..operation = false; } @@ -96,14 +92,14 @@ class ApiService extends BaseService { } Future logout() async { - Map headers = {HttpHeaders.authorizationHeader: 'Bearer $token'}; + final Map headers = {HttpHeaders.authorizationHeader: 'Bearer $token'}; AuthResponse result; try { - String response = await _post('/logout', header: headers); - result = AuthResponse.fromMap(json.decode(response))!; + final String response = await _post('/logout', header: headers); + result = AuthResponse.fromMap(json.decode(response)); } catch (e, stack) { log.e("auth", e, stack); - result = new AuthResponse() + result = AuthResponse() ..message = 'Ошибка вызова сервера' ..operation = false; } @@ -113,12 +109,12 @@ class ApiService extends BaseService { Future dictionaries(String target) async { Response result; try { - Map headers = {HttpHeaders.authorizationHeader: 'Bearer $token'}; - String response = await _post(target, header: headers); + final Map headers = {HttpHeaders.authorizationHeader: 'Bearer $token'}; + final String response = await _post(target, header: headers); result = Response.fromMapList(json.decode(response), null); } catch (e, stack) { log.e("dictionaries", e, stack); - result = new Response()..operation=false..list=[]; + result = Response()..operation=false..list=[]; } return result; } diff --git a/lib/core/services/db_service.dart b/lib/core/services/db_service.dart index eea3c24..1950651 100644 --- a/lib/core/services/db_service.dart +++ b/lib/core/services/db_service.dart @@ -1,16 +1,16 @@ import 'dart:io'; import 'package:satu/core/base/base_service.dart'; -import 'package:satu/core/entity/Category.dart'; -import 'package:satu/core/entity/Goods.dart'; -import 'package:satu/core/entity/Transaction.dart'; +import 'package:satu/core/entity/category_entity.dart'; +import 'package:satu/core/entity/goods_entity.dart'; +import 'package:satu/core/entity/transaction_entity.dart'; import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; class DbService extends BaseService { - static final _databaseName = "AmanSatuDb.db"; - static final _databaseVersion = 1; + static const _databaseName = "AmanSatuDb.db"; + static const _databaseVersion = 1; // make this a singleton class DbService._privateConstructor(); @@ -20,26 +20,24 @@ class DbService extends BaseService { // only have a single app-wide reference to the database static Database? _database; - Future get database async { - if (_database != null) return _database; - // lazily instantiate the db the first time it is accessed - _database = await _initDatabase(); - return _database; + Future get database async { + return _database ?? await _initDatabase(); } // this opens the database (and creates it if it doesn't exist) - _initDatabase() async { - Directory documentsDirectory = await getApplicationDocumentsDirectory(); - String path = join(documentsDirectory.path, _databaseName); - return await openDatabase(path, + Future _initDatabase() async { + final Directory documentsDirectory = await getApplicationDocumentsDirectory(); + final String path = join(documentsDirectory.path, _databaseName); + final Database db = await openDatabase(path, version: _databaseVersion, onUpgrade: _onUpdate, onCreate: _onCreate); + return db; } Future _onUpdate(Database db, int oldVersion, int newVersion) async { log.i('update from $oldVersion to $newVersion'); //Goods table - await db.execute('DROP TABLE IF EXISTS $GoodTableName;'); - await db.execute('DROP TABLE IF EXISTS $CategoryTableName;'); + await db.execute('DROP TABLE IF EXISTS $goodTableName;'); + await db.execute('DROP TABLE IF EXISTS $categoryTableName;'); //await db.execute('DROP TABLE IF EXISTS $Voucher_tableName;'); log.i('dropped tables'); _onCreate(db, newVersion); @@ -49,7 +47,7 @@ class DbService extends BaseService { log.i('create tables'); //Goods table await db.execute(''' - CREATE TABLE IF NOT EXISTS $GoodTableName ( + CREATE TABLE IF NOT EXISTS $goodTableName ( $GoodColumnId integer primary key unique, $GoodColumnArticul integer not null, $GoodColumnName text not null, @@ -64,23 +62,23 @@ class DbService extends BaseService { ); '''); await db.execute(''' - CREATE TABLE IF NOT EXISTS $CategoryTableName ( - $CategoryColumnId integer primary key unique, - $CategoryColumnName text not null, - $CategoryColumnParentIn integer, - $CategoryColumnAppCompanyId integer, - $CategoryColumnUpdatedAt text not null + CREATE TABLE IF NOT EXISTS $categoryTableName ( + $categoryColumnId integer primary key unique, + $categoryColumnName text not null, + $categoryColumnParentIn integer, + $categoryColumnAppCompanyId integer, + $categoryColumnUpdatedAt text not null ); '''); await db.execute(''' - CREATE TABLE IF NOT EXISTS $TransactionTableName ( - $TransactionColumnId integer primary key autoincrement, - $TransactionColumnUuid text, - $TransactionColumnType integer not null, - $TransactionColumnAppCompanyId integer not null, - $TransactionColumnStatus integer not null, - $TransactionColumnData text, - $TransactionColumnCreatedAt text not null + CREATE TABLE IF NOT EXISTS $transactionTableName ( + $transactionColumnId integer primary key autoincrement, + $transactionColumnUuid text, + $transactionColumnType integer not null, + $transactionColumnAppCompanyId integer not null, + $transactionColumnStatus integer not null, + $transactionColumnData text, + $transactionColumnCreatedAt text not null ); '''); } @@ -89,64 +87,74 @@ class DbService extends BaseService { // and the value is the column value. The return value is the id of the // inserted row. Future insert(String table, Map row) async { - Database? db = await instance.database; - return await db!.insert(table, row); + final Database db = await instance.database; + final int result = await db.insert(table, row); + return result; } // All of the rows are returned as a list of maps, where each map is // a key-value list of columns. Future>> queryAllRows(String table) async { - Database? db = await instance.database; - return await db!.query(table); + final Database db = await instance.database; + final List> result = await db.query(table); + return result; } Future>> queryRaw(String sql, List args) async { - Database? db = await instance.database; - return await db!.rawQuery(sql, args ); + final Database db = await instance.database; + final List> result = await db.rawQuery(sql, args ); + return result; } Future>> queryAllRowsOrderBy(String table, String orderBy) async { - Database? db = await instance.database; - return await db!.query(table, orderBy: orderBy); + final Database db = await instance.database; + final List> result = await db.query(table, orderBy: orderBy); + return result; } Future>> queryRowsWithWhere( String table, String where, List args, { String? orderBy }) async { - Database? db = await instance.database; - return await db!.query(table, where: where, whereArgs: args, orderBy: orderBy); + final Database db = await instance.database; + final List> result = await db.query(table, where: where, whereArgs: args, orderBy: orderBy); + return result; } // All of the methods (insert, query, update, delete) can also be done using // raw SQL commands. This method uses a raw query to give the row count. Future queryRowCount(String table) async { - Database? db = await instance.database; - return Sqflite.firstIntValue( - await db!.rawQuery('SELECT COUNT(*) FROM $table')); + final Database db = await instance.database; + final int? result = Sqflite.firstIntValue( + await db.rawQuery('SELECT COUNT(*) FROM $table')); + return result; } // We are assuming here that the id column in the map is set. The other // column values will be used to update the row. Future update(String table, Map row) async { - Database? db = await instance.database; - int id = row['id']; - return await db!.update(table, row, where: 'id = ?', whereArgs: [id]); + final Database db = await instance.database; + final int id = row['id'] as int; + final int result = await db.update(table, row, where: 'id = ?', whereArgs: [id]); + return result; } // Deletes the row specified by the id. The number of affected rows is // returned. This should be 1 as long as the row exists. Future delete(String table, int id) async { - Database? db = await instance.database; - return await db!.delete(table, where: 'id = ?', whereArgs: [id]); + final Database db = await instance.database; + final int result = await db.delete(table, where: 'id = ?', whereArgs: [id]); + return result; } Future deleteAll(String table) async { - Database? db = await instance.database; - return await db!.delete(table); + final Database db = await instance.database; + final int result = await db.delete(table); + return result; } Future deleteByWhere(String table, String where, List args) async { - Database? db = await instance.database; - return await db!.delete(table, where: where, whereArgs: args); + final Database db = await instance.database; + final int result = await db.delete(table, where: where, whereArgs: args); + return result; } Future close() async => instance.close(); diff --git a/lib/core/services/dialog_service.dart b/lib/core/services/dialog_service.dart index 427382c..ecc4750 100644 --- a/lib/core/services/dialog_service.dart +++ b/lib/core/services/dialog_service.dart @@ -4,12 +4,12 @@ import 'package:flutter/cupertino.dart'; import 'package:satu/core/models/dialog_models.dart'; class DialogService { - GlobalKey _dialogNavigationKey = GlobalKey(); - Function(DialogRequest)? _showDialogListener; - Function(DialogRequest)? _showDialogInputListener; + final GlobalKey _dialogNavigationKey = GlobalKey(); + late Function(DialogRequest)? _showDialogListener; + late Function(DialogRequest)? _showDialogInputListener; Completer? _dialogCompleter; - Completer? get completer => this._dialogCompleter; + Completer? get completer => _dialogCompleter; GlobalKey get dialogNavigationKey => _dialogNavigationKey; diff --git a/lib/core/services/dictionary_service.dart b/lib/core/services/dictionary_service.dart index 35c4b08..8295277 100644 --- a/lib/core/services/dictionary_service.dart +++ b/lib/core/services/dictionary_service.dart @@ -1,7 +1,7 @@ import 'package:satu/core/base/base_service.dart'; -import 'package:satu/core/entity/Category.dart'; -import 'package:satu/core/entity/Goods.dart'; +import 'package:satu/core/entity/category_entity.dart'; +import 'package:satu/core/entity/goods_entity.dart'; import 'package:satu/core/models/dictionary/category_response.dart'; import 'package:satu/core/models/dictionary/good_response.dart'; import 'package:satu/core/models/response.dart'; @@ -16,16 +16,16 @@ class DictionaryService extends BaseService { final DbService _db = locator(); Future refreshFull() async { - _db.deleteAll(CategoryTableName); + _db.deleteAll(categoryTableName); await refreshCategory(); - _db.deleteAll(GoodTableName); + _db.deleteAll(goodTableName); await refreshGood(); } Future refreshCategory() async { try { - int? appCompanyId = Redux.store!.state.userState!.auth!.companyId; - Response categories = await _api.dictionaries('/categories'); + final int? appCompanyId = Redux.store!.state.userState!.auth!.companyId; + final Response categories = await _api.dictionaries('/categories'); if (categories.operation! && categories.list!.isNotEmpty) { for (dynamic map in categories.list!) { CategoryResponse cat = CategoryResponse.fromMap(map)!; @@ -35,7 +35,7 @@ class DictionaryService extends BaseService { ..updatedAt = cat.updatedAt ..parentId = cat.parentId ..appCompanyId = appCompanyId; - _db.insert(CategoryTableName, entity.toMap()); + _db.insert(categoryTableName, entity.toMap()); } } } catch (e, stack) { @@ -44,13 +44,13 @@ class DictionaryService extends BaseService { } Future> getCategoryByParentId(int parentId ) async { - List list = []; + final List list = []; try { - int? appCompanyId = Redux.store!.state.userState!.auth!.companyId; - List> elements = await _db.queryRowsWithWhere(CategoryTableName, '$CategoryColumnAppCompanyId = ? and $CategoryColumnParentIn = ?', [appCompanyId, parentId]); - elements.forEach((element) { + final int? appCompanyId = Redux.store?.state.userState?.auth?.companyId; + final List> elements = await _db.queryRowsWithWhere(categoryTableName, '$categoryColumnAppCompanyId = ? and $categoryColumnParentIn = ?', [appCompanyId, parentId]); + for (final Map element in elements){ list.add(Category.fromMap(element)); - }); + } } catch (e, stack) { log.e("getCategoryByParentId", e, stack); } @@ -58,13 +58,13 @@ class DictionaryService extends BaseService { } Future> getGoodsByCategoryId(int categoryId ) async { - List list = []; + final List list = []; try { - int? appCompanyId = Redux.store!.state.userState!.auth!.companyId; - List> elements = await _db.queryRowsWithWhere(GoodTableName, '$GoodColumnAppCompanyId = ? and $GoodColumnCategoryId = ?', [appCompanyId, categoryId]); - elements.forEach((element) { + final int? appCompanyId = Redux.store?.state.userState?.auth?.companyId; + final List> elements = await _db.queryRowsWithWhere(goodTableName, '$GoodColumnAppCompanyId = ? and $GoodColumnCategoryId = ?', [appCompanyId, categoryId]); + for (final Map element in elements){ list.add(Good.fromMap(element)); - }); + } } catch (e, stack) { log.e("getGoodsByCategoryId", e, stack); } @@ -72,19 +72,19 @@ class DictionaryService extends BaseService { } Future> getGoodsByNameOrEan( String query ) async { - List list = []; + final List list = []; try { - int? appCompanyId = Redux.store!.state.userState!.auth!.companyId; + final int? appCompanyId = Redux.store?.state.userState?.auth?.companyId; String where = '( $GoodColumnAppCompanyId = ? and $GoodColumnName like ? ) '; - List args = [appCompanyId, '%$query%']; + final List args = [appCompanyId, '%$query%']; if(_isNumericInt(query)){ where += ' or $GoodColumnEan like ?'; args.add('${int.parse(query).toString()}%'); } - List> elements = await _db.queryRowsWithWhere(GoodTableName, where, args); - elements.forEach((element) { + final List> elements = await _db.queryRowsWithWhere(goodTableName, where, args); + for (final Map element in elements){ list.add(Good.fromMap(element)); - }); + } } catch (e, stack) { log.e("getGoodsByCategoryId", e, stack); } @@ -92,15 +92,16 @@ class DictionaryService extends BaseService { } Future> getGoodsByEan( String code ) async { - List list = []; + final List list = []; try { - int? appCompanyId = Redux.store!.state.userState!.auth!.companyId; - String where = '( $GoodColumnAppCompanyId = ? and $GoodColumnEan like ? ) '; - List args = [appCompanyId, '%$code%']; - List> elements = await _db.queryRowsWithWhere(GoodTableName, where, args); - elements.forEach((element) { + final int? appCompanyId = Redux.store?.state.userState?.auth?.companyId; + final String where = '( $GoodColumnAppCompanyId = ? and $GoodColumnEan like ? ) '; + final List args = [appCompanyId, '%$code%']; + final List> + elements = await _db.queryRowsWithWhere(goodTableName, where, args); + for (final Map element in elements){ list.add(Good.fromMap(element)); - }); + } } catch (e, stack) { log.e("getGoodsByEan", e, stack); } @@ -119,9 +120,9 @@ class DictionaryService extends BaseService { int? appCompanyId = Redux.store!.state.userState!.auth!.companyId; Response categories = await _api.dictionaries('/goods'); if (categories.operation! && categories.list!.isNotEmpty) { - for (dynamic map in categories.list!) { - GoodResponse good = GoodResponse.fromMap(map)!; - Good entity = new Good() + for (final dynamic map in categories.list!) { + final GoodResponse good = GoodResponse.fromMap(map); + final Good entity = new Good() ..id = good.id ..name = good.name ..categoryId = good.categoryId @@ -133,7 +134,7 @@ class DictionaryService extends BaseService { ..divisible = good.divisible ..updatedAt = good.updatedAt ..appCompanyId = appCompanyId; - _db.insert(GoodTableName, entity.toMap()); + _db.insert(goodTableName, entity.toMap()); } } } catch (e, stack) { diff --git a/lib/core/utils/logger.dart b/lib/core/utils/logger.dart index de5ee34..96b208b 100644 --- a/lib/core/utils/logger.dart +++ b/lib/core/utils/logger.dart @@ -9,24 +9,25 @@ class SimpleLogPrinter extends LogPrinter { @override List log(LogEvent event) { - var level = event.level; - var message = stringifyMessage(event.message); - var error = event.error?.toString() ?? ''; - var color = PrettyPrinter.levelColors[level]; - var emoji = PrettyPrinter.levelEmojis[level]; + final Level level = event.level; + final String message = stringifyMessage(event.message); + final String error = event.error?.toString() ?? ''; + final color = PrettyPrinter.levelColors[level]; + final emoji = PrettyPrinter.levelEmojis[level]; String? stack; if (event.stackTrace == null) { stack = formatStackTrace(StackTrace.current, 2); } else { stack = formatStackTrace(event.stackTrace!, 1); } + // ignore: avoid_print print(color!(' $emoji $message $error -> $stack ')); return []; } String stringifyMessage(dynamic message) { if (message is Map || message is Iterable) { - var encoder = JsonEncoder.withIndent(' '); + const encoder = JsonEncoder.withIndent(' '); return encoder.convert(message); } else { return message.toString(); @@ -34,15 +35,15 @@ class SimpleLogPrinter extends LogPrinter { } String? formatStackTrace(StackTrace stackTrace, int methodPosition) { - var lines = stackTrace.toString().split('\n'); - var formatted = []; + final lines = stackTrace.toString().split('\n'); + final formatted = []; var count = 0; - for (var line in lines) { + for (final line in lines) { if (_discardDeviceStacktraceLine(line) || _discardWebStacktraceLine(line)) { continue; } - formatted.add('${line.replaceFirst(RegExp(r'#\d+\s+'), '')}'); + formatted.add(line.replaceFirst(RegExp(r'#\d+\s+'), '')); if (++count == methodPosition) { break; } @@ -57,7 +58,7 @@ class SimpleLogPrinter extends LogPrinter { } bool _discardDeviceStacktraceLine(String line) { - var match = _deviceStackTraceRegex.matchAsPrefix(line); + final match = _deviceStackTraceRegex.matchAsPrefix(line); if (match == null) { return false; } @@ -65,7 +66,7 @@ class SimpleLogPrinter extends LogPrinter { } bool _discardWebStacktraceLine(String line) { - var match = _webStackTraceRegex.matchAsPrefix(line); + final match = _webStackTraceRegex.matchAsPrefix(line); if (match == null) { return false; } diff --git a/lib/core/utils/utilsParse.dart b/lib/core/utils/utilsParse.dart deleted file mode 100644 index c5ec54d..0000000 --- a/lib/core/utils/utilsParse.dart +++ /dev/null @@ -1,4 +0,0 @@ -List? parseListString(json){ - if(json==null) return null; - return new List.from(json); -} \ No newline at end of file diff --git a/lib/core/utils/utils_parse.dart b/lib/core/utils/utils_parse.dart new file mode 100644 index 0000000..6c2035d --- /dev/null +++ b/lib/core/utils/utils_parse.dart @@ -0,0 +1,6 @@ +List? parseListString(Iterable? json){ + if(json==null) return null; + return List.from(json); +} + +T? cast(x) => x is T ? x : null; \ No newline at end of file diff --git a/lib/views/add_product/add_product_view.dart b/lib/views/add_product/add_product_view.dart index 7d380f3..18685c1 100644 --- a/lib/views/add_product/add_product_view.dart +++ b/lib/views/add_product/add_product_view.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:satu/core/entity/Category.dart'; -import 'package:satu/core/entity/Goods.dart'; +import 'package:satu/core/entity/category_entity.dart'; +import 'package:satu/core/entity/goods_entity.dart'; import 'package:satu/core/redux/actions/sell_actions.dart'; import 'package:satu/core/redux/store.dart'; import 'package:satu/core/services/dictionary_service.dart'; @@ -107,14 +107,14 @@ class _AddProductViewState extends State { ); } - onCategoryPress(Category category) { + void onCategoryPress(Category category) { _history!.add(category); navigateCategory(category.id!); } - onGoodPress(Good good) { + void onGoodPress(Good good) { Redux.store!.dispatch(addSellItem(good: good)); - _navigatorService.pop(); + _navigatorService.pop(); } void reset() { diff --git a/lib/views/login/login_view.dart b/lib/views/login/login_view.dart index 5fe19eb..40cfa6a 100644 --- a/lib/views/login/login_view.dart +++ b/lib/views/login/login_view.dart @@ -99,16 +99,17 @@ class _LoginViewState extends State { }); } - _pressBtnEnter() async { + Future _pressBtnEnter() async { Redux.store!.dispatch(authenticate(emailController.text, passwordController.text)); } Future scan() async { - String? result = await locator().push(AddByBarcodeViewRoute); + final NavigatorService _nav = locator().push(AddByBarcodeViewRoute) as NavigatorService; + final dynamic result = await _nav.push(AddByBarcodeViewRoute) ; if(result != null) { if( result.length == 60 ) { - Redux.store?.dispatch(authenticateByToken(result)); + Redux.store?.dispatch(authenticateByToken(result as String)); } else { _dialogService.showDialog(description: 'Не верный формат QR кода'); } diff --git a/lib/views/work/tabs/component/dialog_edit_product.dart b/lib/views/work/tabs/component/dialog_edit_product.dart new file mode 100644 index 0000000..4217ffc --- /dev/null +++ b/lib/views/work/tabs/component/dialog_edit_product.dart @@ -0,0 +1,38 @@ +import 'package:flutter/material.dart'; + +Future dialog(BuildContext cont) async { + return showDialog( + //barrierDismissible: false, + context: cont, + builder: (BuildContext context) { + return StatefulBuilder(builder: (context, setState) { + return AlertDialog( + insetPadding: EdgeInsets.zero, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10.0))), + content: SizedBox.expand( + child: Column( + children: [ + Wrap( + children: [ + Row( + children: [ + const Expanded( + flex: 1, + child: Text( + "Sample type", + style: TextStyle(fontWeight: FontWeight.w700), + ), + ), + Expanded(flex: 1, child: Text("123")) + ], + ), + ], + ), + ], + ), + )); + }); + }, + ); +} diff --git a/lib/views/work/tabs/component/product_list_item.dart b/lib/views/work/tabs/component/product_list_item.dart index ffaf16d..6f550da 100644 --- a/lib/views/work/tabs/component/product_list_item.dart +++ b/lib/views/work/tabs/component/product_list_item.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:satu/core/redux/actions/sell_actions.dart'; import 'package:satu/core/redux/store.dart'; +import 'package:satu/core/services/dialog_service.dart'; import 'package:satu/core/services/navigator_service.dart'; import 'package:satu/core/utils/locator.dart'; import 'package:satu/routes/route_names.dart'; @@ -12,6 +13,8 @@ import 'package:satu/shared/ui_helpers.dart'; import 'package:satu/views/add_by_barcode/add_by_barcode_view.dart'; import 'package:satu/widgets/ui/product_title_widget.dart'; +import 'dialog_edit_product.dart'; + class ProductListItem extends StatefulWidget { final String name; final String? ean; @@ -31,10 +34,11 @@ class ProductListItem extends StatefulWidget { class _ProductListItemState extends State { final NavigatorService _navigatorService = locator(); + final DialogService _dialogService = locator(); void _onItemTapped(BuildContext context) { - Navigator.of(context).push(new MaterialPageRoute( - builder: (BuildContext context) => new AddByBarcodeView())); + Navigator.of(context).push(MaterialPageRoute( + builder: (BuildContext context) => AddByBarcodeView())); } @override @@ -43,8 +47,8 @@ class _ProductListItemState extends State { background: Container( alignment: AlignmentDirectional.centerEnd, color: dangerColor, - child: Padding( - padding: const EdgeInsets.all(8.0), + child: const Padding( + padding: EdgeInsets.all(8.0), child: Text( 'Удалить', style: TextStyle(color: whiteColor, fontWeight: FontWeight.w500), @@ -71,7 +75,6 @@ class _ProductListItemState extends State { ); }, onDismissed: (direction) { - print(direction); Redux.store!.dispatch(removeSellItem(transactionId: this.widget.transactionId!)); }, key: Key(widget.name ), @@ -99,7 +102,6 @@ class _ProductListItemState extends State { ), ), Row( - crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.end, children: [ Material( @@ -108,7 +110,7 @@ class _ProductListItemState extends State { child: InkWell( onTap: () { Redux.store! - .dispatch(counterSellItem(transactionId: this.widget.transactionId!, counter: 1.0)); + .dispatch(counterSellItem(transactionId: widget.transactionId!, counter: 1.0)); }, child: Container( decoration: BoxDecoration( @@ -126,17 +128,24 @@ class _ProductListItemState extends State { Container( width: 45.w, margin: EdgeInsets.symmetric(horizontal: 5.w), - padding: EdgeInsets.symmetric(vertical: 6.0.w), decoration: BoxDecoration( color: whiteColor, borderRadius: BorderRadius.circular(ScreenUtil().radius(5)), boxShadow: [cardShadowBox]), - child: SizedBox( - width: 45.w, - child: Text( - '${widget.count} шт', - style: TextStyle(fontSize: 8.sp, color: placeholderColor), - textAlign: TextAlign.center, + child: InkWell( + onTap: (){ + _dialogService.showConfirmationDialogInput(description: 'asd'); + }, + child: Padding( + padding: EdgeInsets.symmetric(vertical: 6.0.w), + child: SizedBox( + width: 45.w, + child: Text( + '${widget.count} шт', + style: TextStyle(fontSize: 8.sp, color: placeholderColor), + textAlign: TextAlign.center, + ), + ), ), ), ), diff --git a/lib/views/work/tabs/sell_view.dart b/lib/views/work/tabs/sell_view.dart index f039ca4..0379153 100644 --- a/lib/views/work/tabs/sell_view.dart +++ b/lib/views/work/tabs/sell_view.dart @@ -2,7 +2,8 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_redux/flutter_redux.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; -import 'package:satu/core/entity/Goods.dart'; +import 'package:redux/src/store.dart'; +import 'package:satu/core/entity/goods_entity.dart'; import 'package:satu/core/models/flow/product_dao.dart'; import 'package:satu/core/redux/actions/sell_actions.dart'; import 'package:satu/core/redux/state/sell_state.dart'; @@ -31,25 +32,25 @@ class SellView extends StatelessWidget { appBar: ProductsAppBar( drawerShow: true, title: 'Продажа', + backgroundColor: backgroundColor, + childHeight: 60, child: ProductHeaderBar( count: state.items!.length, sum: sumProducts(state.items!), ), - backgroundColor: backgroundColor, - childHeight: 60, ), body: Column( children: [ - ContragentSelectBar( + const ContragentSelectBar( value: 'Частное лицо', ), - Visibility(child: ProductsTitleBarBar(itemsExist: true, title: 'Товары',), visible: state.items!.isNotEmpty,), + Visibility(visible: state.items!.isNotEmpty,child: const ProductsTitleBarBar(itemsExist: true, title: 'Товары',),), ListView.separated( shrinkWrap: true, - physics: BouncingScrollPhysics(), + physics: const BouncingScrollPhysics(), itemCount: state.items!.length, itemBuilder: (BuildContext context, int index) { - ProductDao product = state.items!.elementAt(index); + final ProductDao product = state.items!.elementAt(index); return ProductListItem( key: UniqueKey(), ean: product.eanCode, @@ -62,7 +63,7 @@ class SellView extends StatelessWidget { ); }, separatorBuilder: (context, index) { - return Divider(height: 1, color: disableColor,); + return const Divider(height: 1, color: disableColor,); }, ), ], @@ -72,11 +73,11 @@ class SellView extends StatelessWidget { ); }); } - +/// render floating buttons Widget floatingActionButtonRender() { return StoreConnector( - converter: (store) => store.state.sellState!, - builder: (_, snapshot) { + converter: (Store store) => store.state.sellState!, + builder: (_, SellState snapshot) { return Padding( padding: EdgeInsets.all(15.w), child: Row( @@ -86,6 +87,7 @@ class SellView extends StatelessWidget { Visibility( visible: snapshot.items!.isNotEmpty, child: FloatingActionButton( + mini: true, elevation: 2, backgroundColor: successColor, onPressed: () => print('check'), @@ -96,26 +98,29 @@ class SellView extends StatelessWidget { children: [ FloatingActionButton( elevation: 2, + mini: true, onPressed: () => locator().push(AddProductViewRoute), child: Icon( Icons.add_rounded, - size: 45.sp, + size: 40.sp, color: whiteColor, ), ), - verticalSpaceMedium, + verticalSpaceSmall, FloatingActionButton( elevation: 2, + mini: true, onPressed: () async { - String? result = await locator().push(AddByBarcodeViewRoute); + final NavigatorService _nav = locator().push(AddByBarcodeViewRoute) as NavigatorService; + final dynamic result = await _nav.push(AddByBarcodeViewRoute) ; if(result !=null) { - List goods = await locator().getGoodsByEan(result); + final List goods = await locator().getGoodsByEan(result as String); if(goods.isNotEmpty) { Redux.store?.dispatch(addSellItem( good: goods.first)); } } }, - child: Icon(Icons.qr_code_rounded, size: 35.sp, color: whiteColor), + child: Icon(Icons.qr_code_rounded, size: 30.sp, color: whiteColor), ), ], ) diff --git a/lib/widgets/dialog/dialog_manager.dart b/lib/widgets/dialog/dialog_manager.dart index a937119..13c0083 100644 --- a/lib/widgets/dialog/dialog_manager.dart +++ b/lib/widgets/dialog/dialog_manager.dart @@ -36,10 +36,11 @@ class _DialogManagerState extends State { } void _showDialog(DialogRequest request) { + var isConfirmationDialog = request.cancelTitle != null; - showDialog( + showDialog( context: context, - builder: (context) => AlertDialog( + builder: (BuildContext context) => AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5.0), ), @@ -49,7 +50,7 @@ class _DialogManagerState extends State { children: [ Text( request.title!, - style: TextStyle(fontWeight: FontWeight.bold), + style: const TextStyle(fontWeight: FontWeight.bold), ), //Divider(), ], @@ -58,18 +59,18 @@ class _DialogManagerState extends State { actions: [ if (isConfirmationDialog) TextButton( - child: Text(request.cancelTitle!), onPressed: () { _dialogService .dialogComplete(DialogResponse(confirmed: false)); }, + child: Text(request.cancelTitle!), ), TextButton( - child: Text(request.buttonTitle!), onPressed: () { _dialogService .dialogComplete(DialogResponse(confirmed: true)); }, + child: Text(request.buttonTitle!), ), ], )); diff --git a/lib/widgets/dialog/modal_select_dialog.dart b/lib/widgets/dialog/modal_select_dialog.dart index d368b4e..c859031 100644 --- a/lib/widgets/dialog/modal_select_dialog.dart +++ b/lib/widgets/dialog/modal_select_dialog.dart @@ -28,7 +28,7 @@ class _DialogModalSelectState extends State { ); } - contentBox(context) { + Widget contentBox(BuildContext context) { return Stack( children: [ Container( @@ -43,7 +43,7 @@ class _DialogModalSelectState extends State { color: Colors.white, borderRadius: BorderRadius.circular(padding), boxShadow: [ - BoxShadow( + const BoxShadow( color: Colors.black, offset: Offset(0, 10), blurRadius: 10), ]), child: Column( diff --git a/pubspec.lock b/pubspec.lock index 9fdbb60..5e840a5 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -176,7 +176,7 @@ packages: name: get_it url: "https://pub.dartlang.org" source: hosted - version: "7.1.3" + version: "7.2.0" html: dependency: transitive description: @@ -219,6 +219,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "0.6.3" + lint: + dependency: "direct dev" + description: + name: lint + url: "https://pub.dartlang.org" + source: hosted + version: "1.5.3" logger: dependency: "direct main" description: @@ -344,7 +351,7 @@ packages: name: plugin_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "2.0.0" + version: "2.0.1" process: dependency: transitive description: @@ -552,7 +559,7 @@ packages: name: url_launcher url: "https://pub.dartlang.org" source: hosted - version: "6.0.7" + version: "6.0.9" url_launcher_linux: dependency: transitive description: @@ -573,7 +580,7 @@ packages: name: url_launcher_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "2.0.3" + version: "2.0.4" url_launcher_web: dependency: transitive description: @@ -608,7 +615,7 @@ packages: name: win32 url: "https://pub.dartlang.org" source: hosted - version: "2.2.4" + version: "2.2.5" xdg_directories: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 214b743..3ca11b7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -36,20 +36,20 @@ dependencies: responsive_builder: ^0.4.1 provider: ^5.0.0 logger: ^1.0.0 - get_it: ^7.1.2 - equatable: ^2.0.0 + get_it: ^7.2.0 + equatable: ^2.0.3 http: ^0.13.3 sqflite: ^2.0.0+3 - path_provider: ^2.0.1 + path_provider: ^2.0.2 material_design_icons_flutter: 5.0.5955-rc.1 intl: ^0.17.0 - device_info: ^2.0.0 + device_info: ^2.0.2 auto_size_text: ^3.0.0-nullsafety.0 url_launcher: ^6.0.7 qr_flutter: ^4.0.0 mask_text_input_formatter: ^2.0.0 - flutter_screenutil: ^5.0.0 - shared_preferences: ^2.0.5 + flutter_screenutil: ^5.0.0+2 + shared_preferences: ^2.0.6 material_floating_search_bar: ^0.3.4 implicitly_animated_reorderable_list: ^0.4.0 uuid: ^3.0.4 @@ -59,6 +59,8 @@ dependencies: dev_dependencies: flutter_test: sdk: flutter + lint: ^1.5.3 + # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec