repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/attribute.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'attribute.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class AttributeAdapter extends TypeAdapter<Attribute> { @override final int typeId = 15; @override Attribute read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return Attribute( name: fields[0] as String, type: fields[1] as String, moq: fields[3] == null ? 0 : fields[3] as int, options: (fields[2] as List).cast<Option>(), ); } @override void write(BinaryWriter writer, Attribute obj) { writer ..writeByte(4) ..writeByte(0) ..write(obj.name) ..writeByte(1) ..write(obj.type) ..writeByte(2) ..write(obj.options) ..writeByte(3) ..write(obj.moq); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is AttributeAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/product.dart
import 'dart:convert'; import 'dart:typed_data'; import 'package:hive/hive.dart'; import '../db_utils/db_constants.dart'; import 'attribute.dart'; part 'product.g.dart'; @HiveType(typeId: ProductsBoxTypeId) class Product extends HiveObject { @HiveField(0) String id; @HiveField(1) String name; @HiveField(2) double price; @HiveField(3) String group; @HiveField(4) String description; @HiveField(5) double stock; @HiveField(6) List<Attribute> attributes; @HiveField(7) Uint8List productImage; @HiveField(8) DateTime productUpdatedTime; @HiveField(9, defaultValue: 0.0) double tax; String? productImageUrl; Product( {required this.id, required this.name, required this.group, required this.description, required this.stock, required this.price, required this.attributes, required this.productImage, required this.productUpdatedTime, this.productImageUrl = '', required this.tax}); Product copyWith( {String? id, String? code, String? name, String? group, String? description, double? stock, double? price, List<Attribute>? attributes, double? orderedQuantity, double? orderedPrice, Uint8List? productImage, DateTime? productUpdatedTime, double? tax}) { return Product( id: id ?? this.id, name: name ?? this.name, group: group ?? this.group, description: description ?? this.description, stock: stock ?? this.stock, price: price ?? this.price, attributes: attributes ?? this.attributes, productImage: productImage ?? this.productImage, productUpdatedTime: productUpdatedTime ?? this.productUpdatedTime, tax: tax ?? this.tax, ); } Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'group': group, 'description': description, 'stock': stock, 'price': price, 'attributes': attributes.map((x) => x.toMap()).toList(), 'productImage': productImage, 'productUpdatedTime': productUpdatedTime.toIso8601String(), 'tax': tax }; } factory Product.fromMap(Map<String, dynamic> map) { return Product( id: map['id'], name: map['name'], group: map['group'], description: map['description'], stock: map['stock'], price: map['price'], attributes: List<Attribute>.from( map['attributes']?.map((x) => Attribute.fromMap(x))), productImage: map['productImage'], productUpdatedTime: map['productUpdatedTime'], tax: map['tax']); } String toJson() => json.encode(toMap()); factory Product.fromJson(String source) => Product.fromMap(json.decode(source)); @override String toString() { return 'Product(id: $id, name: $name, group: $group, description: $description, stock: $stock, price: $price, attributes: $attributes, productImage: $productImage, productUpdatedTime: $productUpdatedTime, tax: $tax)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Product && other.id == id && other.name == name && other.group == group && other.description == description && other.stock == stock && other.price == price && other.attributes == attributes && other.productImage == productImage && other.productUpdatedTime == productUpdatedTime; } @override int get hashCode { return id.hashCode ^ name.hashCode ^ group.hashCode ^ description.hashCode ^ stock.hashCode ^ price.hashCode ^ attributes.hashCode ^ productImage.hashCode ^ productUpdatedTime.hashCode; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/attribute.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:hive_flutter/hive_flutter.dart'; import '../db_utils/db_constants.dart'; import 'option.dart'; part 'attribute.g.dart'; @HiveType(typeId: AttributeBoxTypeId) class Attribute extends HiveObject { @HiveField(0) String name; @HiveField(1) String type; @HiveField(2) List<Option> options; @HiveField(3, defaultValue: 0) int moq; Attribute({ required this.name, required this.type, required this.moq, required this.options, }); Attribute copyWith({ String? name, String? type, int? moq, List<Option>? options, double? tax, }) { return Attribute( name: name ?? this.name, type: type ?? this.type, moq: moq ?? this.moq, options: options ?? this.options, ); } Map<String, dynamic> toMap() { return { 'name': name, 'type': type, 'moq': moq, 'options': options.map((x) => x.toMap()).toList(), }; } factory Attribute.fromMap(Map<String, dynamic> map) { return Attribute( name: map['name'] ?? '', type: map['type'] ?? '', moq: map['moq'] ?? 0, options: List<Option>.from(map['options']?.map((x) => Option.fromMap(x))), ); } String toJson() => json.encode(toMap()); factory Attribute.fromJson(String source) => Attribute.fromMap(json.decode(source)); @override String toString() => 'Attribute(name: $name, moq: $moq type: $type, options: $options)'; @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Attribute && other.name == name && other.type == type && other.moq == moq && listEquals(other.options, options); } @override int get hashCode => name.hashCode ^ type.hashCode ^ options.hashCode; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/product.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'product.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class ProductAdapter extends TypeAdapter<Product> { @override final int typeId = 10; @override Product read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return Product( id: fields[0] as String, name: fields[1] as String, group: fields[3] as String, description: fields[4] as String, stock: fields[5] as double, price: fields[2] as double, attributes: (fields[6] as List).cast<Attribute>(), productImage: fields[7] as Uint8List, productUpdatedTime: fields[8] as DateTime, tax: fields[9] == null ? 0.0 : fields[9] as double, ); } @override void write(BinaryWriter writer, Product obj) { writer ..writeByte(10) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.name) ..writeByte(2) ..write(obj.price) ..writeByte(3) ..write(obj.group) ..writeByte(4) ..write(obj.description) ..writeByte(5) ..write(obj.stock) ..writeByte(6) ..write(obj.attributes) ..writeByte(7) ..write(obj.productImage) ..writeByte(8) ..write(obj.productUpdatedTime) ..writeByte(9) ..write(obj.tax); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is ProductAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/park_order.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'park_order.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class ParkOrderAdapter extends TypeAdapter<ParkOrder> { @override final int typeId = 13; @override ParkOrder read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return ParkOrder( id: fields[0] as String, date: fields[1] as String, time: fields[2] as String, customer: fields[3] as Customer, manager: fields[4] as HubManager, items: (fields[5] as List).cast<OrderItem>(), orderAmount: fields[6] as double, transactionDateTime: fields[7] as DateTime, ); } @override void write(BinaryWriter writer, ParkOrder obj) { writer ..writeByte(8) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.date) ..writeByte(2) ..write(obj.time) ..writeByte(3) ..write(obj.customer) ..writeByte(4) ..write(obj.manager) ..writeByte(5) ..write(obj.items) ..writeByte(6) ..write(obj.orderAmount) ..writeByte(7) ..write(obj.transactionDateTime); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is ParkOrderAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/my_account
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/my_account/model/hub_manager_response.dart
import 'dart:convert'; class HubManagerResponse { String name; String email; String phone; double cashBalance; HubManagerResponse({ required this.name, required this.email, required this.phone, required this.cashBalance, }); HubManagerResponse copyWith({ String? name, String? email, String? phone, double? cashBalance, }) { return HubManagerResponse( name: name ?? this.name, email: email ?? this.email, phone: phone ?? this.phone, cashBalance: cashBalance ?? this.cashBalance, ); } Map<String, dynamic> toMap() { return { 'name': name, 'email': email, 'phone': phone, 'cashBalance': cashBalance, }; } factory HubManagerResponse.fromMap(Map<String, dynamic> map) { return HubManagerResponse( name: map['name'], email: map['email'], phone: map['phone'], cashBalance: map['cashBalance'], ); } String toJson() => json.encode(toMap()); factory HubManagerResponse.fromJson(String source) => HubManagerResponse.fromMap(json.decode(source)); @override String toString() { return 'HubManagerResponse(name: $name, email: $email, phone: $phone, cashBalance: $cashBalance, wards: )'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is HubManagerResponse && other.name == name && other.email == email && other.phone == phone && other.cashBalance == cashBalance; } @override int get hashCode { return name.hashCode ^ email.hashCode ^ phone.hashCode ^ cashBalance.hashCode; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/my_account
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/my_account/model/hub_manager_details_response.dart
class HubManagerDetailsResponse { late Message message; HubManagerDetailsResponse({required this.message}); HubManagerDetailsResponse.fromJson(Map<String, dynamic> json) { message = Message.fromJson(json['message']); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['message'] = message.toJson(); return data; } } class Message { late final int successKey; late final String message; late final String name; late final String fullName; late final String email; late final String mobileNo; late final String hubManager; late final String series; String? image; late final double balance; late final String appCurrency; late final String lastTransactionDate; late final List<Wards> wards; Message( {required this.successKey, required this.message, required this.name, required this.fullName, required this.email, required this.mobileNo, required this.hubManager, required this.series, required this.image, required this.balance, required this.appCurrency, required this.lastTransactionDate, required this.wards}); Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; name = json['name']; fullName = json['full_name']; email = json['email']; mobileNo = json['mobile_no'] ?? ""; hubManager = json['hub_manager'] ?? ""; series = json['series'] ?? "T-.YYYY.-.MM.-.####"; image = json['image']; balance = json['balance'] ?? 0; appCurrency = json['app_currency'] ?? "\$"; lastTransactionDate = json['last_transaction_date'] ?? ''; if (json['wards'] != null) { wards = []; json['wards'].forEach((v) { wards.add(Wards.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; data['name'] = name; data['full_name'] = fullName; data['email'] = email; data['mobile_no'] = mobileNo; data['hub_manager'] = hubManager; data['series'] = series; data['image'] = image; data['balance'] = balance; data['app_currency'] = appCurrency; data['last_transaction_date'] = lastTransactionDate; data['wards'] = wards.map((v) => v.toJson()).toList(); return data; } } class Wards { late final String ward; late final int isAssigned; Wards({required this.ward, required this.isAssigned}); Wards.fromJson(Map<String, dynamic> json) { ward = json['ward']; isAssigned = json['is_assigned']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['ward'] = ward; data['is_assigned'] = isAssigned; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/my_account
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/my_account/model/update_cash_balance_request.dart
import 'dart:convert'; class CashbalanceRequest { double cashBalance; CashbalanceRequest({ required this.cashBalance, }); CashbalanceRequest copyWith({ double? cashBalance, }) { return CashbalanceRequest( cashBalance: cashBalance ?? this.cashBalance, ); } Map<String, dynamic> toMap() { return { 'cashBalance': cashBalance, }; } factory CashbalanceRequest.fromMap(Map<String, dynamic> map) { return CashbalanceRequest( cashBalance: map['cashBalance'], ); } String toJson() => json.encode(toMap()); factory CashbalanceRequest.fromJson(String source) => CashbalanceRequest.fromMap(json.decode(source)); @override String toString() => 'CashbalanceRequest(cashBalance: $cashBalance)'; @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is CashbalanceRequest && other.cashBalance == cashBalance; } @override int get hashCode => cashBalance.hashCode; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/my_account
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/my_account/api/get_hub_manager_details.dart
import 'dart:convert'; import 'dart:developer'; import 'dart:typed_data'; import '../../../../../constants/app_constants.dart'; import '../../../../../database/db_utils/db_constants.dart'; import '../../../../../database/db_utils/db_hub_manager.dart'; import '../../../../../database/db_utils/db_preferences.dart'; import '../../../../../database/models/hub_manager.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/helpers/sync_helper.dart'; import '../model/hub_manager_details_response.dart'; class HubManagerDetails { Future<CommanResponse> getAccountDetails() async { //check if Internet is available or else if (await Helper.isNetworkAvailable()) { //Fetching hub manager id/email from DbPreferences String hubManagerId = await DBPreferences().getPreference(HubManagerId); //Creating map for request Map<String, String> data = {'hub_manager': hubManagerId}; //Call to my account api var apiResponse = await APIUtils.postRequest(MY_ACCOUNT_PATH, data); log(jsonEncode(apiResponse)); SyncHelper().checkCustomer(apiResponse["message"]["wards"]); //Parsing the api response HubManagerDetailsResponse hubManagerDetails = HubManagerDetailsResponse.fromJson(apiResponse); //If success response from api if (hubManagerDetails.message.message == "success") { var hubManagerData = hubManagerDetails.message; //Creating instance of DbHubManager DbHubManager dbHubManager = DbHubManager(); //Deleting the hub manager details await dbHubManager.delete(); var image = Uint8List.fromList([]); if (hubManagerData.image != null) { //Fetching image bytes (Uint8List) from image url image = await Helper.getImageBytesFromUrl(hubManagerData.image!); } //Creating hub manager object from api response HubManager hubManager = HubManager( id: hubManagerData.email, name: hubManagerData.fullName, phone: hubManagerData.mobileNo, emailId: hubManagerData.email, profileImage: image, cashBalance: hubManagerData.balance.toDouble(), ); appCurrency = hubManagerData.appCurrency; //Saving the HubManager data into the database await dbHubManager.addManager(hubManager); //Saving the Sales Series await DBPreferences() .savePreference(SalesSeries, hubManagerData.series); //returning the CommanResponse as true return CommanResponse( status: true, message: SUCCESS, apiStatus: ApiStatus.REQUEST_SUCCESS); } else { //If failure response from api //returning the CommanResponse as false with failure message. return CommanResponse( status: false, message: SOMETHING_WRONG, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { //If internet is not available //returning CommanResponse as false with message that no internet, //so loading data from local database (if available). return CommanResponse( status: false, message: NO_INTERNET_LOADING_DATA_FROM_LOCAL, apiStatus: ApiStatus.NO_INTERNET); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/sales_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/sales_history/model/sale_order_list_response.dart
class SalesOrderResponse { Message? message; SalesOrderResponse({this.message}); SalesOrderResponse.fromJson(Map<String, dynamic> json) { message = json['message'] != null ? Message.fromJson(json['message']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; if (message != null) { data['message'] = message!.toJson(); } return data; } } class Message { int? successKey; String? message; List<OrderList>? orderList; int? numberOfOrders; Message({this.successKey, this.message, this.orderList, this.numberOfOrders}); Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; if (json['order_list'] != null) { orderList = <OrderList>[]; json['order_list'].forEach((v) { orderList!.add(OrderList.fromJson(v)); }); } numberOfOrders = json['number_of_orders']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; if (orderList != null) { data['order_list'] = orderList!.map((v) => v.toJson()).toList(); } data['number_of_orders'] = numberOfOrders; return data; } } class OrderList { String? name; String? transactionDate; String? transactionTime; String? ward; String? customer; String? customerName; String? hubManager; double? grandTotal; String? modeOfPayment; String? mpesaNo; String? contactName; String? contactPhone; String? contactMobile; String? contactEmail; String? creation; String? hubManagerName; String? image; List<Items>? items; OrderList( {this.name, this.transactionDate, this.transactionTime, this.ward, this.customer, this.customerName, this.hubManager, this.grandTotal, this.modeOfPayment, this.mpesaNo, this.contactName, this.contactPhone, this.contactMobile, this.contactEmail, this.creation, this.hubManagerName, this.image, this.items}); OrderList.fromJson(Map<String, dynamic> json) { name = json['name']; transactionDate = json['transaction_date']; transactionTime = json['transaction_time']; ward = json['ward']; customer = json['customer']; customerName = json['customer_name']; hubManager = json['hub_manager']; grandTotal = json['grand_total']; modeOfPayment = json['mode_of_payment']; mpesaNo = json['mpesa_no']; contactName = json['contact_name'] ?? json['customer_name']; contactPhone = json['contact_phone'] ?? json['customer_name']; contactMobile = json['contact_mobile'] ?? json['customer_name']; contactEmail = json['contact_email'] ?? json['customer_name']; creation = json['creation']; hubManagerName = json['hub_manager_name']; image = json['image'] ?? ""; if (json['items'] != null) { items = <Items>[]; json['items'].forEach((v) { items!.add(Items.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['name'] = name; data['transaction_date'] = transactionDate; data['transaction_time'] = transactionTime; data['ward'] = ward; data['customer'] = customer; data['customer_name'] = customerName; data['hub_manager'] = hubManager; data['grand_total'] = grandTotal; data['mode_of_payment'] = modeOfPayment; data['mpesa_no'] = mpesaNo; data['contact_name'] = contactName; data['contact_phone'] = contactPhone; data['contact_mobile'] = contactMobile; data['contact_email'] = contactEmail; data['creation'] = creation; data['hub_manager_name'] = hubManagerName; data['image'] = image; if (items != null) { data['items'] = items!.map((v) => v.toJson()).toList(); } return data; } } class Items { String? itemCode; String? itemName; double? qty; String? uom; double? rate; double? amount; String? image; List<SubItems>? subItems; Items( {this.itemCode, this.itemName, this.qty, this.uom, this.rate, this.amount, this.image, this.subItems}); Items.fromJson(Map<String, dynamic> json) { itemCode = json['item_code']; itemName = json['item_name']; qty = json['qty']; uom = json['uom']; rate = json['rate']; amount = json['amount']; image = json['image']; if (json['sub_items'] != null) { subItems = <SubItems>[]; json['sub_items'].forEach((v) { subItems!.add(SubItems.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['item_code'] = itemCode; data['item_name'] = itemName; data['qty'] = qty; data['uom'] = uom; data['rate'] = rate; data['amount'] = amount; data['image'] = image; if (subItems != null) { data['sub_items'] = subItems!.map((v) => v.toJson()).toList(); } return data; } } class SubItems { String? itemCode; String? itemName; double? qty; String? uom; double? rate; double? amount; double? tax; String? associatedItem; String? image; SubItems( {this.itemCode, this.itemName, this.qty, this.uom, this.rate, this.amount, this.tax, this.associatedItem, this.image}); SubItems.fromJson(Map<String, dynamic> json) { itemCode = json['item_code']; itemName = json['item_name']; qty = json['qty']; uom = json['uom']; rate = json['rate']; amount = json['amount']; tax = json['tax'] ?? 0.0; associatedItem = json['associated_item']; image = json['image']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['item_code'] = itemCode; data['item_name'] = itemName; data['qty'] = qty; data['uom'] = uom; data['rate'] = rate; data['amount'] = amount; data['tax'] = tax; data['associated_item'] = associatedItem; data['image'] = image; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/sales_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/sales_history/api/get_previous_order.dart
import 'dart:developer'; import 'dart:typed_data'; import 'package:intl/intl.dart'; import '../../../../../constants/app_constants.dart'; import '../model/sale_order_list_response.dart'; import '../../../../../database/db_utils/db_constants.dart'; import '../../../../../database/db_utils/db_hub_manager.dart'; import '../../../../../database/db_utils/db_preferences.dart'; import '../../../../../database/db_utils/db_sale_order.dart'; import '../../../../../database/models/customer.dart'; import '../../../../../database/models/hub_manager.dart'; import '../../../../../database/models/order_item.dart'; import '../../../../../database/models/sale_order.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; class GetPreviousOrder { /// ///get old orders of hubmanager when user login in to the app /// Future<bool> getOrdersOnLogin() async { DateTime todaysDateTime = DateTime.now(); var dataUpto = todaysDateTime.subtract(const Duration(days: OFFLINE_DATA_FOR)); // Fetching hub manager id/email from DbPreferences String hubManagerId = await DBPreferences().getPreference(HubManagerId); //Getting the hub manager HubManager? hubManager = await DbHubManager().getManager(); //Creating GET api url String apiUrl = SALES_HISTORY; apiUrl += '?hub_manager=$hubManagerId&from_date=$dataUpto&to_date=$todaysDateTime'; // '?hub_manager=$hubManagerId&from_date=$dataUpto&to_date=${DateTime.now()}'; //Call to Sales History api var apiResponse = await APIUtils.getRequestWithHeaders(apiUrl); log('Sales History Response :: $apiResponse}'); if (apiResponse["message"]["message"] == "success") { List<SaleOrder> sales = []; //Parsing the JSON Response SalesOrderResponse salesOrderResponse = SalesOrderResponse.fromJson(apiResponse); //If success response from api if (salesOrderResponse.message!.orderList!.isNotEmpty) { await Future.forEach(salesOrderResponse.message!.orderList!, (orderEntry) async { OrderList order = orderEntry as OrderList; List<OrderItem> orderedProducts = []; await Future.forEach(order.items!, (item) async { Items orderedProduct = item as Items; //Getting product image Uint8List productImage = Uint8List.fromList([]); if (item.image != null && item.image!.isNotEmpty) { productImage = await Helper.getImageBytesFromUrl(item.image!); } OrderItem product = OrderItem( id: orderedProduct.itemCode!, name: orderedProduct.itemName!, group: '', description: '', stock: 0, price: orderedProduct.rate!, attributes: [], orderedQuantity: orderedProduct.qty!, productImage: productImage, productUpdatedTime: DateTime.now(), productImageUrl: '', tax: 0); //TODO:: Siddhant - Need to configure tax after deployment orderedProducts.add(product); }); //String orderTime = Helper.getTime(order.transactionTime); String transactionDateTime = "${order.transactionDate} ${order.transactionTime}"; String date = DateFormat('EEEE d, LLLL y') .format(DateTime.parse(transactionDateTime)) .toString(); // log('Date :1 $date'); //Need to convert 2:26:17 to 02:26 AM String time = DateFormat() .add_jm() .format(DateTime.parse(transactionDateTime)) .toString(); // log('Time : $time'); //Getting customer image // Uint8List customerImage = Uint8List.fromList([]); // if (order.customerImage.isNotEmpty) { // customerImage = // await Helper.getImageBytesFromUrl(order.customerImage); // } //Creating a SaleOrder SaleOrder saleOrder = SaleOrder( id: order.name!, date: date, time: time, customer: Customer( id: order.customer!, name: order.customerName!, phone: order.contactPhone!, email: order.contactEmail!, isSynced: true, modifiedDateTime: DateTime.now() ), items: orderedProducts, manager: hubManager!, orderAmount: order.grandTotal!, tracsactionDateTime: DateTime.parse(transactionDateTime), transactionId: order.mpesaNo ?? "", paymentMethod: order.modeOfPayment!, paymentStatus: "", transactionSynced: true, ); sales.add(saleOrder); }); return await DbSaleOrder().saveOrders(sales); } } return false; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/sales_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/sales_history/api/get_sales_history.dart
import 'dart:developer'; import 'dart:typed_data'; import 'package:intl/intl.dart'; import '../../../../../constants/app_constants.dart'; import '../../../mobile/sales_history/ui/sales_history.dart'; import '../model/sale_order_list_response.dart'; import '../../../../../database/db_utils/db_constants.dart'; import '../../../../../database/db_utils/db_hub_manager.dart'; import '../../../../../database/db_utils/db_preferences.dart'; import '../../../../../database/models/customer.dart'; import '../../../../../database/models/hub_manager.dart'; import '../../../../../database/models/order_item.dart'; import '../../../../../database/models/sale_order.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; class GetSalesHistory { int totalOrders = 1; double noOfPages = 0; Future<CommanResponse> getSalesHistory(int pageNo, String query) async { //If internet is available if (await Helper.isNetworkAvailable()) { //Fetching hub manager id/email from DbPreferences String hubManagerId = await DBPreferences().getPreference(HubManagerId); //Getting the hub manager HubManager? hubManager = await DbHubManager().getManager(); //Fetching the local orders data List<SaleOrder> sales = []; //Creating GET api url String apiUrl = SALES_HISTORY; // apiUrl += '?hub_manager=$hubManagerId&page_no=$pageNo'; if (query.length > 2) { apiUrl += '?hub_manager=$hubManagerId&txt=$query'; } else { apiUrl += '?hub_manager=$hubManagerId&page_no=$pageNo'; } //Call to Sales History api var apiResponse = await APIUtils.getRequestWithHeaders(apiUrl); // log('Sales History Response :: $apiResponse}'); if (apiResponse["message"]["message"] != "success") { return CommanResponse( status: false, message: NO_DATA_FOUND, apiStatus: ApiStatus.NO_DATA_AVAILABLE); } //Parsing the JSON Response SalesOrderResponse salesOrderResponse = SalesOrderResponse.fromJson(apiResponse); SalesHistory.pageSize = salesOrderResponse.message!.numberOfOrders!; totalOrders = salesOrderResponse.message!.numberOfOrders!; noOfPages = (totalOrders / SalesHistory.pageSize).ceilToDouble(); //If success response from api if (salesOrderResponse.message!.orderList!.isNotEmpty) { //Convert the api response to local model for (var order in salesOrderResponse.message!.orderList!) { if (!sales.any((element) => element.id == order.name)) { List<OrderItem> orderedProducts = []; //Ordered products for (var orderedProduct in order.items!) { OrderItem product = OrderItem( id: orderedProduct.itemCode!, // code: orderedProduct.itemCode, name: orderedProduct.itemName!, group: '', description: '', stock: 0, price: orderedProduct.rate!, attributes: [], orderedQuantity: orderedProduct.qty!, productImage: Uint8List.fromList([]), productImageUrl: orderedProduct.image, productUpdatedTime: DateTime.now()); orderedProducts.add(product); } String transactionDateTime = "${order.transactionDate} ${order.transactionTime}"; String date = DateFormat('EEEE d, LLLL y') .format(DateTime.parse(transactionDateTime)) .toString(); log('Date :2 $date'); //Need to convert 2:26:17 to 02:26 AM String time = DateFormat() .add_jm() .format(DateTime.parse(transactionDateTime)) .toString(); log('Time : $time'); //Creating a SaleOrder SaleOrder saleOrder = SaleOrder( id: order.name!, date: date, time: time, customer: Customer( id: order.customer!, name: order.customerName!, phone: order.contactPhone!, email: order.contactEmail!, isSynced: true, modifiedDateTime: DateTime.now() ), items: orderedProducts, manager: hubManager!, orderAmount: order.grandTotal!, tracsactionDateTime: DateTime.parse( '${order.transactionDate} ${order.transactionTime}'), transactionId: order.mpesaNo!, paymentMethod: order.modeOfPayment!, paymentStatus: "", transactionSynced: true, ); sales.add(saleOrder); } } return CommanResponse( status: true, message: sales, apiStatus: ApiStatus.REQUEST_SUCCESS); } //If failure response from api else { //Returning the comman response as false return CommanResponse( status: false, message: NO_DATA_FOUND, apiStatus: ApiStatus.REQUEST_FAILURE); } } //If internet connection is not available else { return CommanResponse( status: false, message: NO_INTERNET_LOADING_DATA_FROM_LOCAL, apiStatus: ApiStatus.NO_INTERNET); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/forgot_password
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/forgot_password/api/forgot_password_api.dart
import '../../../../../constants/app_constants.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; class ForgotPasswordApi { Future<CommanResponse> sendResetPasswordMail( String email, String instanceUrl) async { /* if (!_isvalidUrl(instanceUrl)) { return CommanResponse(status: false, message: INVALID_URL); }*/ if (!isValidEmail(email)) { //Return the email validation failed Response return CommanResponse(status: false, message: INVALID_EMAIL); } if (await Helper.isNetworkAvailable()) { String apiUrl = instanceUrl + FORGET_PASSWORD; apiUrl += '?user=$email'; var apiResponse = await APIUtils.getRequestWithCompleteUrl(apiUrl); if (apiResponse["message"]["success_key"] == 1) { return CommanResponse( status: true, message: SUCCESS, apiStatus: ApiStatus.REQUEST_SUCCESS); } else if (apiResponse["message"]["success_key"] == 0) { return CommanResponse( status: false, message: apiResponse["message"]["message"], apiStatus: ApiStatus.REQUEST_FAILURE); } else { return CommanResponse( status: false, message: SOMETHING_WENT_WRONG, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { return CommanResponse( status: false, message: NO_INTERNET, apiStatus: ApiStatus.NO_INTERNET); } } ///Function to check whether the input URL is valid or not static bool _isvalidUrl(String url) { // Regex to check valid URL String regex = "((http|https)://)(www.)?[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)"; return RegExp(regex).hasMatch(url); } ///Function to check whether email is in correct format or not. static bool isValidEmail(String email) { return RegExp( r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+") .hasMatch(email); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/login
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/login/model/login_response.dart
class LoginResponse { LoginResponse({ required this.message, required this.homePage, required this.fullName, }); Message? message; String? homePage; String? fullName; LoginResponse.fromJson(Map<String, dynamic> json) { message = Message.fromJson(json['message']); homePage = json['home_page']; fullName = json['full_name']; } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['message'] = message!.toJson(); data['home_page'] = homePage; data['full_name'] = fullName; return data; } } class Message { Message({ required this.successKey, required this.message, required this.sid, required this.apiKey, required this.apiSecret, required this.username, required this.email, }); int? successKey; String? message; String? sid; String? apiKey; String? apiSecret; String? username; String? email; Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; sid = json['sid']; apiKey = json['api_key']; apiSecret = json['api_secret']; username = json['username']; email = json['email']; } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; data['sid'] = sid; data['api_key'] = apiKey; data['api_secret'] = apiSecret; data['username'] = username; data['email'] = email; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/login
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/login/api/login_api_service.dart
import 'dart:developer'; import '../../../../../constants/app_constants.dart'; import '../../../../../database/db_utils/db_constants.dart'; import '../../../../../database/db_utils/db_preferences.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/helpers/sync_helper.dart'; import '../../../../database/db_utils/db_instance_url.dart'; import '../model/login_response.dart'; class LoginService { static Future<CommanResponse> login( String email, String password, String url) async { /* if (!_isValidUrl(url)) { return CommanResponse(status: false, message: INVALID_URL); }*/ if (!isValidEmail(email)) { //Return the email validation failed Response return CommanResponse(status: false, message: INVALID_EMAIL); } if (!isValidPassword(password)) { //Return the password validation failed Response return CommanResponse(status: false, message: invalidPasswordMsg); } //Check for the internet connection var isInternetAvailable = await Helper.isNetworkAvailable(); await DbInstanceUrl().saveUrl(url); String savedUrl = await DbInstanceUrl().getUrl(); log('Saved URL :: $savedUrl'); instanceUrl = url; if (isInternetAvailable) { //Login api url from api_constants String apiUrl = LOGIN_PATH; apiUrl += '?usr=$email&pwd=$password'; //Call to login api var apiResponse = await APIUtils.getRequest(apiUrl); //Parsing the login response LoginResponse loginResponse = LoginResponse.fromJson(apiResponse); //API success if (loginResponse.message!.successKey == 1) { DBPreferences dbPreferences = DBPreferences(); //Saving API Key and API secret in database. await dbPreferences.savePreference( ApiKey, loginResponse.message!.apiKey); await dbPreferences.savePreference( ApiSecret, loginResponse.message!.apiSecret); await dbPreferences.savePreference( HubManagerId, loginResponse.message!.email); await SyncHelper().loginFlow(); //Return the Success Login Response return CommanResponse( status: true, message: SUCCESS, apiStatus: ApiStatus.REQUEST_SUCCESS); } //API Failure else { //Return the Failure Login Response return CommanResponse( status: loginResponse.message!.successKey == 1 ? true : false, message: loginResponse.message!.message, apiStatus: ApiStatus.REQUEST_FAILURE); } } //If internet is not available else { return CommanResponse( status: false, message: NO_INTERNET, apiStatus: ApiStatus.NO_INTERNET); } } ///Function to check whether email is in correct format or not. static bool isValidEmail(String email) { return RegExp( r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+") .hasMatch(email); } ///Function to check whether password is in correct format or not. static bool isValidPassword(String password) { String regex = (r"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$"); return RegExp(regex).hasMatch(regex); } ///Function to check whether the input URL is valid or not static bool _isValidUrl(String url) { // Regex to check valid URL String regex = "((http|https)://)(www.)?[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)"; return RegExp(regex).hasMatch(url); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/login
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/login/api/verify_instance_service.dart
import 'package:nb_posx/network/api_constants/api_paths.dart'; import 'package:nb_posx/network/api_helper/api_status.dart'; import 'package:nb_posx/network/api_helper/comman_response.dart'; import 'package:nb_posx/network/service/api_utils.dart'; import 'package:nb_posx/utils%20copy/helper.dart'; import 'package:http/http.dart' as http; class VerificationUrl { static Future<CommanResponse> checkAppStatus() async { try { var isInternetAvailable = await Helper.isNetworkAvailable(); if (isInternetAvailable) { String apiPath = Verify_URL; var apiResponse = await APIUtils.getRequestVerify(apiPath); //var apiResponse = await ApiFunctions().getRequest(apiPath); var uri = Uri.parse(apiPath); var response = await http.get((uri)).timeout(const Duration(seconds: 30)); if (response.statusCode == 200) { //bool status = apiResponse[“message”]; return CommanResponse( status: true, message: true, apiStatus: ApiStatus.REQUEST_SUCCESS); } else { return CommanResponse( status: false, message: false, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { return CommanResponse( status: false, message: "No internet connection", apiStatus: ApiStatus.NO_INTERNET); } } catch (e) { return CommanResponse( status: false, message: e.toString(), apiStatus: ApiStatus.REQUEST_FAILURE); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/product
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/product/model/category_products_response.dart
class CategoryProductsResponse { List<Message>? message; CategoryProductsResponse({this.message}); CategoryProductsResponse.fromJson(Map<String, dynamic> json) { if (json['message'] != null) { message = <Message>[]; json['message'].forEach((v) { message!.add(Message.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; if (message != null) { data['message'] = message!.map((v) => v.toJson()).toList(); } return data; } } class Message { String? itemGroup; List<Items>? items; String? itemGroupImage; Message({this.itemGroup, this.items, this.itemGroupImage}); Message.fromJson(Map<String, dynamic> json) { itemGroup = json['item_group']; itemGroupImage = json['item_group_image']; if (json['items'] != null) { items = <Items>[]; json['items'].forEach((v) { items!.add(Items.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['item_group'] = itemGroup; data['item_group_image'] = itemGroupImage; if (items != null) { data['items'] = items!.map((v) => v.toJson()).toList(); } return data; } } class Items { String? id; String? name; List<Attributes>? attributes; String? image; List<Tax>? tax; double? productPrice; String? warehouse; double? stockQty; Items( {this.id, this.name, this.attributes, this.image, this.tax, this.productPrice, this.warehouse, this.stockQty}); Items.fromJson(Map<String, dynamic> json) { id = json['id']; name = json['name']; if (json['attributes'] != null) { attributes = <Attributes>[]; json['attributes'].forEach((v) { attributes!.add(Attributes.fromJson(v)); }); } image = json['image'] ?? ""; if (json['tax'] != null && json['tax'] != '') { tax = <Tax>[]; json['tax'].forEach((v) { tax!.add(Tax.fromJson(v)); }); } productPrice = json['product_price']; warehouse = json['warehouse']; stockQty = json['stock_qty'] == 0 ? 0.0 : json['stock_qty']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['id'] = id; data['name'] = name; if (attributes != null) { data['attributes'] = attributes!.map((v) => v.toJson()).toList(); } data['image'] = image; if (tax != null) { data['tax'] = tax!.map((v) => v.toJson()).toList(); } data['product_price'] = productPrice; data['warehouse'] = warehouse; data['stock_qty'] = stockQty; return data; } } class Attributes { String? name; String? type; int? moq; List<Options>? options; Attributes({this.name, this.type, this.moq, this.options}); Attributes.fromJson(Map<String, dynamic> json) { name = json['name']; type = json['type']; moq = json['moq']; if (json['options'] != null) { options = <Options>[]; json['options'].forEach((v) { options!.add(Options.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['name'] = name; data['type'] = type; data['moq'] = moq; if (options != null) { data['options'] = options!.map((v) => v.toJson()).toList(); } return data; } } class Options { String? id; String? name; List<Tax>? tax; double? price; bool? selected; String? warehouse; double? stockQty; Options( {this.id, this.name, this.tax, this.price, this.selected, this.warehouse, this.stockQty}); Options.fromJson(Map<String, dynamic> json) { id = json['id']; name = json['name']; if (json['tax'] != null && json['tax'] != '') { tax = <Tax>[]; json['tax'].forEach((v) { tax!.add(Tax.fromJson(v)); }); } price = json['price'] == "" ? 0.0 : json['price']; selected = json['selected']; warehouse = json['warehouse']; stockQty = double.tryParse(json['stock_qty'].toString()); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['id'] = id; data['name'] = name; if (tax != null) { data['tax'] = tax!.map((v) => v.toJson()).toList(); } data['price'] = price; data['selected'] = selected; data['warehouse'] = warehouse; data['stock_qty'] = stockQty; return data; } } class Tax { String? itemTaxTemplate; double? taxRate; Tax({this.itemTaxTemplate, this.taxRate}); Tax.fromJson(Map<String, dynamic> json) { itemTaxTemplate = json['item_tax_template'] ?? ""; taxRate = json['tax_rate'] ?? 0.0; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['item_tax_template'] = itemTaxTemplate; data['tax_rate'] = taxRate; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/product
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/product/model/products_response.dart
class ProductsResponse { late Message message; ProductsResponse({required this.message}); ProductsResponse.fromJson(Map<String, dynamic> json) { message = Message.fromJson(json['message']); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['message'] = message.toJson(); return data; } } class Message { late int successKey; late String message; late List<ItemList> itemList; Message( {required this.successKey, required this.message, required this.itemList}); Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; if (json['item_list'] != null) { itemList = []; json['item_list'].forEach((v) { itemList.add(ItemList.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; data['item_list'] = itemList.map((v) => v.toJson()).toList(); return data; } } class ItemList { late String itemCode; late String itemName; late String itemGroup; late String description; late int hasVariants; late String variantBasedOn; String? image; late double priceListRate; late String itemModified; late String priceModified; late double availableQty; late String stockModified; ItemList( {required this.itemCode, required this.itemName, required this.itemGroup, required this.description, required this.hasVariants, required this.variantBasedOn, required this.image, required this.priceListRate, required this.itemModified, required this.priceModified, required this.availableQty, required this.stockModified}); ItemList.fromJson(Map<String, dynamic> json) { itemCode = json['item_code']; itemName = json['item_name']; itemGroup = json['item_group']; description = json['description']; hasVariants = json['has_variants']; variantBasedOn = json['variant_based_on']; image = json['image']; priceListRate = json['price_list_rate']; itemModified = json['item_modified']; priceModified = json['price_modified']; availableQty = json['available_qty']; stockModified = json['stock_modified']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['item_code'] = itemCode; data['item_name'] = itemName; data['item_group'] = itemGroup; data['description'] = description; data['has_variants'] = hasVariants; data['variant_based_on'] = variantBasedOn; data['image'] = image; data['price_list_rate'] = priceListRate; data['item_modified'] = itemModified; data['price_modified'] = priceModified; data['available_qty'] = availableQty; data['stock_modified'] = stockModified; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/product
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/product/api/products_api_service.dart
import 'dart:convert'; import 'dart:developer'; import 'dart:typed_data'; import 'package:intl/intl.dart'; import '../../../../../constants/app_constants.dart'; import '../model/category_products_response.dart' as cat_resp; import '../../../../../database/db_utils/db_categories.dart'; import '../../../../../database/db_utils/db_constants.dart'; import '../../../../../database/db_utils/db_preferences.dart'; import '../../../../../database/db_utils/db_product.dart'; import '../../../../../database/models/attribute.dart'; import '../../../../../database/models/category.dart'; import '../../../../../database/models/option.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; import '../../../../../database/models/product.dart'; import '../model/products_response.dart'; class ProductsService { Future<CommanResponse> getCategoryProduct() async { if (await Helper.isNetworkAvailable()) { String lastSyncDateTime = await DBPreferences().getPreference(PRODUCT_LAST_SYNC_DATETIME); String formattedDate = lastSyncDateTime.isNotEmpty ? DateFormat("yyyy-MM-dd").format(DateTime.parse(lastSyncDateTime)) : ""; var categoryProductsPath = "$CATEGORY_PRODUCTS_PATH?from_date="; //Call to products list api var apiResponse = await APIUtils.getRequestWithHeaders(categoryProductsPath); log(jsonEncode(apiResponse)); cat_resp.CategoryProductsResponse resp = cat_resp.CategoryProductsResponse.fromJson(apiResponse); if (resp.message!.isNotEmpty) { List<Category> categories = []; await Future.forEach(resp.message!, (catObj) async { var catData = catObj as cat_resp.Message; //var image = Uint8List.fromList([]); var image = (catData.itemGroupImage == null || catData.itemGroupImage!.isEmpty) ? Uint8List.fromList([]) : await Helper.getImageBytesFromUrl(catData.itemGroupImage!); List<Product> products = []; await Future.forEach(catData.items!, (itemObj) async { var item = itemObj as cat_resp.Items; List<Attribute> attributes = []; await Future.forEach(item.attributes!, (attributeObj) async { var attributeData = attributeObj as cat_resp.Attributes; List<Option> options = []; for (var optionObj in attributeData.options!) { Option option = Option( id: optionObj.id!, name: optionObj.name!, price: optionObj.price!, selected: optionObj.selected!, tax: optionObj.tax != null ? optionObj.tax!.first.taxRate! : 0.0); options.add(option); } Attribute attrib = Attribute( name: attributeData.name!, moq: attributeData.moq!, type: attributeData.type!, options: options); attributes.add(attrib); }); var imageBytes = await Helper.getImageBytesFromUrl(item.image!); Product product = Product( id: item.id!, name: item.name!, group: catData.itemGroup!, description: '', stock: item.stockQty!, price: item.productPrice ?? 0.0, attributes: attributes, productImage: imageBytes, productImageUrl: item.image, productUpdatedTime: DateTime.now(), tax: item.tax != null && item.tax!.isNotEmpty ? item.tax!.first.taxRate! : 0.0); products.add(product); }); Category category = Category( id: catData.itemGroup!, name: catData.itemGroup!, image: image, items: products); categories.add(category); }); await DbCategory().addCategory(categories); await DBPreferences().savePreference( PRODUCT_LAST_SYNC_DATETIME, Helper.getCurrentDateTime()); //returning the CommanResponse as true return CommanResponse( status: true, message: SUCCESS, apiStatus: ApiStatus.REQUEST_SUCCESS); } else { //returning the CommanResponse as false with message from api. return CommanResponse( status: false, message: NO_PRODUCTS_FOUND_MSG, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { //returning CommanResponse as false with message that no internet, //so loading data from local database (if available). return CommanResponse( status: false, message: NO_INTERNET_LOADING_DATA_FROM_LOCAL, apiStatus: ApiStatus.NO_INTERNET); } } Future<CommanResponse> getProducts() async { if (await Helper.isNetworkAvailable()) { //Fetching hub manager id/email from DbPreferences String hubManagerId = await DBPreferences().getPreference(HubManagerId); String lastSyncDateTime = await DBPreferences().getPreference(PRODUCT_LAST_SYNC_DATETIME); String apiUrl = PRODUCTS_PATH; apiUrl += '?hub_manager=$hubManagerId&last_sync=$lastSyncDateTime'; //Call to products list api var apiResponse = await APIUtils.getRequestWithHeaders(apiUrl); log(jsonEncode(apiResponse)); //Parsing the JSON response ProductsResponse productData = ProductsResponse.fromJson(apiResponse); //If success response from api if (productData.message.message == "success") { //Creating the object of DBCustomer //Products list List<Product> products = []; //Populating the customer database with new data from api await Future.forEach(productData.message.itemList, (prodData) async { var product = prodData as ItemList; var image = Uint8List.fromList([]); if (product.image != null) { //Fetching image bytes (Uint8List) from image url image = await Helper.getImageBytesFromUrl(product.image!); } //Creating object for product Product tempProduct = Product( id: product.itemCode, name: product.itemName, group: product.itemGroup, description: product.description, stock: product.availableQty, price: product.priceListRate.toDouble(), attributes: [], productImage: image, productUpdatedTime: DateTime.parse(product.itemModified), tax: 0.0); //Adding product into the products list products.add(tempProduct); }); //Adding new products list into the database await DbProduct().addProducts(products); await DBPreferences().savePreference( PRODUCT_LAST_SYNC_DATETIME, Helper.getCurrentDateTime()); //returning the CommanResponse as true return CommanResponse( status: true, message: SUCCESS, apiStatus: ApiStatus.REQUEST_SUCCESS); } //If failure response from api else { //returning the CommanResponse as false with message from api. return CommanResponse( status: false, message: NO_PRODUCTS_FOUND_MSG, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { //returning CommanResponse as false with message that no internet, //so loading data from local database (if available). return CommanResponse( status: false, message: NO_INTERNET_LOADING_DATA_FROM_LOCAL, apiStatus: ApiStatus.NO_INTERNET); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/topics
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/topics/model/topic_response.dart
class TopicResponse { TopicResponse({ required this.message, }); late final Message message; TopicResponse.fromJson(Map<String, dynamic> json) { message = Message.fromJson(json['message']); } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['message'] = message.toJson(); return data; } } class Message { Message({ required this.successKey, required this.message, required this.privacyPolicy, required this.termsAndConditions, }); late final int successKey; late final String message; late final String privacyPolicy; late final String termsAndConditions; Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; privacyPolicy = json['Privacy_Policy']; termsAndConditions = json['Terms_and_Conditions']; } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; data['Privacy_Policy'] = privacyPolicy; data['Terms_and_Conditions'] = termsAndConditions; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/topics
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/topics/enums/topic_types.dart
// ignore_for_file: constant_identifier_names enum TopicTypes { PRIVACY_POLICY, TERMS_AND_CONDITIONS, }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/topics
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/topics/api/topic_api_service.dart
import '../../../../../../constants/app_constants.dart'; import '../../../../../../network/api_constants/api_paths.dart'; import '../../../../../../network/api_helper/api_status.dart'; import '../../../../../../network/api_helper/comman_response.dart'; import '../../../../../../network/service/api_utils.dart'; import '../../../../../../utils/helper.dart'; import '../enums/topic_types.dart'; import '../model/topic_response.dart'; ///Class to handle the api calls for terms and conditions and privacy policy class TopicDataService { ///Function to get privacy policy or terms & conditions data static Future<CommanResponse> getTopicData(TopicTypes topicTypes) async { //api url String apiUrl = TOPICS_PATH; //Check for internet connectivity bool isInternetAvailable = await Helper.isNetworkAvailable(); if (isInternetAvailable) { //Call to api var response = await APIUtils.getRequest(apiUrl); //Parsing the api JSON response TopicResponse topicResponse = TopicResponse.fromJson(response); //Checking if message is success, or not empty from api if (topicResponse.message.successKey == 1 || topicResponse.message.message == 'success') { //If requested type is privacy policy if (topicTypes == TopicTypes.PRIVACY_POLICY) { //Returning the CommanResponse as true with privacy policy data return CommanResponse( status: true, message: topicResponse.message.privacyPolicy, apiStatus: ApiStatus.REQUEST_SUCCESS); } //If requested type is terms and conditions else { //Returning the CommanResponse as true with terms & conditions data return CommanResponse( status: true, message: topicResponse.message.termsAndConditions, apiStatus: ApiStatus.REQUEST_SUCCESS); } } else { //Returning the CommanResponse as false, if no data found. return CommanResponse( status: true, message: NO_DATA_FOUND, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { //Returning CommanResponse as false with message that no internet return CommanResponse( status: false, message: NO_INTERNET, apiStatus: ApiStatus.NO_INTERNET); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/select_customer
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/select_customer/model/customer_response.dart
class NewCustomerResponse { Message? message; NewCustomerResponse({this.message}); NewCustomerResponse.fromJson(Map<String, dynamic> json) { message = json['message'] != null ? Message.fromJson(json['message']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; if (message != null) { data['message'] = message!.toJson(); } return data; } } class Message { int? successKey; String? message; List<CustomerRes>? customer; Message({this.successKey, this.message, this.customer}); Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; if (json['customer'] != null) { customer = <CustomerRes>[]; json['customer'].forEach((v) { customer!.add(CustomerRes.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; if (customer != null) { data['customer'] = customer!.map((v) => v.toJson()).toList(); } return data; } } class CustomerRes { String? name; String? customerName; String? customerPrimaryContact; String? mobileNo; String? emailId; dynamic primaryAddress; dynamic hubManager; CustomerRes( {this.name, this.customerName, this.customerPrimaryContact, this.mobileNo, this.emailId, this.primaryAddress, this.hubManager}); CustomerRes.fromJson(Map<String, dynamic> json) { name = json['name']; customerName = json['customer_name']; customerPrimaryContact = json['customer_primary_contact']; mobileNo = json['mobile_no']; emailId = json['email_id']; primaryAddress = json['primary_address']; hubManager = json['hub_manager']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['name'] = name; data['customer_name'] = customerName; data['customer_primary_contact'] = customerPrimaryContact; data['mobile_no'] = mobileNo; data['email_id'] = emailId; data['primary_address'] = primaryAddress; data['hub_manager'] = hubManager; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/select_customer
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/select_customer/model/create_customer_response.dart
class CreateCustomerResponse { Message? message; CreateCustomerResponse({this.message}); CreateCustomerResponse.fromJson(Map<String, dynamic> json) { message = json['message'] != null ? Message.fromJson(json['message']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; if (message != null) { data['message'] = message!.toJson(); } return data; } } class Message { int? successKey; String? message; CustomerRes? customer; Message({this.successKey, this.message, this.customer}); Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; customer = json['customer'] != null ? CustomerRes.fromJson(json['customer']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; if (customer != null) { data['customer'] = customer!.toJson(); } return data; } } class CustomerRes { String? name; String? customerName; String? mobileNo; String? emailId; CustomerRes({this.name, this.customerName, this.mobileNo, this.emailId}); CustomerRes.fromJson(Map<String, dynamic> json) { name = json['name']; customerName = json['customer_name']; mobileNo = json['mobile_no']; emailId = json['email_id'] ?? ""; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['name'] = name; data['customer_name'] = customerName; data['mobile_no'] = mobileNo; data['email_id'] = emailId; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/select_customer
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/select_customer/api/get_customer.dart
import '../../../../../constants/app_constants.dart'; import '../model/customer_response.dart'; import '../../../../../database/models/customer.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; class GetCustomer { //?mobile_no= Future<CommanResponse> getByMobileno(String mobileNo) async { // Check If internet available or not if (await Helper.isNetworkAvailable()) { //Creating GET api url String apiUrl = CUSTOMER_PATH; apiUrl += '?mobile_no=$mobileNo'; //Call to Sales History api var apiResponse = await APIUtils.getRequestWithHeaders(apiUrl); if (apiResponse["message"]["message"] == "Mobile Number Does Not Exist") { return CommanResponse( status: false, message: NO_DATA_FOUND, apiStatus: ApiStatus.NO_DATA_AVAILABLE); } NewCustomerResponse resp = NewCustomerResponse.fromJson(apiResponse); // var image = Uint8List.fromList([]); Customer tempCustomer = Customer( // profileImage: image, // ward: Ward(id: "1", name: "1"), email: resp.message!.customer!.first.emailId!, id: resp.message!.customer!.first.name!, name: resp.message!.customer!.first.customerName!, phone: resp.message!.customer!.first.mobileNo!, isSynced: true, modifiedDateTime: DateTime.now()); List<Customer> custlist = []; custlist.add(tempCustomer); //TODO:: Siddhant - Uncomment this if found any issue with the customer search //await DbCustomer().addCustomers(custlist); //returning the CommanResponse as true return CommanResponse( status: true, message: SUCCESS, apiStatus: ApiStatus.REQUEST_SUCCESS); } return CommanResponse( status: false, message: NO_INTERNET_LOADING_DATA_FROM_LOCAL, apiStatus: ApiStatus.NO_INTERNET); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/select_customer
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/select_customer/api/create_customer.dart
import 'dart:convert'; import 'dart:developer'; import '../../../../../constants/app_constants.dart'; import '../model/create_customer_response.dart'; import '../../../../../database/db_utils/db_customer.dart'; import '../../../../../database/models/customer.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; class CreateCustomer { Future<CommanResponse> createNew( String phone, String? name, String email) async { if (await Helper.isNetworkAvailable()) { //Creating map for request Map<String, String> requestBody = { 'customer_name': name??"Guest", 'mobile_no': phone, 'email_id': email }; var apiResponse = await APIUtils.postRequest(CREATE_CUSTOMER_PATH, requestBody); log(jsonEncode(apiResponse)); CreateCustomerResponse resp = CreateCustomerResponse.fromJson(apiResponse); if (apiResponse["message"]["message"] == "success") { if (resp.message!.message == "success") { // var image = Uint8List.fromList([]); Customer tempCustomer = Customer( // profileImage: image, // ward: Ward(id: "1", name: "1"), email: resp.message!.customer!.emailId!, id: resp.message!.customer!.name!, name: resp.message!.customer!.customerName!, phone: resp.message!.customer!.mobileNo!, isSynced: true, modifiedDateTime: DateTime.now()); List<Customer> customers = []; customers.add(tempCustomer); await DbCustomer().addCustomers(customers); return CommanResponse( status: true, message: tempCustomer, apiStatus: ApiStatus.REQUEST_SUCCESS); } } else if (resp.message!.successKey == 0) { Customer existingCustomer = Customer( id: resp.message!.customer!.name!, name: resp.message!.customer!.customerName!, email: resp.message!.customer!.emailId!, phone: resp.message!.customer!.mobileNo!, isSynced: true, modifiedDateTime: DateTime.now()); return CommanResponse( status: true, message: existingCustomer, apiStatus: ApiStatus.REQUEST_SUCCESS); } } return CommanResponse( status: false, message: NO_INTERNET, apiStatus: ApiStatus.NO_INTERNET); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/change_password
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/change_password/api/change_hubmanager_password.dart
import 'dart:convert'; import 'dart:developer'; import '../../../../../constants/app_constants.dart'; import '../../../../../database/db_utils/db_constants.dart'; import '../../../../../database/db_utils/db_preferences.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; class ChangeHubManagerPassword { Future<CommanResponse> changePassword(String newPass) async { // ignore: valid_regexps var passWordRegex = RegExp(r"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$"); if (!passWordRegex.hasMatch(newPass)) { return CommanResponse( status: false, message: invalidPasswordMsg, apiStatus: ApiStatus.NONE); } if (await Helper.isNetworkAvailable()) { //Fetching hub manager id/email from DbPreferences String hubManagerId = await DBPreferences().getPreference(HubManagerId); //Creating map for request Map<String, String> data = {'usr': hubManagerId, "pwd": newPass}; //Call to my account api var apiResponse = await APIUtils.postRequest(CHANGE_PASSWORD_PATH, data); log(jsonEncode(apiResponse)); return CommanResponse( status: true, message: SUCCESS, apiStatus: ApiStatus.REQUEST_SUCCESS); } else { return CommanResponse( status: false, message: NO_INTERNET, apiStatus: ApiStatus.NO_INTERNET); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order/model/create_sales_order_response.dart
class CreateSalesOrderResponse { CreateSalesOrderResponse({ required this.message, }); late final Message message; CreateSalesOrderResponse.fromJson(Map<String, dynamic> json) { message = Message.fromJson(json['message']); } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['message'] = message.toJson(); return data; } } class Message { Message({ required this.successKey, required this.message, required this.salesOrder, }); late final int successKey; late final String message; late final SalesOrder salesOrder; Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; salesOrder = SalesOrder.fromJson(json['sales_order'] ?? {}); } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; data['sales_order'] = salesOrder.toJson(); return data; } } class SalesOrder { SalesOrder({ required this.name, required this.docStatus, }); late final String name; late final int docStatus; SalesOrder.fromJson(Map<String, dynamic> json) { name = json['name'] ?? ""; docStatus = json['doc_status'] ?? 0; } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['name'] = name; data['doc_status'] = docStatus; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order/model/sales_order_request.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; class SalesOrderRequest { late String hubManager; late String customer; late String transactionDate; late String deliveryDate; late List<Items> items; late String modeOfPayment; late String mpesaNo; SalesOrderRequest( {required this.hubManager, required this.customer, required this.transactionDate, required this.deliveryDate, required this.items, required this.modeOfPayment, this.mpesaNo = ""}); SalesOrderRequest.fromJson(Map<String, dynamic> json) { hubManager = json['hub_manager']; customer = json['customer']; transactionDate = json['transaction_date']; deliveryDate = json['delivery_date']; if (json['items'] != null) { items = []; json['items'].forEach((v) { items.add(Items.fromJson(v)); }); } modeOfPayment = json['mode_of_payment']; mpesaNo = json['mpesa_no']; } Map toJson() { // final Map<String, dynamic> data = <String, dynamic>{}; // data['hub_manager'] = hubManager; // // data['ward'] = ward; // data['customer'] = customer; // data['transaction_date'] = transactionDate; // data['delivery_date'] = deliveryDate; // // ignore: unnecessary_null_comparison // if (items != null) { // data['items'] = items.map((v) => v.toJson()).toList(); // } // data['mode_of_payment'] = modeOfPayment; // data['mpesa_no'] = mpesaNo; List<Map> itemList = items.map((v) => v.toJson()).toList(); return { 'hub_manager': hubManager, 'customer': customer, 'transaction_date': transactionDate, 'delivery_date': deliveryDate, 'mode_of_payment': modeOfPayment, 'items': itemList }; } } class Items { String itemCode; String name; double price; List<SelectedOptions> selectedOption; double orderedQuantity; double orderedPrice; Items({ required this.itemCode, required this.name, required this.price, required this.selectedOption, required this.orderedQuantity, required this.orderedPrice, }); Items copyWith({ String? itemCode, String? name, double? price, List<SelectedOptions>? selectedOption, double? orderedQuantity, double? orderedPrice, }) { return Items( itemCode: itemCode ?? this.itemCode, name: name ?? this.name, price: price ?? this.price, selectedOption: selectedOption ?? this.selectedOption, orderedQuantity: orderedQuantity ?? this.orderedQuantity, orderedPrice: orderedPrice ?? this.orderedPrice, ); } Map<String, dynamic> toMap() { return { 'item_code': itemCode, 'item_name': name, 'rate': price, 'sub_items': selectedOption.map((x) => x.toMap()).toList(), 'qty': orderedQuantity, 'ordered_price': orderedPrice, }; } factory Items.fromMap(Map<String, dynamic> map) { return Items( itemCode: map['itemCode'] ?? '', name: map['name'] ?? '', price: map['price'] ?? '', selectedOption: List<SelectedOptions>.from( map['selectedOption']?.map((x) => SelectedOptions.fromMap(x))), orderedQuantity: map['orderedQuantity'] ?? '', orderedPrice: map['orderedPrice'] ?? '', ); } Map toJson() => toMap(); factory Items.fromJson(String source) => Items.fromMap(json.decode(source)); @override String toString() { return 'Items(itemCode: $itemCode, name: $name, price: $price, selectedOption: $selectedOption, orderedQuantity: $orderedQuantity, orderedPrice: $orderedPrice)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Items && other.itemCode == itemCode && other.name == name && other.price == price && listEquals(other.selectedOption, selectedOption) && other.orderedQuantity == orderedQuantity && other.orderedPrice == orderedPrice; } @override int get hashCode { return itemCode.hashCode ^ name.hashCode ^ price.hashCode ^ selectedOption.hashCode ^ orderedQuantity.hashCode ^ orderedPrice.hashCode; } } class SelectedOptions { String id; String name; double price; double qty; SelectedOptions({ required this.id, required this.name, required this.price, required this.qty, }); SelectedOptions copyWith({ String? id, String? name, double? price, double? qty, }) { return SelectedOptions( id: id ?? this.id, name: name ?? this.name, price: price ?? this.price, qty: qty ?? this.qty, ); } Map<String, dynamic> toMap() { return { 'item_code': id, 'item_name': name, 'qty': qty, 'rate': price, }; } factory SelectedOptions.fromMap(Map<String, dynamic> map) { return SelectedOptions( id: map['id'] ?? '', name: map['name'] ?? '', price: map['price']?.toDouble() ?? 0.0, qty: map['qty'] ?? 0.0, ); } String toJson() => json.encode(toMap()); factory SelectedOptions.fromJson(String source) => SelectedOptions.fromMap(json.decode(source)); @override String toString() => 'SelectedOptions(id: $id, name: $name, price: $price, qty: $qty)'; @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is SelectedOptions && other.id == id && other.name == name && other.price == price && other.qty == qty; } @override int get hashCode => id.hashCode ^ name.hashCode ^ price.hashCode ^ qty.hashCode; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order/model/promo_codes_response.dart
class PromoCodesResponse { Message? message; PromoCodesResponse({this.message}); PromoCodesResponse.fromJson(Map<String, dynamic> json) { message = json['message'] != null ? Message.fromJson(json['message']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; if (message != null) { data['message'] = message!.toJson(); } return data; } } class Message { int? successKey; String? message; List<CouponCode>? couponCode; Message({this.successKey, this.message, this.couponCode}); Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; if (json['coupon_code'] != null) { couponCode = <CouponCode>[]; json['coupon_code'].forEach((v) { couponCode!.add(CouponCode.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; if (couponCode != null) { data['coupon_code'] = couponCode!.map((v) => v.toJson()).toList(); } return data; } } class CouponCode { String? name; String? couponCode; String? pricingRule; int? maximumUse; int? used; String? description; String? validFrom; String? validUpto; String? applyOn; String? priceOrProductDiscount; int? minQty; int? maxQty; int? minAmt; int? maxAmt; String? rateOrDiscount; String? applyDiscountOn; int? discountAmount; int? rate; int? discountPercentage; CouponCode( {this.name, this.couponCode, this.pricingRule, this.maximumUse, this.used, this.description, this.validFrom, this.validUpto, this.applyOn, this.priceOrProductDiscount, this.minQty, this.maxQty, this.minAmt, this.maxAmt, this.rateOrDiscount, this.applyDiscountOn, this.discountAmount, this.rate, this.discountPercentage}); CouponCode.fromJson(Map<String, dynamic> json) { name = json['name']; couponCode = json['coupon_code']; pricingRule = json['pricing_rule']; maximumUse = json['maximum_use']; used = json['used']; description = json['description']; validFrom = json['valid_from']; validUpto = json['valid_upto']; applyOn = json['apply_on']; priceOrProductDiscount = json['price_or_product_discount']; minQty = json['min_qty']; maxQty = json['max_qty']; minAmt = json['min_amt']; maxAmt = json['max_amt']; rateOrDiscount = json['rate_or_discount']; applyDiscountOn = json['apply_discount_on']; discountAmount = json['discount_amount']; rate = json['rate']; discountPercentage = json['discount_percentage']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['name'] = name; data['coupon_code'] = couponCode; data['pricing_rule'] = pricingRule; data['maximum_use'] = maximumUse; data['used'] = used; data['description'] = description; data['valid_from'] = validFrom; data['valid_upto'] = validUpto; data['apply_on'] = applyOn; data['price_or_product_discount'] = priceOrProductDiscount; data['min_qty'] = minQty; data['max_qty'] = maxQty; data['min_amt'] = minAmt; data['max_amt'] = maxAmt; data['rate_or_discount'] = rateOrDiscount; data['apply_discount_on'] = applyDiscountOn; data['discount_amount'] = discountAmount; data['rate'] = rate; data['discount_percentage'] = discountPercentage; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order/api/create_sales_order.dart
import 'dart:convert'; import 'dart:developer'; import 'package:intl/intl.dart'; import '../../../../../constants/app_constants.dart'; import '../model/create_sales_order_response.dart'; import '../model/sales_order_request.dart' as request_items; import '../model/sales_order_request.dart'; import '../../../../../database/db_utils/db_parked_order.dart'; import '../../../../../database/models/order_item.dart'; import '../../../../../database/models/sale_order.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/helpers/sync_helper.dart'; class CreateOrderService { Future<CommanResponse> createOrder(SaleOrder order) async { if (await Helper.isNetworkAvailable()) { List<request_items.Items> items = []; for (OrderItem item in order.items) { List<request_items.SelectedOptions> selectedOption = []; for (var atrib in item.attributes) { for (var opt in atrib.options) { if (opt.selected) { selectedOption.add(request_items.SelectedOptions( id: opt.id, name: opt.name, price: opt.price, qty: item.orderedQuantity)); } } } request_items.Items i = request_items.Items( itemCode: item.id, name: item.name, price: item.price, selectedOption: selectedOption, orderedPrice: item.orderedPrice, orderedQuantity: item.orderedQuantity); items.add(i); } var transactionDateTime = DateFormat('yyyy-MM-dd HH:mm:ss').format(order.tracsactionDateTime); log('Formatted Transaction Date Time :: $transactionDateTime'); SalesOrderRequest orderRequest = SalesOrderRequest( hubManager: order.manager.emailId, // ward: "order.customer.ward.id", customer: order.customer.id, transactionDate: transactionDateTime, deliveryDate: _parseDate(order.tracsactionDateTime), items: items, modeOfPayment: order.paymentMethod, mpesaNo: order.transactionId, ); var body = {'order_list': orderRequest.toJson()}; log("${orderRequest.toJson()}"); log(json.encode(body)); var apiResponse = await APIUtils.postRequest(CREATE_SALES_ORDER_PATH, body); log(json.encode(apiResponse)); CreateSalesOrderResponse salesOrderResponse = CreateSalesOrderResponse.fromJson(apiResponse); SyncHelper().getDetails(); // ignore: unnecessary_null_comparison if (salesOrderResponse.message != null && salesOrderResponse.message.successKey == 1) { DbParkedOrder().deleteOrderById(order.parkOrderId!); return CommanResponse( status: true, message: salesOrderResponse.message.salesOrder.name, apiStatus: ApiStatus.REQUEST_SUCCESS); } else { return CommanResponse( status: false, message: SOMETHING_WRONG, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { return CommanResponse( status: false, message: NO_INTERNET_CREATE_ORDER_SYNC_QUEUED, apiStatus: ApiStatus.NO_INTERNET); } } String _parseDate(DateTime date) { var month = date.month < 10 ? "0${date.month}" : date.month; var day = date.day < 10 ? "0${date.day}" : date.day; var dateValue = '${date.year}-$month-$day'; log('Parsed date :: $dateValue'); return dateValue; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/create_order/api/promo_code_service.dart
import 'package:nb_posx/core/service/create_order/model/promo_codes_response.dart'; import 'package:nb_posx/network/api_constants/api_paths.dart'; import 'package:nb_posx/network/service/api_utils.dart'; import '../../../../constants/app_constants.dart'; import '../../../../network/api_helper/api_status.dart'; import '../../../../network/api_helper/comman_response.dart'; import '../../../../utils/helper.dart'; class PromoCodeservice { Future<CommanResponse> getPromoCodes() async { if (await Helper.isNetworkAvailable()) { String apiUrl = GET_ALL_PROMO_CODES_PATH; var apiResponse = await APIUtils.getRequest(apiUrl); Helper.printJSONData(apiResponse); PromoCodesResponse promoCodesResponse = PromoCodesResponse.fromJson(apiResponse); if (promoCodesResponse.message!.successKey == 1) { return CommanResponse( status: true, message: promoCodesResponse, apiStatus: ApiStatus.REQUEST_SUCCESS ); } else { return CommanResponse( status: false, message: NO_DATA_FOUND, apiStatus: ApiStatus.NO_DATA_AVAILABLE, ); } } else { return CommanResponse( status: false, message: NO_INTERNET_CREATE_ORDER_SYNC_QUEUED, apiStatus: ApiStatus.NO_INTERNET); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/customer
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/customer/model/customer_response.dart
class CustomersResponse { late Message message; CustomersResponse({required this.message}); CustomersResponse.fromJson(Map<String, dynamic> json) { if (json.isNotEmpty) message = Message.fromJson(json['message']); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['message'] = message.toJson(); return data; } } class Message { late int successKey; late String message; late List<CustomerList> customerList; Message( {required this.successKey, required this.message, required this.customerList}); Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; if (json['customer'] != null) { customerList = []; json['customer'].forEach((v) { customerList.add(CustomerList.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; data['customer'] = customerList.map((v) => v.toJson()).toList(); return data; } } class CustomerList { late String customerName; late String emailId; late String mobileNo; late String ward; late String wardName; late String name; late String creation; late String modified; late int disabled; String? image; CustomerList( {required this.customerName, required this.emailId, required this.mobileNo, required this.ward, required this.wardName, required this.name, required this.creation, required this.modified, required this.disabled, required this.image}); CustomerList.fromJson(Map<String, dynamic> json) { customerName = json['customer_name'] ?? "Guest"; emailId = json['email_id'] ?? ""; mobileNo = json['mobile_no'] ?? ""; ward = json['ward'] ?? ""; wardName = json['ward_name'] ?? ""; name = json['name'] ?? ""; creation = json['creation'] ?? ""; modified = json['modified'] ?? ""; disabled = json['disabled'] ?? 0; image = json['image'] ?? ""; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['customer_name'] = customerName; data['email_id'] = emailId; data['mobile_no'] = mobileNo; data['ward'] = ward; data['ward_name'] = wardName; data['name'] = name; data['creation'] = creation; data['modified'] = modified; data['disabled'] = disabled; data['image'] = image; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/customer
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/customer/api/customer_api_service.dart
import 'dart:convert'; import 'dart:developer'; import 'package:intl/intl.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../database/db_utils/db_constants.dart'; import '../../../../../database/db_utils/db_customer.dart'; import '../../../../../database/db_utils/db_preferences.dart'; import '../../../../../database/models/customer.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; import '../model/customer_response.dart'; ///[CustomerService] class for providing api calls functionality related to customer data. class CustomerService { ///Function to fetch the customer data from api & handle the responses. Future<CommanResponse> getCustomers({String searchTxt = ""}) async { // Check If internet available or not if (await Helper.isNetworkAvailable()) { //Fetching hub manager id/email from DbPreferences String hubManagerId = await DBPreferences().getPreference(HubManagerId); //Creating map for request Map<String, String> requestBody = {'hub_manager': hubManagerId}; String lastSyncDateTime = await DBPreferences().getPreference(CUSTOMER_LAST_SYNC_DATETIME); if (lastSyncDateTime.isNotEmpty) { requestBody.putIfAbsent('last_sync', () => lastSyncDateTime); } String formattedDate = lastSyncDateTime.isNotEmpty ? DateFormat("yyyy-MM-dd").format(DateTime.parse(lastSyncDateTime)) : ''; String customerUrl = '$NEW_GET_ALL_CUSTOMERS_PATH?search=$searchTxt&from_date=$lastSyncDateTime'; //Call to customer api var apiResponse = await APIUtils.getRequestWithHeaders(customerUrl); log(jsonEncode(apiResponse)); //If success response from api if (apiResponse["message"]["message"] == "success") { //Parsing the JSON response CustomersResponse customersResponse = CustomersResponse.fromJson(apiResponse); //If customers list is not empty from api if (customersResponse.message.message == "success") { //Creating customer list List<Customer> customers = []; //Populating the customer database with new data from api await Future.forEach(customersResponse.message.customerList, (customerData) async { var customer = customerData as CustomerList; // var image = Uint8List.fromList([]); // if (customer.image != null) { // //Fetching image bytes (Uint8List) from image url // image = await Helper.getImageBytesFromUrl(customer.image!); // } //Creating customer object Customer tempCustomer = Customer( id: customer.name, name: customer.customerName, email: customer.emailId, phone: customer.mobileNo, isSynced: true, modifiedDateTime: DateTime.now()); if (customer.disabled == 1) { await DbCustomer().deleteCustomer(tempCustomer.id); } else { var existingCustomer = await DbCustomer().getCustomer(tempCustomer.phone); if (existingCustomer.isEmpty) { customers.add(tempCustomer); } else { Customer modifiedCustomer = existingCustomer.first; modifiedCustomer.id = tempCustomer.id; modifiedCustomer.email = tempCustomer.email; modifiedCustomer.name = tempCustomer.name; modifiedCustomer.modifiedDateTime = tempCustomer.modifiedDateTime; modifiedCustomer.isSynced = true; modifiedCustomer.save(); //await DbCustomer().updateCustomer(modifiedCustomer); } } //Adding customer into customer list }); //Adding new customers into the database await DbCustomer().addCustomers(customers); await DBPreferences().savePreference( CUSTOMER_LAST_SYNC_DATETIME, Helper.getCurrentDateTime()); //returning the CommanResponse as true return CommanResponse( status: true, message: SUCCESS, apiStatus: ApiStatus.REQUEST_SUCCESS); } else { //If failure response from api //returning the CommanResponse as false with message from api. return CommanResponse( status: false, message: SOMTHING_WRONG_LOADING_LOCAL, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { await DBPreferences().savePreference( CUSTOMER_LAST_SYNC_DATETIME, Helper.getCurrentDateTime()); //If customer list is empty in api //Returning the CommanResponse as true with message No data available. return CommanResponse( status: true, message: NO_DATA_FOUND, apiStatus: ApiStatus.NO_DATA_AVAILABLE); } } else { //If internet is not available //returning CommanResponse as false with message that no internet, //so loading data from local database (if available). return CommanResponse( status: false, message: NO_INTERNET_LOADING_DATA_FROM_LOCAL, apiStatus: ApiStatus.NO_INTERNET); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/finance
mirrored_repositories/GETPOS-Flutter-App/lib/core/service/finance/api/get_updated_account_details.dart
import 'dart:convert'; import 'dart:developer'; import 'dart:typed_data'; import '../../../../../constants/app_constants.dart'; import '../../../../../database/db_utils/db_constants.dart'; import '../../../../../database/db_utils/db_hub_manager.dart'; import '../../../../../database/db_utils/db_preferences.dart'; import '../../../../../database/db_utils/db_sale_order.dart'; import '../../../../../database/models/hub_manager.dart'; import '../../../../../network/api_constants/api_paths.dart'; import '../../../../../network/api_helper/api_status.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../network/service/api_utils.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/helpers/sync_helper.dart'; import '../../my_account/model/hub_manager_details_response.dart'; class UpdatedHubManagerDetails { Future<CommanResponse> getUpdatedAccountDetails() async { //check if Internet is available or else if (await Helper.isNetworkAvailable()) { //Fetching hub manager id/email from DbPreferences String hubManagerId = await DBPreferences().getPreference(HubManagerId); //Creating map for request Map<String, String> data = {'hub_manager': hubManagerId}; //Call to my account api var apiResponse = await APIUtils.postRequest(MY_ACCOUNT_PATH, data); log(jsonEncode(apiResponse)); SyncHelper().checkCustomer(apiResponse["message"]["wards"]); //Parsing the api response HubManagerDetailsResponse hubManagerDetails = HubManagerDetailsResponse.fromJson(apiResponse); //If success response from api if (hubManagerDetails.message.message == "success") { var hubManagerData = hubManagerDetails.message; //Creating instance of DbHubManager DbHubManager dbHubManager = DbHubManager(); double offLineCashBalance = await DbSaleOrder().getOfflineOrderCashBalance(); // print("OFFLINE CASH BALANCE $offLineCashBalance"); // print("ONLINE CASH BALANCE ${hubManagerData.balance}"); var newCashbalance = hubManagerData.balance.toDouble() + offLineCashBalance; // print("NEW CASH BALANCE $newCashbalance"); //Deleting the hub manager details await dbHubManager.delete(); var image = Uint8List.fromList([]); if (hubManagerData.image != null) { //Fetching image bytes (Uint8List) from image url image = await Helper.getImageBytesFromUrl(hubManagerData.image!); } //Creating hub manager object from api response HubManager hubManager = HubManager( id: hubManagerData.email, name: hubManagerData.fullName, phone: hubManagerData.mobileNo, emailId: hubManagerData.email, profileImage: image, cashBalance: newCashbalance, ); //Saving the HubManager data into the database await dbHubManager.addManager(hubManager); //Saving the Sales Series await DBPreferences() .savePreference(SalesSeries, hubManagerData.series); //returning the CommanResponse as true return CommanResponse( status: true, message: SUCCESS, apiStatus: ApiStatus.REQUEST_SUCCESS); } else { //If failure response from api //returning the CommanResponse as false with failure message. return CommanResponse( status: false, message: SOMETHING_WRONG, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { //If internet is not available //returning CommanResponse as false with message that no internet, //so loading data from local database (if available). return CommanResponse( status: false, message: NO_INTERNET_LOADING_DATA_FROM_LOCAL, apiStatus: ApiStatus.NO_INTERNET); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/my_account
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/my_account/ui/my_account.dart
import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/route_manager.dart'; import 'package:package_info_plus/package_info_plus.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../database/db_utils/db_hub_manager.dart'; import '../../../../../database/db_utils/db_sale_order.dart'; import '../../../../../database/models/hub_manager.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/helpers/sync_helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../utils/ui_utils/text_styles/edit_text_hint_style.dart'; import '../../../../../widgets/custom_appbar.dart'; import '../../change_password/ui/change_password.dart'; import '../../login/ui/login.dart'; class MyAccount extends StatefulWidget { const MyAccount({Key? key}) : super(key: key); @override State<MyAccount> createState() => _MyAccountState(); } class _MyAccountState extends State<MyAccount> { String? name, email, phone, version; late Uint8List profilePic; @override void initState() { super.initState(); profilePic = Uint8List.fromList([]); getManagerName(); } ///Function to fetch the hub manager account details getManagerName() async { PackageInfo packageInfo = await PackageInfo.fromPlatform(); //Fetching the data from database HubManager manager = await DbHubManager().getManager() as HubManager; name = manager.name; email = manager.emailId; phone = manager.phone; version = "$APP_VERSION - ${packageInfo.version}"; profilePic = manager.profileImage; setState(() {}); } Widget _actionListItem(imageAsset, label) => Row( children: [ Padding( padding: const EdgeInsets.fromLTRB( MY_ACCOUNT_ICON_PADDING_LEFT, MY_ACCOUNT_ICON_PADDING_TOP, MY_ACCOUNT_ICON_PADDING_RIGHT, MY_ACCOUNT_ICON_PADDING_BOTTOM), child: SvgPicture.asset( imageAsset, width: MY_ACCOUNT_ICON_WIDTH, ), ), Text( label, style: getBoldStyle(), ) ], ); @override Widget build(BuildContext context) { return Scaffold( // endDrawer: MainDrawer( // menuItem: Helper.getMenuItemList(context), // ), body: SafeArea( child: Column( children: [ const CustomAppbar(title: MY_ACCOUNT_TXT, hideSidemenu: true), hightSpacer30, _getProfileImage(), hightSpacer10, Text(name ?? "", style: getTextStyle( fontWeight: FontWeight.w700, fontSize: MEDIUM_PLUS_FONT_SIZE, )), Padding( padding: smallPaddingAll(), child: Text(email ?? "", style: getTextStyle( color: MAIN_COLOR, fontSize: MEDIUM_MINUS_FONT_SIZE, fontWeight: FontWeight.normal)), ), Text(phone ?? "", style: getTextStyle( fontWeight: FontWeight.w600, fontSize: MEDIUM_PLUS_FONT_SIZE, )), hightSpacer25, Container( margin: horizontalSpace(x: 32), height: 100, child: Column( children: [ InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const ChangePassword())); }, child: _actionListItem(CHANGE_PASSWORD_IMAGE, CHANGE_PASSWORD), ), const Divider(), InkWell( onTap: () => handleLogout(), child: _actionListItem(LOGOUT_IMAGE, LOGOUT_TITLE), ), ], ), // decoration: BoxDecoration( // borderRadius: // BorderRadius.circular(BORDER_CIRCULAR_RADIUS_20), // boxShadow: [boxShadow]), ), const Spacer(), Center( child: Text( version ?? APP_VERSION_FALLBACK, style: getHintStyle(), )), hightSpacer10 ], ), ), ); } Future<void> handleLogout() async { await SyncHelper().logoutFlow(); Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (context) => const Login()), (Route<dynamic> route) => false); // var offlineOrders = await DbSaleOrder().getOfflineOrders(); // if (offlineOrders.isEmpty) { // if (!mounted) return; // var res = await Helper.showConfirmationPopup( // context, LOGOUT_QUESTION, OPTION_YES, // // await SyncHelper().logoutFlow(); // // Get.offAll(() => const Login()); // hasCancelAction: true); // if (res != OPTION_CANCEL.toLowerCase()) { // // await SyncHelper().logoutFlow(); // // if (!mounted) return;sss // // Navigator.pop(context); // // Navigator.pushReplacement( // // context, MaterialPageRoute(builder: (context) => const Login())); // } // } else { // if (!mounted) return; // await Helper.showConfirmationPopup(context, OFFLINE_ORDER_MSG, OPTION_OK); // // print("You clicked $res"); // } // await SyncHelper().logoutFlow(); // Get.offAll(() => const Login()); } Widget _getProfileImage() { return profilePic.isEmpty ? SvgPicture.asset( MY_ACCOUNT_IMAGE, width: 200, ) : CircleAvatar( radius: 64, backgroundColor: MAIN_COLOR, foregroundImage: MemoryImage(profilePic), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/add_products
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/add_products/ui/added_product_item.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:nb_posx/utils/ui_utils/spacer_widget.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../database/models/attribute.dart'; import '../../../../database/models/order_item.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class AddedProductItem extends StatefulWidget { Function? onDelete; Function? onItemAdd; Function? onItemRemove; OrderItem product; bool? disableDeleteOption; bool isUsedinVariantsPopup; AddedProductItem( {Key? key, required this.onDelete, required this.onItemAdd, required this.onItemRemove, this.disableDeleteOption = false, required this.product, this.isUsedinVariantsPopup = false}) : super(key: key); @override State<AddedProductItem> createState() => _AddedProductItemState(); } class _AddedProductItemState extends State<AddedProductItem> { final Widget _greySizedBox = SizedBox(width: 1.0, child: Container(color: MAIN_COLOR)); @override Widget build(BuildContext context) { String selectedQty = widget.product.orderedQuantity < 10 ? "0${widget.product.orderedQuantity.round()}" : "${widget.product.orderedQuantity.round()}"; return Row( children: [ Container( height: 90, width: 90, clipBehavior: Clip.hardEdge, decoration: BoxDecoration( color: MAIN_COLOR.withOpacity(0.1), borderRadius: const BorderRadius.all(Radius.circular(10)), ), child: widget.product.productImage.isEmpty ? SvgPicture.asset( PRODUCT_IMAGE_SMALL, fit: BoxFit.contain, ) : Image.memory( widget.product.productImage, fit: BoxFit.fill, ), ), widthSpacer(15), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( widget.product.name, style: getTextStyle(fontSize: LARGE_FONT_SIZE), overflow: TextOverflow.ellipsis, maxLines: 1, ), Row(children: [ Visibility( visible: !widget.disableDeleteOption!, child: InkWell( onTap: () => widget.onDelete!(), child: Padding( padding: miniPaddingAll(), child: SvgPicture.asset(DELETE_IMAGE, height: 18, color: DARK_GREY_COLOR, fit: BoxFit.contain)))), Visibility( visible: widget.isUsedinVariantsPopup, child: InkWell( onTap: () => Navigator.pop(context), child: Padding( padding: miniPaddingAll(), child: SvgPicture.asset(CROSS_ICON, height: 20, color: BLACK_COLOR, fit: BoxFit.contain)))) ]), ], ), Text( widget.isUsedinVariantsPopup ? 'Item Code - ${widget.product.id}' : "${_getItemVariants(widget.product.attributes)} x ${widget.product.orderedQuantity.toInt()}", style: getTextStyle( fontSize: SMALL_FONT_SIZE, fontWeight: FontWeight.normal), overflow: TextOverflow.ellipsis, maxLines: 2, ), hightSpacer15, Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '$appCurrency ${widget.product.price.toStringAsFixed(2)}', style: getTextStyle( fontWeight: FontWeight.w600, fontSize: MEDIUM_PLUS_FONT_SIZE, color: MAIN_COLOR), ), Visibility( visible: widget.isUsedinVariantsPopup, child: Text( "Stock - ${widget.product.stock}", style: getTextStyle( fontWeight: FontWeight.bold, fontSize: MEDIUM_FONT_SIZE, color: GREEN_COLOR, ), )), ], ), Container( width: 100, height: 25, decoration: BoxDecoration( border: Border.all( color: MAIN_COLOR, ), borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_08)), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ InkWell( onTap: () => widget.onItemRemove!(), child: const Icon( Icons.remove, size: 25, )), _greySizedBox, Container( color: MAIN_COLOR.withOpacity(0.1), child: Text( selectedQty, style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w600, color: MAIN_COLOR, ), )), _greySizedBox, InkWell( onTap: () => widget.onItemAdd!(), child: const Icon( Icons.add, size: 25, )), ], )) ]), ], )), ], ); // return ListTile( // isThreeLine: true, // contentPadding: horizontalSpace(x: 10), // minVerticalPadding: 10, // leading: SizedBox( // // height: 70, // // width: 70, // child: Container( // height: 100, // width: 100, // decoration: BoxDecoration( // color: MAIN_COLOR.withOpacity(0.1), // borderRadius: const BorderRadius.all(Radius.circular(10))), // child: widget.product.productImage.isEmpty // ? SvgPicture.asset( // PRODUCT_IMAGE_SMALL, // // height: 50, // // width: 50, // fit: BoxFit.contain, // ) // : Image.memory(widget.product.productImage))), // title: Padding( // padding: horizontalSpace(x: 5), // child: Row( // mainAxisAlignment: MainAxisAlignment.spaceBetween, // children: [ // Expanded( // child: Column( // mainAxisAlignment: MainAxisAlignment.spaceEvenly, // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Text( // widget.product.name, // style: getTextStyle(fontSize: SMALL_PLUS_FONT_SIZE), // overflow: TextOverflow.ellipsis, // maxLines: 2, // ), // Text( // "Item Code - ${widget.product.id}", // style: getTextStyle( // fontSize: SMALL_MINUS_FONT_SIZE, // color: DARK_GREY_COLOR, // fontWeight: FontWeight.normal), // ) // ], // )), // Visibility( // visible: !widget.disableDeleteOption!, // child: InkWell( // onTap: () => widget.onDelete!(), // child: Padding( // padding: miniPaddingAll(), // child: SvgPicture.asset( // DELETE_IMAGE, // height: 15, // // width: 20, // color: DARK_GREY_COLOR, // fit: BoxFit.contain, // ))), // ) // ], // )), // subtitle: Padding( // padding: horizontalSpace(x: 5), // child: Row( // mainAxisAlignment: MainAxisAlignment.spaceBetween, // children: [ // Column( // mainAxisAlignment: MainAxisAlignment.end, // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Text( // "$ADD_PRODUCTS_AVAILABLE_STOCK_TXT - ${widget.product.stock}", // style: getTextStyle( // fontWeight: FontWeight.normal, // fontSize: SMALL_MINUS_FONT_SIZE, // color: WHITE_COLOR, // ), // ), // Text( // '$APP_CURRENCY ${widget.product.orderedPrice}', // style: getTextStyle( // fontWeight: FontWeight.w400, // fontSize: SMALL_PLUS_FONT_SIZE, // color: MAIN_COLOR), // ), // ], // ), // Container( // width: 100, // height: 25, // decoration: BoxDecoration( // border: Border.all( // color: GREY_COLOR, // ), // borderRadius: // BorderRadius.circular(BORDER_CIRCULAR_RADIUS_08)), // child: Row( // mainAxisAlignment: MainAxisAlignment.spaceEvenly, // children: [ // InkWell( // onTap: () => widget.onItemAdd!(), // child: const Icon( // Icons.add, // size: 18, // color: DARK_GREY_COLOR, // )), // _greySizedBox, // Text( // selectedQty, // style: getTextStyle( // fontSize: MEDIUM_FONT_SIZE, // fontWeight: FontWeight.w600, // color: MAIN_COLOR), // ), // _greySizedBox, // InkWell( // onTap: () => widget.onItemRemove!(), // child: const Icon( // Icons.remove, // size: 18, // color: DARK_GREY_COLOR, // )), // ], // )) // ], // )), // ); } String _getItemVariants(List<Attribute> itemVariants) { String variants = ''; if (itemVariants.isNotEmpty) { for (var variantData in itemVariants) { for (var selectedOption in variantData.options) { if (selectedOption.selected) { variants = variants.isEmpty ? '${selectedOption.name} [$appCurrency ${selectedOption.price.toStringAsFixed(2)}]' : "$variants, ${selectedOption.name} [$appCurrency ${selectedOption.price.toStringAsFixed(2)}]"; } } } } return variants; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/add_products
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/add_products/ui/added_products_widget.dart
// import 'package:nb_pos/configs/theme_config.dart'; // import 'package:nb_pos/constants/app_constants.dart'; // import 'package:nb_pos/core/add_products/ui/added_product_item.dart'; // import 'package:nb_pos/database/models/order_item.dart'; // import 'package:nb_pos/database/models/product.dart'; // import 'package:nb_pos/utils/ui_utils/padding_margin.dart'; // import 'package:nb_pos/utils/ui_utils/text_styles.dart/custom_text_style.dart'; // import 'package:flutter/cupertino.dart'; // import 'package:flutter/material.dart'; // import 'package:flutter/painting.dart'; // // ignore: must_be_immutable // class AddProductsWidget extends StatefulWidget { // Function(Product product)? onDelete; // Function(Product product)? onItemAdd; // Function(Product product)? onItemRemove; // Function? onAddMoreProducts; // List<OrderItem> orderedProducts; // AddProductsWidget( // {Key? key, // required this.onDelete, // required this.onItemAdd, // required this.onItemRemove, // required this.onAddMoreProducts, // required this.orderedProducts}) // : super(key: key); // @override // _AddProductsWidgetState createState() => _AddProductsWidgetState(); // } // class _AddProductsWidgetState extends State<AddProductsWidget> { // Widget dividerLine = Padding( // padding: topSpace(), child: const Divider(height: 1, color: GREY_COLOR)); // @override // Widget build(BuildContext context) { // return Padding( // padding: horizontalSpace(), // child: Card( // elevation: 2.0, // child: Padding( // padding: const EdgeInsets.only(top: 15, left: 10, right: 10), // child: Column( // children: [ // Align( // alignment: AlignmentDirectional.topStart, // child: Text( // ADD_PRODUCT_TXT, // style: getTextStyle(), // )), // ListView.separated( // separatorBuilder: (context, index) { // return dividerLine; // }, // shrinkWrap: true, // itemCount: widget.orderedProducts.length, // primary: false, // itemBuilder: (context, position) { // return AddedProductItem( // product: widget.orderedProducts[position], // onDelete: () => widget // .onDelete!(widget.orderedProducts[position]), // onItemAdd: () => widget // .onItemAdd!(widget.orderedProducts[position]), // onItemRemove: () => widget // .onItemRemove!(widget.orderedProducts[position]), // ); // }), // dividerLine, // TextButton( // onPressed: () => widget.onAddMoreProducts!(), // child: Text( // ADD_MORE_PRODUCTS, // style: getTextStyle(color: MAIN_COLOR), // )) // ], // ), // ))); // } // }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/add_products
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/add_products/ui/add_products_screen.dart
// import 'package:nb_pos/constants/app_constants.dart'; // import 'package:nb_pos/database/db_utils/db_product.dart'; // import 'package:nb_pos/database/models/product.dart'; // import 'package:nb_pos/utils/helper.dart'; // import 'package:nb_pos/utils/ui_utils/spacer_widget.dart'; // import 'package:nb_pos/utils/ui_utils/padding_margin.dart'; // import 'package:nb_pos/utils/ui_utils/text_styles.dart/custom_text_style.dart'; // import 'package:nb_pos/widgets/custom_appbar.dart'; // import 'package:nb_pos/widgets/long_button_widget.dart'; // import 'package:nb_pos/widgets/product_shimmer_widget.dart'; // import 'package:nb_pos/widgets/product_widget.dart'; // import 'package:nb_pos/widgets/search_widget.dart'; // import 'package:flutter/cupertino.dart'; // import 'package:flutter/material.dart'; // // ignore: must_be_immutable // class AddProductsScreen extends StatefulWidget { // List<Product> orderedProducts; // AddProductsScreen({Key? key, required this.orderedProducts}) // : super(key: key); // @override // _AddProductsScreenState createState() => _AddProductsScreenState(); // } // class _AddProductsScreenState extends State<AddProductsScreen> { // List<Product> products = []; // List<Product> orderedProducts = []; // List<Product> productsToOrder = []; // late double totalAmount; // int totalItems = 0; // late TextEditingController searchProductsController; // bool isProductsFound = true; // @override // void initState() { // super.initState(); // searchProductsController = TextEditingController(); // getProducts(0); // orderedProducts.addAll(widget.orderedProducts); // totalItems = widget.orderedProducts.length; // totalAmount = 0.0; // orderedProducts.forEach((product) async { // totalAmount = totalAmount + (product.price * product.orderedQuantity); // }); // } // @override // void dispose() { // searchProductsController.dispose(); // super.dispose(); // } // @override // Widget build(BuildContext context) { // return Scaffold( // body: SafeArea( // child: SingleChildScrollView( // physics: products.isEmpty // ? const NeverScrollableScrollPhysics() // : const ScrollPhysics(), // child: Column( // children: [ // const CustomAppbar(title: ADD_PRODUCT_TXT), // hightSpacer10, // Container( // margin: horizontalSpace(), // child: SearchWidget( // searchHint: ADD_PRODUCTS_SEARCH_TXT, // searchTextController: searchProductsController, // onTextChanged: (text) { // if (text.isNotEmpty) { // filterProductsData(text); // } else { // getProducts(0); // } // }, // onSubmit: (text) { // if (text.isNotEmpty) { // filterProductsData(text); // } else { // getProducts(0); // } // }, // )), // Visibility( // visible: isProductsFound, // child: Padding( // padding: const EdgeInsets.fromLTRB(16, 12, 16, 12), // child: GridView.builder( // itemCount: products.isEmpty ? 10 : products.length, // gridDelegate: // const SliverGridDelegateWithFixedCrossAxisCount( // crossAxisCount: 2, // mainAxisSpacing: 16, // crossAxisSpacing: 16, // childAspectRatio: 0.80, // mainAxisExtent: 215), // shrinkWrap: true, // padding: bottomSpace(), // physics: const BouncingScrollPhysics(), // itemBuilder: (context, position) { // if (products.isEmpty) { // return const ProductShimmer(); // } else { // return ProductWidget( // title: ADD_PRODUCT_TITLE, // asset: products[position].productImage, // enableAddProductButton: true, // product: products[position], // onAddToCart: () { // Product product = products[position]; // addProductIntoCart(product); // }, // ); // } // }, // ))), // Visibility( // visible: !isProductsFound, // child: Center( // child: Text( // NO_DATA_FOUND, // style: getTextStyle( // fontWeight: FontWeight.w600, // fontSize: SMALL_PLUS_FONT_SIZE), // ))) // ], // ), // ), // ), // bottomNavigationBar: LongButton( // buttonTitle: ADD_CONTINUE, // isAmountAndItemsVisible: true, // totalAmount: '$totalAmount', // totalItems: '$totalItems', // onTap: () { // productsToOrder.clear(); // productsToOrder.addAll(orderedProducts); // Navigator.pop(context, productsToOrder); // }, // ), // ); // } // Future<void> getProducts(val) async { // //Fetching data from DbProduct database // products = await DbProduct().getAllProducts(); // isProductsFound = products.isNotEmpty; // if (val == 0) setState(() {}); // } // void addProductIntoCart(Product product) async { // Product productData = product; // Product prod = orderedProducts.singleWhere( // (element) => element.id == product.id, // orElse: () => productData); // if (prod.orderedQuantity + 1 <= productData.stock) { // if (orderedProducts.any((element) => element.id == productData.id)) { // //productData.orderedQuantity = productData.orderedQuantity + 1; // int indexOfProduct = orderedProducts // .indexWhere((element) => element.id == productData.id); // Product tempProduct = orderedProducts.elementAt(indexOfProduct); // productData.orderedQuantity = tempProduct.orderedQuantity + 1; // orderedProducts.removeAt(indexOfProduct); // orderedProducts.insert(indexOfProduct, productData); // } else { // productData.orderedQuantity = productData.orderedQuantity + 1; // orderedProducts.add(productData); // } // totalItems = orderedProducts.length; // totalAmount = 0.0; // orderedProducts.forEach((product) { // totalAmount = totalAmount + (product.price * product.orderedQuantity); // }); // setState(() {}); // } else { // Helper.showSnackBar(context, INSUFFICIENT_STOCK_ERROR); // } // } // void filterProductsData(String searchText) async { // await getProducts(1); // products = products // .where((element) => // element.name.toLowerCase().contains(searchText.toLowerCase()) || // element.id.toLowerCase().contains(searchText.toLowerCase())) // .toList(); // isProductsFound = products.isNotEmpty; // setState(() {}); // } // }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order_new
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order_new/ui/cart_screen.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:intl/intl.dart'; import 'package:nb_posx/core/mobile/home/ui/product_list_home.dart'; import 'package:nb_posx/core/mobile/parked_orders/ui/orderlist_screen.dart'; import 'package:nb_posx/core/service/create_order/api/promo_code_service.dart'; import 'package:nb_posx/core/service/create_order/model/promo_codes_response.dart'; import 'package:nb_posx/network/api_helper/api_status.dart'; import 'package:nb_posx/network/api_helper/comman_response.dart'; import 'package:nb_posx/utils/ui_utils/spacer_widget.dart'; import 'package:nb_posx/widgets/long_button_widget.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../database/db_utils/db_parked_order.dart'; import '../../../../../database/models/order_item.dart'; import '../../../../../database/models/park_order.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../widgets/custom_appbar.dart'; import '../../../../../widgets/product_shimmer_widget.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../database/db_utils/db_hub_manager.dart'; import '../../../../database/models/hub_manager.dart'; import '../../../../database/models/sale_order.dart'; import '../../../../utils/helper.dart'; import '../../add_products/ui/added_product_item.dart'; import '../../sale_success/ui/sale_success_screen.dart'; import '../../select_customer/ui/new_select_customer.dart'; import 'new_create_order.dart'; // ignore: must_be_immutable class CartScreen extends StatefulWidget { ParkOrder order; CartScreen({required this.order, Key? key}) : super(key: key); @override State<CartScreen> createState() => _CartScreenState(); } class _CartScreenState extends State<CartScreen> { bool _isCODSelected = false; double totalAmount = 0.0; double subTotalAmount = 0.0; double taxAmount = 0.0; int totalItems = 0; double taxPercentage = 0; late HubManager? hubManager; // String? transactionID; late String paymentMethod; List<CouponCode> couponCodes = []; bool isPromoCodeAvailableForUse = false; @override void initState() { super.initState(); //_getAllPromoCodes(); _getHubManager(); //totalAmount = Helper().getTotal(widget.order.items); totalItems = widget.order.items.length; // paymentMethod = "Cash"; _configureTaxAndTotal(widget.order.items); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( elevation: 0, shadowColor: WHITE_COLOR, automaticallyImplyLeading: false, backgroundColor: WHITE_COLOR, title: const CustomAppbar( title: "Cart", hideSidemenu: true, ), ), body: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: paddingXY(x: 16, y: 16), child: Text( widget.order.customer.name, style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, color: MAIN_COLOR, fontWeight: FontWeight.bold), )), Padding( padding: paddingXY(x: 16, y: 16), child: Text( "Items", style: getTextStyle( fontWeight: FontWeight.bold, fontSize: MEDIUM_PLUS_FONT_SIZE, color: BLACK_COLOR), ), ), productList(widget.order.items), // selectedCustomerSection, // searchBarSection, // productCategoryList() hightSpacer15, Padding( padding: paddingXY(x: 16, y: 16), child: Text( 'Payment Methods', style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, color: BLACK_COLOR, fontWeight: FontWeight.bold), )), Padding( padding: paddingXY(x: 16), child: Row( children: [ getPaymentOption( PAYMENT_CARD_ICON, CARD_PAYMENT_TXT, !_isCODSelected), widthSpacer(15), getPaymentOption( PAYMENT_CASH_ICON, CASH_PAYMENT_TXT, _isCODSelected), ], ), ), hightSpacer20, Padding( padding: paddingXY(x: 16, y: 0), child: _promoCodeSection()), hightSpacer15, Padding( padding: paddingXY(x: 16, y: 0), child: _subtotalSection('Subtotal', '$appCurrency ${subTotalAmount.toStringAsFixed(2)}')), hightSpacer10, Padding( padding: paddingXY(x: 16, y: 0), child: _subtotalSection('Discount', '$appCurrency 0.00', isDiscount: true)), hightSpacer10, ], )), bottomNavigationBar: bottomBarWidget(), )); } Widget bottomBarWidget() => Container( margin: const EdgeInsets.all(15), height: 100, child: Row(children: [ GestureDetector( onTap: (() { _parkOrder(); }), child: Container( height: 70, width: 80, alignment: Alignment.center, padding: const EdgeInsets.all(4), decoration: const BoxDecoration( color: LIGHT_BLACK_COLOR, borderRadius: BorderRadius.all(Radius.circular(7))), child: Text( 'Park Order', style: getTextStyle( color: WHITE_COLOR, fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.w500), textAlign: TextAlign.center, ), )), Expanded( child: GestureDetector( onTap: () => createSale(!_isCODSelected ? "Card" : "Cash"), child: Container( height: 70, margin: const EdgeInsets.only(left: 10), padding: const EdgeInsets.only(left: 15, right: 15), decoration: const BoxDecoration( color: MAIN_COLOR, borderRadius: BorderRadius.all(Radius.circular(7))), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( widget.order.items.length > 1 ? "${widget.order.items.length} Items" : "${widget.order.items.length} Item", style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE, color: WHITE_COLOR, fontWeight: FontWeight.normal), ), Text( "$appCurrency ${totalAmount.toStringAsFixed(2)}", style: getTextStyle( fontSize: LARGE_FONT_SIZE, fontWeight: FontWeight.w600, color: WHITE_COLOR)), ], ), Text("Checkout", style: getTextStyle( fontSize: LARGE_FONT_SIZE, fontWeight: FontWeight.w400, color: WHITE_COLOR)), ], )))) ]), ); _parkOrder() async { await DbParkedOrder().saveOrder(widget.order); // ignore: use_build_context_synchronously await showGeneralDialog( context: context, transitionBuilder: (context, animation, secondaryAnimation, child) { return FadeTransition( opacity: animation, child: ScaleTransition( scale: animation, child: child, ), ); }, pageBuilder: ((context, animation, secondaryAnimation) { return Dialog( shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8))), child: SizedBox( height: 350, child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Align( alignment: Alignment.topRight, child: IconButton( onPressed: (() { Navigator.pop(context); }), icon: SvgPicture.asset( CROSS_ICON, color: BLACK_COLOR, height: 20, width: 20, ))), hightSpacer10, Text( "Order Parked", style: getTextStyle( fontWeight: FontWeight.w600, fontSize: LARGE_FONT_SIZE, color: BLACK_COLOR), ), hightSpacer30, LongButton( isAmountAndItemsVisible: false, buttonTitle: 'Create A New Order', onTap: () { Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => const ProductListHome()), (route) => route.isFirst); }), LongButton( isAmountAndItemsVisible: false, buttonTitle: ' Home Page', onTap: () { Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => const ProductListHome()), (route) => route.isFirst); }), LongButton( isAmountAndItemsVisible: false, buttonTitle: 'View Parked Orders', onTap: () { Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => const OrderListScreen()), (route) => route.isFirst); }), hightSpacer20 ], ), )); })); } getPaymentOption(String icon, String title, bool selected) { return SizedBox( child: InkWell( onTap: () { setState(() { if (!selected) { _isCODSelected = !_isCODSelected; } }); }, child: Container( height: 120, width: 100, decoration: BoxDecoration( color: selected ? OFF_WHITE_COLOR : WHITE_COLOR, border: Border.all( color: selected ? MAIN_COLOR : DARK_GREY_COLOR, width: 0.4), borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_10)), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( icon, height: 40, ), hightSpacer20, Text(title, style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE, color: DARK_GREY_COLOR)), ], ), ), ), ); } Widget productList(List<OrderItem> prodList) { return Padding( padding: horizontalSpace(), child: ListView.separated( separatorBuilder: (context, index) { return const Divider(); }, shrinkWrap: true, itemCount: prodList.isEmpty ? 10 : prodList.length, primary: false, itemBuilder: (context, position) { if (prodList.isEmpty) { return const ProductShimmer(); } else { return InkWell( onTap: () { // _openItemDetailDialog(context, prodList[position]); }, child: AddedProductItem( product: prodList[position], onDelete: () { prodList.remove(prodList[position]); //_updateOrderPriceAndSave(); if (prodList.isEmpty) { //DbParkedOrder().deleteOrder(widget.order); Navigator.pop(context, "reload"); } else { _updateOrderPriceAndSave(); } }, onItemAdd: () { setState(() { if (prodList[position].orderedQuantity < prodList[position].stock) { prodList[position].orderedQuantity = prodList[position].orderedQuantity + 1; _updateOrderPriceAndSave(); } }); }, onItemRemove: () { setState(() { if (prodList[position].orderedQuantity > 0) { prodList[position].orderedQuantity = prodList[position].orderedQuantity - 1; if (prodList[position].orderedQuantity == 0) { widget.order.items.remove(prodList[position]); if (prodList.isEmpty) { //DbParkedOrder().deleteOrder(widget.order); Navigator.pop(context, "reload"); } else { _updateOrderPriceAndSave(); } } else { _updateOrderPriceAndSave(); } } }); }, ), ); // return ListTile(title: Text(prodList[position].name)); } }), ); } Widget _promoCodeSection() { return Container( // height: 60, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), width: double.infinity, decoration: BoxDecoration( color: MAIN_COLOR.withOpacity(0.1), border: Border.all(width: 1, color: MAIN_COLOR.withOpacity(0.5)), borderRadius: BorderRadius.circular(12)), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "Promo Code", style: getTextStyle( fontWeight: FontWeight.w500, color: MAIN_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE), ), Column( children: [ Text( "", style: getTextStyle( fontWeight: FontWeight.w600, color: MAIN_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE), ), const SizedBox(height: 2), Row( children: List.generate( 15, (index) => Container( width: 2, height: 1, margin: const EdgeInsets.symmetric(horizontal: 1), color: MAIN_COLOR, )), ) ], ), ], ), ); } Widget _subtotalSection(title, amount, {bool isDiscount = false}) => Padding( padding: const EdgeInsets.only(top: 6, left: 8, right: 8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( title, style: getTextStyle( fontWeight: FontWeight.w500, color: isDiscount ? GREEN_COLOR : BLACK_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE), ), Text( amount, style: getTextStyle( fontWeight: FontWeight.w600, color: isDiscount ? GREEN_COLOR : BLACK_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE), ), ], ), ); createSale(String paymentMethod) async { paymentMethod = paymentMethod; if (paymentMethod == "Card") { return Helper.showPopup(context, "Comming Soon"); } else { DateTime currentDateTime = DateTime.now(); String date = DateFormat('EEEE d, LLLL y').format(currentDateTime).toString(); log('Date : $date'); String time = DateFormat().add_jm().format(currentDateTime).toString(); log('Time : $time'); String orderId = await Helper.getOrderId(); log('Order No : $orderId'); SaleOrder saleOrder = SaleOrder( id: orderId, orderAmount: totalAmount, date: date, time: time, customer: widget.order.customer, manager: hubManager!, items: widget.order.items, transactionId: '', paymentMethod: paymentMethod, paymentStatus: "Paid", transactionSynced: false, parkOrderId: "${widget.order.transactionDateTime.millisecondsSinceEpoch}", tracsactionDateTime: currentDateTime); if (!mounted) return; Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => SaleSuccessScreen(placedOrder: saleOrder))); } } // double _getItemTotal(items) { // double total = 0; // for (OrderItem item in items) { // total = total + (item.orderedPrice * item.orderedQuantity); // } // return total; // } //TODO:: Siddhant - Need to correct the tax calculation logic here. _configureTaxAndTotal(List<OrderItem> items) { totalAmount = 0.0; subTotalAmount = 0.0; taxAmount = 0.0; totalItems = 0; taxPercentage = 0; for (OrderItem item in items) { //taxPercentage = taxPercentage + (item.tax * item.orderedQuantity); log('Tax Percentage after adding ${item.name} :: $taxPercentage'); subTotalAmount = subTotalAmount + (item.orderedPrice * item.orderedQuantity); log('SubTotal after adding ${item.name} :: $subTotalAmount'); if (item.attributes.isNotEmpty) { for (var attribute in item.attributes) { //taxPercentage = taxPercentage + attribute.tax; //log('Tax Percentage after adding ${attribute.name} :: $taxPercentage'); if (attribute.options.isNotEmpty) { for (var option in attribute.options) { if (option.selected) { //taxPercentage = taxPercentage + option.tax; subTotalAmount = subTotalAmount + (option.price * item.orderedQuantity); log('SubTotal after adding ${attribute.name} :: $subTotalAmount'); } } } } } } //taxAmount = (subTotalAmount / 100) * taxPercentage; totalAmount = subTotalAmount + taxAmount; widget.order.orderAmount = totalAmount; log('Subtotal :: $subTotalAmount'); log('Tax percentage :: $taxAmount'); log('Tax Amount :: $taxAmount'); log('Total :: $totalAmount'); setState(() {}); //return taxPercentage; } void _getHubManager() async { hubManager = await DbHubManager().getManager(); } void _updateOrderPriceAndSave() { double orderAmount = 0; for (OrderItem item in widget.order.items) { orderAmount += item.orderedPrice * item.orderedQuantity; } widget.order.orderAmount = orderAmount; _configureTaxAndTotal(widget.order.items); //widget.order.save(); //DbParkedOrder().saveOrder(widget.order); } void _getAllPromoCodes() async { CommanResponse commanResponse = await PromoCodeservice().getPromoCodes(); if (commanResponse.apiStatus == ApiStatus.NO_INTERNET) { isPromoCodeAvailableForUse = false; } else if (commanResponse.apiStatus == ApiStatus.REQUEST_SUCCESS) { PromoCodesResponse promoCodesResponse = commanResponse.message; couponCodes = promoCodesResponse.message!.couponCode!; } else { isPromoCodeAvailableForUse = false; } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order_new
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order_new/ui/new_create_order.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../database/db_utils/db_categories.dart'; import '../../../../../database/db_utils/db_hub_manager.dart'; import '../../../../../database/db_utils/db_parked_order.dart'; import '../../../../../database/models/category.dart'; import '../../../../../database/models/customer.dart'; import '../../../../../database/models/hub_manager.dart'; import '../../../../../database/models/order_item.dart'; import '../../../../../database/models/park_order.dart'; import '../../../../../database/models/product.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../widgets/custom_appbar.dart'; import '../../../../../widgets/item_options.dart'; import '../../../../../widgets/product_shimmer_widget.dart'; import '../../../../../widgets/search_widget.dart'; import '../../select_customer/ui/new_select_customer.dart'; import 'cart_screen.dart'; import 'widget/category_item.dart'; // ignore: must_be_immutable class NewCreateOrder extends StatefulWidget { ParkOrder? order; NewCreateOrder({Key? key, this.order}) : super(key: key); @override State<NewCreateOrder> createState() => _NewCreateOrderState(); } class _NewCreateOrderState extends State<NewCreateOrder> { late TextEditingController searchProductCtrl; Customer? _selectedCust; List<Category> categories = []; List<Product> products = []; ParkOrder? parkOrder; // List<Product> cartProducts = []; @override void initState() { super.initState(); searchProductCtrl = TextEditingController(); if (widget.order != null) { _selectedCust = widget.order!.customer; parkOrder = widget.order!; _calculateOrderAmount(); getProducts(); } if (_selectedCust == null) { Future.delayed(Duration.zero, () => goToSelectCustomer()); } } @override void dispose() { searchProductCtrl.dispose(); super.dispose(); } Widget get selectedCustomerSection => _selectedCust != null ? Padding( padding: paddingXY(x: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( _selectedCust!.name, style: getTextStyle( fontSize: LARGE_FONT_SIZE, color: MAIN_COLOR, fontWeight: FontWeight.w500), ), InkWell( onTap: () { goToSelectCustomer(); }, child: Padding( padding: miniPaddingAll(), child: SvgPicture.asset( CROSS_ICON, color: MAIN_COLOR, width: 20,height:20 , ), ), ) ], ), ) : Container(); Widget get searchBarSection => Padding( padding: mediumPaddingAll(), child: SearchWidget( searchHint: SEARCH_PRODUCT_HINT_TXT, searchTextController: searchProductCtrl, onTextChanged: (text) { // log('Changed text :: $text'); // if (text.isNotEmpty) { // filterCustomerData(text); // } else { // getCustomersFromDB(); // } }, onSubmit: (text) { // if (text.isNotEmpty) { // filterCustomerData(text); // } else { // getCustomersFromDB(); // } }, ) ); @override Widget build(BuildContext context) { return Scaffold( // endDrawer: MainDrawer( // menuItem: Helper.getMenuItemList(context), // ), body: SafeArea( child: Stack( children: [ SingleChildScrollView( child: Column( children: [ const CustomAppbar( title: "", ), selectedCustomerSection, searchBarSection, productCategoryList() ], )), parkOrder == null ? Container() : Align( alignment: Alignment.bottomCenter, child: Container( margin: morePaddingAll(), decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: MAIN_COLOR, ), child: ListTile( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => CartScreen(order: parkOrder!))); }, title: Text( "${parkOrder!.items.length} Item", style: getTextStyle( fontSize: SMALL_FONT_SIZE, color: WHITE_COLOR, fontWeight: FontWeight.normal), ), subtitle: Text("$appCurrency ${_getItemTotal()}", style: getTextStyle( fontSize: LARGE_FONT_SIZE, fontWeight: FontWeight.w600, color: WHITE_COLOR)), trailing: Text("View Cart", style: getTextStyle( fontSize: LARGE_FONT_SIZE, fontWeight: FontWeight.w400, color: WHITE_COLOR)), ), ), ), ], ), ), ); } Future<void> getProducts() async { //Fetching data from DbProduct database // products = await DbProduct().getProducts(); // categories = Category.getCategories(products); categories = await DbCategory().getCategories(); setState(() {}); } Widget productCategoryList() { return ListView.separated( separatorBuilder: (context, index) { return const Divider( thickness: 1, ); }, shrinkWrap: true, itemCount: categories.isEmpty ? 10 : categories.length, primary: false, itemBuilder: (context, position) { if (categories.isEmpty) { return const ProductShimmer(); } else { return Column( children: [ // category tile for product InkWell( onTap: () { setState(() { categories[position].isExpanded = !categories[position].isExpanded; }); }, child: Padding( padding: mediumPaddingAll(), child: Row( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( categories[position].name, style: categories[position].isExpanded ? getTextStyle( fontSize: LARGE_FONT_SIZE, color: DARK_GREY_COLOR, fontWeight: FontWeight.w500) : getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500, ), ), categories[position].isExpanded ? Container() : Padding( padding: verticalSpace(x: 5), child: Text( "${categories[position].items.length} items", style: getTextStyle( color: MAIN_COLOR, fontWeight: FontWeight.normal, fontSize: SMALL_PLUS_FONT_SIZE), ), ), ], ), const Spacer(), SvgPicture.asset( categories[position].isExpanded ? CATEGORY_OPENED_ICON : CATEGORY_CLOSED_ICON, height: 10, ) ], ), ), ), // Expanded panel for a category categories[position].isExpanded ? productList(categories[position].items) : Container() ], ); } }); } Widget productList(List<Product> prodList) { return ListView.builder( shrinkWrap: true, itemCount: prodList.isEmpty ? 10 : prodList.length, primary: false, itemBuilder: (context, position) { if (prodList.isEmpty) { return const ProductShimmer(); } else { return InkWell( onTap: () { var item = OrderItem.fromJson(prodList[position].toJson()); _openItemDetailDialog(context, item); }, child: CategoryItem( product: prodList[position], ), ); } }); } void goToSelectCustomer() async { var data = await Navigator.push(context, MaterialPageRoute(builder: (context) => const NewSelectCustomer())); if (data != null) { getProducts(); setState(() { _selectedCust = data; }); } else { if (!mounted) return; Navigator.pop(context); } } _openItemDetailDialog(BuildContext context, OrderItem product) async { product.orderedPrice = product.price; if (product.orderedQuantity == 0) { product.orderedQuantity = 1; } var res = await showDialog( context: context, builder: (context) { return ItemOptions(orderItem: product); }); if (res == true) { if (parkOrder == null) { HubManager manager = await DbHubManager().getManager() as HubManager; parkOrder = ParkOrder( id: _selectedCust!.id, date: Helper.getCurrentDate(), time: Helper.getCurrentTime(), customer: _selectedCust!, items: [], orderAmount: 0, manager: manager, transactionDateTime: DateTime.now()); } setState(() { if (product.orderedQuantity > 0 && !parkOrder!.items.contains(product)) { OrderItem newItem = product; parkOrder!.items.add(newItem); _calculateOrderAmount(); } else if (product.orderedQuantity == 0) { parkOrder!.items.remove(product); _calculateOrderAmount(); } }); DbParkedOrder().saveOrder(parkOrder!); } return res; } double _getItemTotal() { double total = 0; for (OrderItem item in parkOrder!.items) { total = total + (item.orderedPrice * item.orderedQuantity); } return total; } void _calculateOrderAmount() { double amount = 0; for (var item in parkOrder!.items) { amount += item.orderedPrice * item.orderedQuantity; } parkOrder!.orderAmount = amount; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order_new/ui
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order_new/ui/widget/category_item.dart
import 'dart:developer'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../database/models/product.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/card_border_shape.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; // ignore: must_be_immutable class CategoryItem extends StatefulWidget { Product? product; CategoryItem({Key? key, this.product}) : super(key: key); @override State<CategoryItem> createState() => _CategoryItemState(); } class _CategoryItemState extends State<CategoryItem> { bool isUserOnline = true; @override void initState() { _checkUserAvailability(); super.initState(); } _checkUserAvailability() async { isUserOnline = await Helper.isNetworkAvailable(); setState(() {}); } @override Widget build(BuildContext context) { return Card( shape: cardBorderShape(), margin: mediumPaddingAll(), child: Container( padding: horizontalSpace(), child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( flex: 2, child: Container( decoration: BoxDecoration( // border: Border.all( // color: GREY_COLOR, // ), borderRadius: BorderRadius.circular(20)), padding: verticalSpace(), child: _getOrderedProductImage()), ), widthSpacer(10), Expanded( flex: 4, child: Container( height: 85, padding: verticalSpace(x: 5), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( widget.product!.name, style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.normal), ), Text( '$ITEM_CODE_TXT - ${widget.product!.id}', style: getTextStyle( fontWeight: FontWeight.normal, color: DARK_GREY_COLOR), ), const Spacer(), Text( '$appCurrency ${widget.product!.price}', style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, color: MAIN_COLOR, fontWeight: FontWeight.w500), ), ], ), ), ) ]), )); } _getOrderedProductImage() { if (isUserOnline && widget.product!.productImageUrl!.isNotEmpty) { log('Image Url : ${widget.product!.productImageUrl!}'); return ClipRRect( borderRadius: BorderRadius.circular(8), // Image border child: SizedBox( // Image radius height: 80, child: Image(image: NetworkImage(widget.product!.productImageUrl!)), )); } else { log('Local image'); return widget.product!.productImage.isEmpty ? SvgPicture.asset( PRODUCT_IMAGE_, height: 30, width: 30, fit: BoxFit.contain, ) : ClipRRect( borderRadius: BorderRadius.circular(8), // Image border child: SizedBox( // Image radius height: 80, child: Image.memory(widget.product!.productImage, fit: BoxFit.cover), ), ); // Image.memory(widget.product!.productImage); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/webview_screens
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/webview_screens/model/topic_response.dart
class TopicResponse { TopicResponse({ required this.message, }); late final Message message; TopicResponse.fromJson(Map<String, dynamic> json) { message = Message.fromJson(json['message']); } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['message'] = message.toJson(); return data; } } class Message { Message({ required this.successKey, required this.message, required this.privacyPolicy, required this.termsAndConditions, }); late final int successKey; late final String message; late final String privacyPolicy; late final String termsAndConditions; Message.fromJson(Map<String, dynamic> json) { successKey = json['success_key']; message = json['message']; privacyPolicy = json['Privacy_Policy']; termsAndConditions = json['Terms_and_Conditions']; } Map<String, dynamic> toJson() { final data = <String, dynamic>{}; data['success_key'] = successKey; data['message'] = message; data['Privacy_Policy'] = privacyPolicy; data['Terms_and_Conditions'] = termsAndConditions; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/webview_screens
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/webview_screens/service/topic_api_service.dart
import '../../../../constants/app_constants.dart'; import '../../../../network/api_constants/api_paths.dart'; import '../../../../network/api_helper/api_status.dart'; import '../../../../network/api_helper/comman_response.dart'; import '../../../../network/service/api_utils.dart'; import '../../../../utils/helper.dart'; import '../enums/topic_types.dart'; import '../model/topic_response.dart'; ///Class to handle the api calls for terms and conditions and privacy policy class TopicDataService { ///Function to get privacy policy or terms & conditions data static Future<CommanResponse> getTopicData( TopicTypes topicTypes, String instanceUrl) async { //api url String apiUrl = "$instanceUrl$TOPICS_PATH"; //Check for internet connectivity bool isInternetAvailable = await Helper.isNetworkAvailable(); if (isInternetAvailable) { //Call to api var response = await APIUtils.getRequestWithCompleteUrl(apiUrl); //Parsing the api JSON response TopicResponse topicResponse = TopicResponse.fromJson(response); //Checking if message is success, or not empty from api if (topicResponse.message.successKey == 1 || topicResponse.message.message == 'success') { //If requested type is privacy policy if (topicTypes == TopicTypes.PRIVACY_POLICY) { //Returning the CommanResponse as true with privacy policy data return CommanResponse( status: true, message: topicResponse.message.privacyPolicy, apiStatus: ApiStatus.REQUEST_SUCCESS); } //If requested type is terms and conditions else { //Returning the CommanResponse as true with terms & conditions data return CommanResponse( status: true, message: topicResponse.message.termsAndConditions, apiStatus: ApiStatus.REQUEST_SUCCESS); } } else { //Returning the CommanResponse as false, if no data found. return CommanResponse( status: true, message: NO_DATA_FOUND, apiStatus: ApiStatus.REQUEST_FAILURE); } } else { //Returning CommanResponse as false with message that no internet return CommanResponse( status: false, message: NO_INTERNET, apiStatus: ApiStatus.NO_INTERNET); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/webview_screens
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/webview_screens/enums/topic_types.dart
// ignore_for_file: constant_identifier_names enum TopicTypes { PRIVACY_POLICY, TERMS_AND_CONDITIONS, }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/webview_screens
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/webview_screens/ui/webview_screen.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:nb_posx/widgets/custom_appbar.dart'; import 'package:webview_flutter/webview_flutter.dart'; import '../../../../constants/app_constants.dart'; import '../../../../network/api_helper/api_status.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../enums/topic_types.dart'; import '../service/topic_api_service.dart'; class WebViewScreen extends StatefulWidget { final TopicTypes topicTypes; final String apiUrl; const WebViewScreen( {Key? key, required this.topicTypes, required this.apiUrl}) : super(key: key); @override State<WebViewScreen> createState() => _WebViewScreenState(); } class _WebViewScreenState extends State<WebViewScreen> { String parsedHtml = ''; String apiResponse = ''; WebViewController? _webViewController; String title = ""; @override void initState() { super.initState(); if (widget.topicTypes == TopicTypes.PRIVACY_POLICY) { title = "Privacy Policy"; } else { title = "Terms & Conditions"; } getTopicData(); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Column( children: [ CustomAppbar(title: title, hideSidemenu: true), Expanded( child: SizedBox( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, child: WebView( javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (webController) { _webViewController = webController; }, ))) ], )), ); } //Function to get the data from api for privacy policy and T&C void getTopicData() async { //Call to api service as the topic type var response = await TopicDataService.getTopicData(widget.topicTypes, widget.apiUrl); //Execute when internet is not available if (response.apiStatus == ApiStatus.NO_INTERNET) { //Show the message that internet is not available final snackBar = SnackBar( content: Text( NO_INTERNET, style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE, fontWeight: FontWeight.normal), )); if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar(snackBar); //Now pop out the screen, as internet is not available Navigator.pop(context); } //If internet is available then load the html data from api in webview else { apiResponse = response.message; _loadHtml(); } } ///Function to load the html data into webview void _loadHtml() async { //Converting the html data from api into Uri and then to string var data = Uri.dataFromString(apiResponse, mimeType: 'text/html', encoding: Encoding.getByName('utf-8')) .toString(); //Loading the html string into webview _webViewController!.loadUrl(data); setState(() {}); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view/transaction_detail_screen.dart
import 'package:flutter/material.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/custom_appbar.dart'; import '../../../../widgets/customer_tile.dart'; import '../model/transaction.dart'; import 'widgets/header_data.dart'; import 'widgets/transaction_detail_item.dart'; class TransactionDetailScreen extends StatefulWidget { final Transaction order; const TransactionDetailScreen({Key? key, required this.order}) : super(key: key); @override State<TransactionDetailScreen> createState() => _TransactionDetailScreenState(); } class _TransactionDetailScreenState extends State<TransactionDetailScreen> { @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ const CustomAppbar( title: SALES_DETAILS_TXT, hideSidemenu: true, ), hightSpacer30, Padding( padding: horizontalSpace(x: 13), child: Row( children: [ TransactionHeaderData( heading: SALES_ID, headingColor: DARK_GREY_COLOR, content: widget.order.id, ), widthSpacer(50), TransactionHeaderData( heading: SALE_AMOUNT_TXT, content: '$appCurrency ${widget.order.orderAmount.toStringAsFixed(2)}', headingColor: DARK_GREY_COLOR, contentColor: MAIN_COLOR, // crossAlign: CrossAxisAlignment.center, ), ], )), hightSpacer20, Padding( padding: horizontalSpace(x: 13), child: TransactionHeaderData( heading: DATE_TIME, headingColor: DARK_GREY_COLOR, content: '${widget.order.date} ${widget.order.time}', )), Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ hightSpacer20, Padding( padding: horizontalSpace(x: 13), child: Text( CUSTOMER_INFO, style: getTextStyle( fontWeight: FontWeight.w500, fontSize: MEDIUM_MINUS_FONT_SIZE, color: DARK_GREY_COLOR), )), hightSpacer5, CustomerTile( isCheckBoxEnabled: false, isDeleteButtonEnabled: false, isSubtitle: false, customer: widget.order.customer, isHighlighted: true, ) ], ), hightSpacer20, Padding( padding: horizontalSpace(x: 13), child: Text( ITEMS_SUMMARY, style: getTextStyle( fontWeight: FontWeight.w500, fontSize: MEDIUM_MINUS_FONT_SIZE, color: DARK_GREY_COLOR), )), hightSpacer10, ListView.builder( shrinkWrap: true, physics: const ClampingScrollPhysics(), itemCount: widget.order.items.length, itemBuilder: (context, position) { return TransactionDetailItem( product: widget.order.items[position], ); }) ], )), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view/transaction_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:http/http.dart' as http; import '../bloc/transaction_bloc.dart'; import 'transaction_list_screen.dart'; class TransactionScreen extends StatelessWidget { const TransactionScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocProvider( create: (_) => TransactionBloc(httpClient: http.Client())..add(TransactionFetched()), child: const TransactionListScreen(), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view/transaction_list_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:nb_posx/configs/theme_config.dart'; import 'package:nb_posx/core/mobile/parked_orders/ui/orderlist_screen.dart'; import 'package:nb_posx/utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../constants/app_constants.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../widgets/custom_appbar.dart'; import '../../../../widgets/search_widget.dart'; import '../bloc/transaction_bloc.dart'; import 'widgets/bottomloader.dart'; import 'widgets/transaction_item.dart'; class TransactionListScreen extends StatefulWidget { const TransactionListScreen({Key? key}) : super(key: key); @override State<TransactionListScreen> createState() => _TransactionListScreenState(); } class _TransactionListScreenState extends State<TransactionListScreen> { final _scrollController = ScrollController(); late TextEditingController _searchTransactionCtrl; @override void initState() { super.initState(); _searchTransactionCtrl = TextEditingController(); _scrollController.addListener(_onScroll); } @override void dispose() { _searchTransactionCtrl.dispose(); _scrollController ..removeListener(_onScroll) ..dispose(); super.dispose(); } void _onScroll() { if (_isBottom) { if (_searchTransactionCtrl.text.isEmpty) { context.read<TransactionBloc>().add(TransactionFetched()); } else { context .read<TransactionBloc>() .add(TransactionSearched(_searchTransactionCtrl.text, false)); } } } bool get _isBottom { if (!_scrollController.hasClients) return false; final maxScroll = _scrollController.position.maxScrollExtent; final currentScroll = _scrollController.offset; return currentScroll <= (maxScroll * 0.8); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Column( mainAxisSize: MainAxisSize.min, children: [ const CustomAppbar(title: SALES_HISTORY_TXT, hideSidemenu: true), hightSpacer10, Padding( padding: horizontalSpace(), child: SearchWidget( searchHint: SEARCH_HINT_TXT, searchTextController: _searchTransactionCtrl, keyboardType: TextInputType.phone, inputFormatters: [ FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(12) ], onTextChanged: (text) { if (text.isEmpty) { context.read<TransactionBloc>().state.orders.clear(); context.read<TransactionBloc>().add(TransactionFetched()); } else { context .read<TransactionBloc>() .add(TransactionSearched(text, true)); } }, onSubmit: (text) { if (text.isEmpty) { context.read<TransactionBloc>().state.orders.clear(); context.read<TransactionBloc>().add(TransactionFetched()); } else { context .read<TransactionBloc>() .add(TransactionSearched(text, true)); } }, )), hightSpacer10, BlocBuilder<TransactionBloc, TransactionState>( builder: (context, state) { switch (state.status) { case TransactionStatus.failure: return const Center( child: Text("Failed to fetch transactions"), ); case TransactionStatus.success: if (state.orders.isEmpty) { return const Center( child: Text("No orders"), ); } return Expanded( child: ListView.builder( itemCount: state.hasReachedMax ? state.orders.length : state.orders.length + 1, controller: _scrollController, itemBuilder: (BuildContext context, int index) { return index >= state.orders.length ? const Visibility( visible: false, child: BottomLoader()) : TransactionItem(order: state.orders[index]); }), ); default: return const Center( child: CircularProgressIndicator(), ); } }), ], ), extendBodyBehindAppBar: true, bottomNavigationBar: Container( height: 60, margin: const EdgeInsets.only(left: 15, right: 15, bottom: 30), decoration: const BoxDecoration( color: MAIN_COLOR, borderRadius: BorderRadius.all(Radius.circular(10))), child: TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const OrderListScreen())); }, child: Text( 'Parked Orders', style: getTextStyle( fontWeight: FontWeight.bold, fontSize: MEDIUM_PLUS_FONT_SIZE, color: WHITE_COLOR), )), ), )); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view/widgets/transaction_details_popup.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/route_manager.dart'; import 'package:nb_posx/database/models/attribute.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../model/transaction.dart'; class TransactionDetailsPopup extends StatelessWidget { final Transaction order; const TransactionDetailsPopup({Key? key, required this.order}) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( width: Get.width / 2.2, child: Column( children: [ Align( alignment: Alignment.topRight, child: InkWell( onTap: () { Get.back(); }, child: Padding( padding: const EdgeInsets.only(right: 15), child: SvgPicture.asset( CROSS_ICON, color: BLACK_COLOR, width: 20, height: 20, ), ), ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( order.customer.name, style: getTextStyle( fontSize: LARGE_FONT_SIZE, fontWeight: FontWeight.w600), ), Text( 'Order ID: ${order.id}', style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ), ], ), hightSpacer10, Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( order.customer.phone.isEmpty ? "9090909090" : order.customer.phone, style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ), Text( //'27th Jul 2021, 11:00AM ', '${order.date} ${order.time}', style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ) ], ), hightSpacer30, Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "${order.items.length} Items", style: getTextStyle( color: MAIN_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w600), ), Text( '$appCurrency ${order.orderAmount}', style: getTextStyle( color: MAIN_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w600), ) ], ), const Divider( color: GREY_COLOR, thickness: 1, ), _getOrderDetails(), hightSpacer20, _promoCodeSection(), _subtotalSection("Subtotal", "$appCurrency 0.00"), _subtotalSection("Discount", "- $appCurrency 0.00", isDiscount: true), // _subtotalSection("Tax (0%)", "$appCurrency 0.00"), _totalSection("Total", "$appCurrency ${order.orderAmount}"), ], ), ), ], ), ); } _getOrderDetails() { final itemCount = order.items.length; return SizedBox( height: itemCount < 10 ? itemCount * 70 : 10 * 50, child: ListView.builder( itemCount: itemCount, //order.items.length, itemBuilder: (context, index) => Padding( padding: paddingXY(x: 0), child: Row( children: [ ClipRRect( borderRadius: BorderRadius.circular(50), child: Container( width: 50, height: 50, color: MAIN_COLOR, child: Image.network( order.items[index].productImageUrl ?? "assets/images/burgar_img.png", fit: BoxFit.fill, ), ), ), widthSpacer(15), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( order.items[index].name, style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ), const SizedBox( height: 5, ), SizedBox( width: 350, child: Text( "${_getItemVariants(order.items[index].attributes)} x ${order.items[index].orderedQuantity}", style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), textAlign: TextAlign.start, overflow: TextOverflow.ellipsis, maxLines: 5, softWrap: false, ), ), ], ), const Spacer(), Text( "$appCurrency ${order.items[index].price.toStringAsFixed(2)}", style: getTextStyle( color: GREEN_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ), widthSpacer(5), Text( " x${order.items[index].orderedQuantity.round() == 0 ? index + 1 : order.items[index].orderedQuantity.round()}", style: getTextStyle( color: MAIN_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ), ], ), ), ), ); // return ListView.builder( // itemCount: 5, // itemBuilder: (BuildContext context, index) { // return Row( // children: [ // ClipRRect( // child: Container( // width: 50, // height: 50, // color: MAIN_COLOR, // ), // borderRadius: BorderRadius.circular(50), // ), // widthSpacer(15), // Text( // order.items.first.name, // style: getTextStyle( // fontSize: MEDIUM_PLUS_FONT_SIZE, // fontWeight: FontWeight.w500), // ), // const Spacer(), // Text( // "₹ ${order.items.first.price}", // style: getTextStyle( // color: GREEN_COLOR, // fontSize: MEDIUM_PLUS_FONT_SIZE, // fontWeight: FontWeight.w500), // ), // Text( // " x${order.items.first.stock.round()}", // style: getTextStyle( // color: MAIN_COLOR, // fontSize: MEDIUM_PLUS_FONT_SIZE, // fontWeight: FontWeight.w500), // ), // ], // ); // }); } Widget _promoCodeSection() { return Container( // height: 60, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), width: double.infinity, decoration: BoxDecoration( color: MAIN_COLOR.withOpacity(0.1), border: Border.all(width: 1, color: MAIN_COLOR.withOpacity(0.5)), borderRadius: BorderRadius.circular(12)), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "Promo Code", style: getTextStyle( fontWeight: FontWeight.w500, color: MAIN_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE), ), // Column( // children: [ // // Text( // // "Deal 20", // // style: getTextStyle( // // fontWeight: FontWeight.w600, // // color: MAIN_COLOR, // // fontSize: MEDIUM_PLUS_FONT_SIZE), // // ), // const SizedBox(height: 2), // Row( // children: List.generate( // 15, // (index) => Container( // width: 2, // height: 1, // margin: const EdgeInsets.symmetric(horizontal: 1), // color: MAIN_COLOR, // )), // ) // ], // ), ], ), ); } Widget _subtotalSection(title, amount, {bool isDiscount = false}) => Padding( padding: const EdgeInsets.only(top: 6, left: 8, right: 8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( title, style: getTextStyle( fontWeight: FontWeight.w500, color: isDiscount ? GREEN_COLOR : BLACK_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE), ), Text( amount, style: getTextStyle( fontWeight: FontWeight.w600, color: isDiscount ? GREEN_COLOR : BLACK_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE), ), ], ), ); Widget _totalSection(title, amount) => Padding( padding: const EdgeInsets.only(top: 6, left: 8, right: 8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( title, style: getTextStyle( fontWeight: FontWeight.w700, color: BLACK_COLOR, fontSize: LARGE_FONT_SIZE), ), Text( amount, style: getTextStyle( fontWeight: FontWeight.w700, fontSize: LARGE_FONT_SIZE), ), ], ), ); } String _getItemVariants(List<Attribute> itemVariants) { String variants = ''; if (itemVariants.isNotEmpty) { for (var variantData in itemVariants) { for (var selectedOption in variantData.options) { if (!selectedOption.selected) { variants = variants.isEmpty ? '${selectedOption.name} [$appCurrency ${selectedOption.price.toStringAsFixed(2)}]' : "$variants, ${selectedOption.name} [$appCurrency ${selectedOption.price.toStringAsFixed(2)}]"; } } } } return variants; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view/widgets/bottomloader.dart
import 'package:flutter/material.dart'; class BottomLoader extends StatelessWidget { const BottomLoader({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const Center( child: SizedBox( height: 24, width: 24, child: CircularProgressIndicator(strokeWidth: 1.5), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view/widgets/transaction_item.dart
import 'package:flutter/material.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../utils/ui_utils/card_border_shape.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../model/transaction.dart'; import '../transaction_detail_screen.dart'; class TransactionItem extends StatelessWidget { final Transaction order; const TransactionItem({Key? key, required this.order}) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => TransactionDetailScreen( order: order, ))); }, child: Card( shape: cardBorderShape(), margin: const EdgeInsets.fromLTRB(10, 2, 10, 5), child: Container( padding: mediumPaddingAll(), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( order.customer.name, style: getTextStyle(fontSize: MEDIUM_FONT_SIZE), ), hightSpacer4, Text( '$SALES_ID - ${order.id}', style: getTextStyle(fontSize: SMALL_FONT_SIZE), ), hightSpacer4, Text( '${order.date}, ${order.time}', style: getItalicStyle(fontSize: SMALL_FONT_SIZE), ), hightSpacer7, Row( children: [ Text( '$appCurrency ${order.orderAmount.toStringAsFixed(2)}', style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, color: MAIN_COLOR), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view/widgets/transaction_item_landscape.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../model/transaction.dart'; import 'transaction_details_popup.dart'; class TransactionItemLandscape extends StatelessWidget { final Transaction order; const TransactionItemLandscape({Key? key, required this.order}) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: () => _handleOrderDetails(), child: Container( decoration: BoxDecoration( border: Border.all(color: GREY_COLOR, width: 0.4), borderRadius: BorderRadius.circular(8), ), padding: morePaddingAll(), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( flex: 3, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( order.customer.name, style: getTextStyle( fontSize: LARGE_FONT_SIZE, fontWeight: FontWeight.w500), ), hightSpacer10, Text( order.customer.phone.isEmpty ? "9090909090" : order.customer.phone, style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.w500), ), ], ), ), // hightSpacer7, Expanded( flex: 2, child: Text( '$appCurrency ${order.orderAmount}', style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, color: MAIN_COLOR, fontWeight: FontWeight.w500), ), ), Expanded( flex: 4, child: Column( // crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( 'Order ID: ${order.id}', overflow: TextOverflow.clip, style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ), hightSpacer10, Text( textAlign: TextAlign.start, // '27th Jul 2021, 11:00AM ', '${order.date} ${order.time}', overflow: TextOverflow.clip, // textAlign: TextAlign.right, style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE, fontWeight: FontWeight.w500), ), ], ), ), ], ), ), ); } _handleOrderDetails() async { await Get.defaultDialog( // contentPadding: paddingXY(x: 0, y: 0), title: "", titlePadding: paddingXY(x: 0, y: 0), // custom: Container(), content: TransactionDetailsPopup( order: order, ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view/widgets/header_data.dart
import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import 'package:flutter/material.dart'; // ignore: must_be_immutable class TransactionHeaderData extends StatefulWidget { String? heading; String? content; Color? headingColor; Color? contentColor; CrossAxisAlignment crossAlign; TransactionHeaderData( {Key? key, this.heading, this.content, this.crossAlign = CrossAxisAlignment.start, this.headingColor = BLACK_COLOR, this.contentColor = BLACK_COLOR}) : super(key: key); @override State<TransactionHeaderData> createState() => _TransactionHeaderDataState(); } class _TransactionHeaderDataState extends State<TransactionHeaderData> { @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: widget.crossAlign, children: [ Text(widget.heading!, textAlign: TextAlign.end, style: getTextStyle( fontWeight: FontWeight.w500, color: widget.headingColor, fontSize: MEDIUM_MINUS_FONT_SIZE, )), hightSpacer5, Text( widget.content!, style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE, color: widget.contentColor), ) ], ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/view/widgets/transaction_detail_item.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../database/models/attribute.dart'; import '../../../../../database/models/order_item.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/card_border_shape.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class TransactionDetailItem extends StatefulWidget { final OrderItem product; const TransactionDetailItem({Key? key, required this.product}) : super(key: key); @override State<TransactionDetailItem> createState() => _TransactionDetailItemState(); } class _TransactionDetailItemState extends State<TransactionDetailItem> { bool isUserOnline = true; @override void initState() { _checkUserAvailability(); super.initState(); } _checkUserAvailability() async { isUserOnline = await Helper.isNetworkAvailable(); setState(() {}); } @override Widget build(BuildContext context) { return Card( shape: cardBorderShape(), margin: mediumPaddingAll(), elevation: 0, child: Container( padding: horizontalSpace(), child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [ Container( height: 90, width: 90, clipBehavior: Clip.hardEdge, decoration: BoxDecoration( color: MAIN_COLOR.withOpacity(0.1), borderRadius: const BorderRadius.all(Radius.circular(10)), ), child: _getOrderedProductImage()), widthSpacer(15), Expanded( flex: 4, child: Container( height: 85, padding: verticalSpace(x: 5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( widget.product.orderedQuantity > 0 ? '${widget.product.name} (${widget.product.orderedQuantity.round()})' : widget.product.name, style: getTextStyle(fontSize: SMALL_PLUS_FONT_SIZE), overflow: TextOverflow.ellipsis, maxLines: 1, ), Text( _getItemVariants(widget.product.attributes), style: getTextStyle( fontSize: SMALL_FONT_SIZE, fontWeight: FontWeight.normal), overflow: TextOverflow.ellipsis, maxLines: 2, ), Text( '$appCurrency ${widget.product.price.toStringAsFixed(2)}', style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, color: MAIN_COLOR, fontWeight: FontWeight.w600), ), ], ), ), ) ]), )); } String _getItemVariants(List<Attribute> itemVariants) { String variants = ''; if (itemVariants.isNotEmpty) { for (var variantData in itemVariants) { for (var selectedOption in variantData.options) { variants = variants.isEmpty ? '${selectedOption.name} [$appCurrency ${selectedOption.price.toStringAsFixed(2)}]' : "$variants, ${selectedOption.name} [$appCurrency ${selectedOption.price.toStringAsFixed(2)}]"; } } } return variants; } _getOrderedProductImage() { if (isUserOnline && widget.product.productImageUrl != null && widget.product.productImageUrl!.isNotEmpty) { log('Image Url : ${widget.product.productImageUrl!}'); return ClipRRect( borderRadius: BorderRadius.circular(8), // Image border child: SizedBox( // Image radius height: 80, child: Image.network(widget.product.productImageUrl!, fit: BoxFit.cover), ), ); } else { log('Local image'); return widget.product.productImage.isEmpty ? SvgPicture.asset( PRODUCT_IMAGE_, height: 30, width: 30, fit: BoxFit.contain, ) : ClipRRect( borderRadius: BorderRadius.circular(8), // Image border child: SizedBox( // Image radius height: 80, child: Image.memory(widget.product.productImage, fit: BoxFit.cover), ), ); // Image.memory(widget.product.productImage); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/bloc/transaction_event.dart
part of 'transaction_bloc.dart'; abstract class TransactionEvent extends Equatable { @override List<Object> get props => []; } class TransactionFetched extends TransactionEvent {} class TransactionSearched extends TransactionEvent { final String text; final bool isSearchTextChanged; TransactionSearched(this.text, this.isSearchTextChanged); @override List<Object> get props => [text, isSearchTextChanged]; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/bloc/transaction_state.dart
part of 'transaction_bloc.dart'; enum TransactionStatus { initial, success, failure } class TransactionState extends Equatable { final TransactionStatus status; final List<Transaction> orders; final bool hasReachedMax; const TransactionState({ this.status = TransactionStatus.initial, this.orders = const <Transaction>[], this.hasReachedMax = false, }); TransactionState copyWith({ TransactionStatus? status, List<Transaction>? orders, bool? hasReachedMax, }) { return TransactionState( status: status ?? this.status, orders: orders ?? this.orders, hasReachedMax: hasReachedMax ?? this.hasReachedMax, ); } @override String toString() => 'TransactionState(status: $status, orders: $orders, hasReachedMax: $hasReachedMax)'; @override List<Object> get props => [status, orders, hasReachedMax]; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/bloc/transaction_bloc.dart
import 'dart:async'; import 'dart:developer'; import 'dart:typed_data'; import 'package:bloc_concurrency/bloc_concurrency.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:http/http.dart' as http; import 'package:intl/intl.dart'; import 'package:nb_posx/database/db_utils/db_sale_order.dart'; import 'package:nb_posx/database/models/attribute.dart'; import 'package:nb_posx/database/models/sale_order.dart'; import 'package:stream_transform/stream_transform.dart'; import '../../../../constants/app_constants.dart'; import '../../../../database/db_utils/db_constants.dart'; import '../../../../database/db_utils/db_preferences.dart'; import '../../../../database/models/customer.dart'; import '../../../../database/models/option.dart'; import '../../../../database/models/order_item.dart'; import '../../../../network/api_constants/api_paths.dart'; import '../../../../network/service/api_utils.dart'; import '../../../../utils/helper.dart'; import '../../../service/sales_history/model/sale_order_list_response.dart'; import '../model/transaction.dart'; part 'transaction_event.dart'; part 'transaction_state.dart'; const throttleDuration = Duration(milliseconds: 100); const _listSize = 10; EventTransformer<E> throttleDroppable<E>(Duration duration) { return (events, mapper) { return droppable<E>().call(events.throttle(duration), mapper); }; } class TransactionBloc extends Bloc<TransactionEvent, TransactionState> { final http.Client httpClient; TransactionBloc({required this.httpClient}) : super(const TransactionState()) { on<TransactionFetched>(_onPostFetched, transformer: throttleDroppable(throttleDuration)); on<TransactionSearched>((event, emit) async { if (event.text.length > 2) { if (state.hasReachedMax) return; final transactions = await _searchTransactions(event.text, orderSize: event.isSearchTextChanged ? 0 : state.orders.length); if (event.isSearchTextChanged) { return emit(state.copyWith( status: TransactionStatus.success, orders: transactions, hasReachedMax: false)); } else { return emit(transactions.isEmpty ? state.copyWith(hasReachedMax: true) : state.copyWith( status: TransactionStatus.success, orders: List.of(state.orders)..addAll(transactions), hasReachedMax: transactions.length < _listSize, )); } } else if (event.text.isEmpty) { //final transactions = await _fetchTransactions(0); return emit(state.copyWith( status: TransactionStatus.initial, orders: [], hasReachedMax: false, )); } }, transformer: throttleDroppable(throttleDuration)); } FutureOr<void> _onPostFetched( TransactionFetched event, Emitter<TransactionState> emit) async { if (state.hasReachedMax) return; try { if (state.status == TransactionStatus.initial) { final transactions = await _fetchTransactions(); return emit(state.copyWith( status: TransactionStatus.success, orders: transactions, hasReachedMax: false, )); } final transactions = await _fetchTransactions(state.orders.length); emit(transactions.isEmpty ? state.copyWith(hasReachedMax: true) : state.copyWith( status: TransactionStatus.success, orders: List.of(state.orders)..addAll(transactions), hasReachedMax: transactions.length < _listSize, )); } catch (_) { emit(state.copyWith(status: TransactionStatus.failure)); } } Future<List<Transaction>> _fetchTransactions([int orderSize = 0]) async { if (await Helper.isNetworkAvailable()) { int pageNo = 1; if (orderSize > 0) { var ord = orderSize / _listSize; pageNo = (ord.ceilToDouble() + 1).toInt(); } debugPrint("Current Page No: $pageNo"); String hubManagerId = await DBPreferences().getPreference(HubManagerId); //Creating GET api url String apiUrl = SALES_HISTORY; apiUrl += '?hub_manager=$hubManagerId&page_no=$pageNo'; return _processRequest(apiUrl); } else { List<SaleOrder> offlineOrders = await DbSaleOrder().getOfflineOrders(); List<Transaction> offlineTransactions = []; for (var order in offlineOrders) { Transaction transaction = Transaction( id: order.id, date: order.date, time: order.time, customer: order.customer, items: order.items, orderAmount: order.orderAmount, tracsactionDateTime: order.tracsactionDateTime); offlineTransactions.add(transaction); } return offlineTransactions; } //throw Exception("Error fetching transactions"); } Future<List<Transaction>> _processRequest(String apiUrl) async { try { List<Transaction> sales = []; //Call to Sales History api var apiResponse = await APIUtils.getRequestWithHeaders(apiUrl); //Fetching the local orders data if (apiResponse["message"]["message"] != "success") { throw Exception(NO_DATA_FOUND); } //Parsing the JSON Response SalesOrderResponse salesOrderResponse = SalesOrderResponse.fromJson(apiResponse); if (salesOrderResponse.message!.orderList!.isNotEmpty) { //Convert the api response to local model for (var order in salesOrderResponse.message!.orderList!) { if (!sales.any((element) => element.id == order.name)) { List<OrderItem> orderedProducts = []; //Ordered products for (var orderedProduct in order.items!) { List<Attribute> attributes = []; for (var attribute in orderedProduct.subItems!) { Option option = Option( id: attribute.itemCode!, name: attribute.itemName!, price: attribute.amount!, selected: false, tax: attribute.tax!); Attribute orderedAttribute = Attribute( name: attribute.itemName!, type: '', moq: 0, options: [option], ); attributes.add(orderedAttribute); } OrderItem product = OrderItem( id: orderedProduct.itemCode!, name: orderedProduct.itemName!, group: '', description: '', stock: 0, price: orderedProduct.rate!, attributes: attributes, orderedQuantity: orderedProduct.qty!, productImage: Uint8List.fromList([]), productImageUrl: orderedProduct.image, productUpdatedTime: DateTime.now(), tax: 0); orderedProducts.add(product); } String transactionDateTime = "${order.transactionDate} ${order.transactionTime}"; String date = DateFormat('EEEE d, LLLL y') .format(DateTime.parse(transactionDateTime)) .toString(); log('Date :2 $date'); //Need to convert 2:26:17 to 02:26 AM String time = DateFormat() .add_jm() .format(DateTime.parse(transactionDateTime)) .toString(); log('Time : $time'); Transaction sale = Transaction( id: order.name!, customer: Customer( id: order.customer!, name: order.customerName!, phone: order.contactMobile!, email: order.contactEmail!, isSynced: false, modifiedDateTime: DateTime.now()), items: orderedProducts, orderAmount: order.grandTotal!, date: date, time: time, tracsactionDateTime: DateTime.parse( '${order.transactionDate} ${order.transactionTime}'), ); sales.add(sale); } } return sales; } else { return []; } } catch (ex) { debugPrint("Exception occured $ex"); debugPrintStack(); log(ex.toString()); return []; } } Future<List<Transaction>> _searchTransactions(String query, {int orderSize = 0}) async { if (await Helper.isNetworkAvailable()) { int pageNo = 1; if (orderSize > 0) { var ord = orderSize / _listSize; pageNo = (ord.ceilToDouble() + 1).toInt(); } debugPrint("Search Sales Order - Current Page No: $pageNo"); String hubManagerId = await DBPreferences().getPreference(HubManagerId); //Creating GET api url String apiUrl = SALES_HISTORY; apiUrl += '?hub_manager=$hubManagerId&mobile_no=$query&page_no=$pageNo'; return _processRequest(apiUrl); } throw Exception("Error fetching transactions"); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/transaction_history/model/transaction.dart
import 'dart:convert'; import 'package:equatable/equatable.dart'; import '../../../../database/models/customer.dart'; import '../../../../database/models/order_item.dart'; class Transaction extends Equatable { final String id; final String date; final String time; final Customer customer; final List<OrderItem> items; final double orderAmount; final DateTime tracsactionDateTime; const Transaction({ required this.id, required this.date, required this.time, required this.customer, required this.items, required this.orderAmount, required this.tracsactionDateTime, }); Transaction copyWith({ String? id, String? date, String? time, Customer? customer, List<OrderItem>? items, double? orderAmount, DateTime? tracsactionDateTime, }) { return Transaction( id: id ?? this.id, date: date ?? this.date, time: time ?? this.time, customer: customer ?? this.customer, items: items ?? this.items, orderAmount: orderAmount ?? this.orderAmount, tracsactionDateTime: tracsactionDateTime ?? this.tracsactionDateTime, ); } Map<String, dynamic> toMap() { return { 'id': id, 'date': date, 'time': time, 'customer': customer.toMap(), 'items': items.map((x) => x.toMap()).toList(), 'orderAmount': orderAmount, 'tracsactionDateTime': tracsactionDateTime.millisecondsSinceEpoch, }; } factory Transaction.fromMap(Map<String, dynamic> map) { return Transaction( id: map['id'] ?? '', date: map['date'] ?? '', time: map['time'] ?? '', customer: Customer.fromMap(map['customer']), items: List<OrderItem>.from(map['items']?.map((x) => OrderItem.fromMap(x))), orderAmount: map['orderAmount']?.toDouble() ?? 0.0, tracsactionDateTime: DateTime.fromMillisecondsSinceEpoch(map['tracsactionDateTime']), ); } String toJson() => json.encode(toMap()); factory Transaction.fromJson(String source) => Transaction.fromMap(json.decode(source)); @override String toString() { return 'Transaction(id: $id, date: $date, time: $time, customer: $customer, items: $items, orderAmount: $orderAmount, tracsactionDateTime: $tracsactionDateTime)'; } @override List<Object> get props { return [ id, date, time, customer, items, orderAmount, tracsactionDateTime, ]; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sale_success
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sale_success/ui/sale_success_screen.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:lottie/lottie.dart'; import 'package:nb_posx/utils/helper.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../database/db_utils/db_sale_order.dart'; import '../../../../database/models/sale_order.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/long_button_widget.dart'; import '../../../service/create_order/api/create_sales_order.dart'; import '../../create_order_new/ui/new_create_order.dart'; import '../../home/ui/product_list_home.dart'; class SaleSuccessScreen extends StatefulWidget { final SaleOrder placedOrder; const SaleSuccessScreen({Key? key, required this.placedOrder}) : super(key: key); @override State<SaleSuccessScreen> createState() => _SaleSuccessScreenState(); } class _SaleSuccessScreenState extends State<SaleSuccessScreen> { @override void initState() { super.initState(); log("${widget.placedOrder}"); CreateOrderService().createOrder(widget.placedOrder).then((value) { if (value.status!) { // print("create order response::::YYYYY"); SaleOrder order = widget.placedOrder; order.transactionSynced = true; order.id = value.message; //order.save(); DbSaleOrder().createOrder(order).then((value) { debugPrint('order sync and saved to db'); //Helper.showPopup(context, "Order synced and saved locally"); }); } else { DbSaleOrder().createOrder(widget.placedOrder).then((value) { debugPrint('order saved to db'); Helper.showPopup(context, "Order saved locally, and will be synced when you restart the app."); }); } }); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { // Navigate to the HomeScreen when the back button is pressed Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => ProductListHome()), (route) => false, // Remove all other routes from the stack ); return true; // Prevent default back button behavior }, child: Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Center( child: Lottie.asset(SUCCESS_IMAGE, animate: true), ), hightSpacer30, Text( SALES_SUCCESS_TXT, style: getTextStyle( fontSize: LARGE_FONT_SIZE, color: BLACK_COLOR, fontWeight: FontWeight.w600), ), hightSpacer30, //rajni LongButton( isAmountAndItemsVisible: false, buttonTitle: "Print Receipt", onTap: () { _printInvoice(); }, ), // LongButton( // isAmountAndItemsVisible: false, // buttonTitle: RETURN_TO_HOME_TXT, // onTap: () { // Navigator.popUntil(context, (route) => route.isFirst); // }, // ), LongButton( isAmountAndItemsVisible: false, buttonTitle: "New Order", onTap: () { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (context) => NewCreateOrder()), (route) => route.isFirst); }, ), ], ), )); } //TODO:: Need to handle the print receipt here _printInvoice() async { try { bool isPrintSuccessful = await Helper().printInvoice(widget.placedOrder); if (!isPrintSuccessful && mounted) { Helper.showPopup(context, "Print operation cancelled by you."); } } catch (e) { Helper.showPopup(context, SOMETHING_WENT_WRONG); log('Exception ocurred in printing invoice :: $e'); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history/ui/sales_header_data.dart
import 'package:flutter/material.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class SalesHeaderAndData extends StatefulWidget { String? heading; String? content; Color? headingColor; Color? contentColor; CrossAxisAlignment crossAlign; SalesHeaderAndData( {Key? key, this.heading, this.content, this.crossAlign = CrossAxisAlignment.start, this.headingColor = BLACK_COLOR, this.contentColor = BLACK_COLOR}) : super(key: key); @override State<SalesHeaderAndData> createState() => _SalesHeaderAndDataState(); } class _SalesHeaderAndDataState extends State<SalesHeaderAndData> { @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: widget.crossAlign, children: [ Text(widget.heading!, textAlign: TextAlign.end, style: getTextStyle( fontWeight: FontWeight.w500, color: widget.headingColor)), hightSpacer5, Text( widget.content!, style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE, color: widget.contentColor), ) ], ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history/ui/sales_history.dart
import 'dart:developer'; import '../../../../constants/app_constants.dart'; import '../../../../database/db_utils/db_sale_order.dart'; import '../../../../database/models/sale_order.dart'; import '../../../../network/api_helper/api_status.dart'; import '../../../../network/api_helper/comman_response.dart'; import '../../../../utils/helper.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/custom_appbar.dart'; import '../../../../widgets/search_widget.dart'; import 'package:flutter/material.dart'; import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart'; import '../../../service/sales_history/api/get_sales_history.dart'; import 'sales_data_item.dart'; class SalesHistory extends StatefulWidget { static int pageSize = 1; const SalesHistory({Key? key}) : super(key: key); @override State<SalesHistory> createState() => _SalesHistoryState(); } class _SalesHistoryState extends State<SalesHistory> { bool isUserOnline = false; //Offline data list List<SaleOrder> orderFromLocalDB = []; List<SaleOrder> offlineOrders = []; String searchTerm = ""; late TextEditingController searchsalesController; late PagingController<int, SaleOrder> _pagingController; bool isLoading = false; //Online data List List<SaleOrder> salesOrders = []; @override void initState() { //Adding listener for pagination searchsalesController = TextEditingController(); _pagingController = PagingController(firstPageKey: 1); _getOrdersToShow(); super.initState(); } @override void dispose() { _pagingController.dispose(); searchsalesController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( // endDrawer: MainDrawer( // menuItem: Helper.getMenuItemList(context), // ), body: SafeArea( child: SingleChildScrollView( primary: true, child: Column( mainAxisSize: MainAxisSize.min, children: [ const CustomAppbar(title: SALES_HISTORY_TXT), hightSpacer10, Padding( padding: horizontalSpace(), child: SearchWidget( searchHint: SEARCH_HINT_TXT, searchTextController: searchsalesController, onTextChanged: (text) { filterSalesData(text); // else // getSales(); }, onSubmit: (text) { filterSalesData(text); // else // getSales(); }, )), hightSpacer10, Visibility( visible: orderFromLocalDB.isNotEmpty, child: ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), primary: false, itemCount: offlineOrders.length, itemBuilder: (context, position) { return SalesDataItem( saleOrder: offlineOrders[position], ); }), ), !isUserOnline ? Container() : RefreshIndicator( onRefresh: () => Future.sync( () => _pagingController.refresh(), ), child: PagedListView<int, SaleOrder>( primary: false, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), pagingController: _pagingController, builderDelegate: PagedChildBuilderDelegate<SaleOrder>( noItemsFoundIndicatorBuilder: (context) { return Center( child: Text( NO_ORDERS_FOUND_MSG, style: getTextStyle(fontSize: MEDIUM_FONT_SIZE), ), ); }, itemBuilder: (context, item, position) { return SalesDataItem(saleOrder: item); }), ), ), ], //), ), ), ), ); } ///Function to fetch all the orders from db. Future<void> getSales() async { orderFromLocalDB = await DbSaleOrder().getOrders(); offlineOrders = orderFromLocalDB.reversed.toList(); setState(() {}); } ///Function to filter the orders as per the search keyword. void filterSalesData(String searchText) { offlineOrders = orderFromLocalDB .where((element) => element.id.toLowerCase().contains(searchText) || element.customer.name.toLowerCase().contains(searchText) || element.customer.phone.toLowerCase().contains(searchText)) .toList(); offlineOrders = offlineOrders.reversed.toList(); if (searchText.trim().isEmpty) { offlineOrders = orderFromLocalDB.reversed.toList(); _pagingController.refresh(); } if (searchText.trim().length > 2) { SalesHistory.pageSize = 1; salesOrders = []; _pagingController.refresh(); } setState(() {}); } ///Function to fetch the offline orders from db, which is not synced. Future<void> getOfflineOrdersFromDb() async { orderFromLocalDB = await DbSaleOrder().getOfflineOrders(); offlineOrders = orderFromLocalDB.reversed.toList(); setState(() {}); } ///Function to fetch the sales data from server in page form. Future<void> _fetchsalesData(int page) async { try { //Sales Details api call CommanResponse commanResponse = await GetSalesHistory() .getSalesHistory(page, searchsalesController.text.trim()); //If success response from api means internet is also available if (commanResponse.status!) { //Casting the custom response into actual response var salesData = commanResponse.message as List<SaleOrder>; //Adding all the sales data from api into the online sales details list. salesOrders.addAll(salesData); //Check whether the page is last or not bool isLastPage = salesOrders.length >= SalesHistory.pageSize; //If page is not last then increment the key (page value) by 1. if (!isLastPage) { //Incrementing the page by 1. int nextPageKey = page + 1; //Appending the fetched sales data into paging controller along with next page value. _pagingController.appendPage(salesData, nextPageKey); } //If the page is last else { //Appending the last page in paging controller _pagingController.appendLastPage(salesData); } } else if (commanResponse.status! == false && commanResponse.apiStatus == ApiStatus.NO_DATA_AVAILABLE) { List<SaleOrder> salesData = []; // TODO::: handle data in case of search if no matching data found _pagingController.appendLastPage(salesData); } //If internet connection is not available else if (commanResponse.status! == false && commanResponse.apiStatus == ApiStatus.NO_INTERNET) { //Fetch all the orders from db and display it in UI. await getSales(); } } catch (error) { log('Exception caught :: $error'); _pagingController.error = error; } } void _getOrdersToShow() async { isUserOnline = await Helper.isNetworkAvailable(); if (isUserOnline) { //Fetch the offline & not synced orders from db and display it in UI. _pagingController.addPageRequestListener((pageKey) { // print("PAGEKEY: $pageKey"); _fetchsalesData(pageKey); }); await getOfflineOrdersFromDb(); } else { await getSales(); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history/ui/sales_data_item.dart
import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../utils/ui_utils/card_border_shape.dart'; import '../../../../utils/helper.dart'; import '../../../../database/models/sale_order.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import 'package:flutter/material.dart'; import 'sales_details.dart'; // ignore: must_be_immutable class SalesDataItem extends StatelessWidget { SaleOrder? saleOrder; SalesDataItem({Key? key, this.saleOrder}) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => SalesDetailsScreen( saleOrder: saleOrder, ))); }, child: Card( shape: cardBorderShape(), margin: const EdgeInsets.fromLTRB(10, 2, 10, 5), child: Container( padding: mediumPaddingAll(), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '$SALES_ID - ${saleOrder!.id}', style: getTextStyle(fontSize: MEDIUM_FONT_SIZE), ), hightSpacer4, Text( '${saleOrder!.date} ${saleOrder!.time}', style: getItalicStyle(fontSize: SMALL_FONT_SIZE), ), hightSpacer7, Row( children: [ Text( '$appCurrency ${saleOrder!.orderAmount}', style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, color: MAIN_COLOR), ), const Spacer(), Text( saleOrder!.paymentStatus, style: getTextStyle( fontWeight: FontWeight.w500, fontSize: SMALL_PLUS_FONT_SIZE, color: Helper.getPaymentStatusColor( saleOrder!.paymentStatus)), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history/ui/sales_history_sidd.dart
import 'dart:developer'; import '../../../../constants/app_constants.dart'; import '../../../service/sales_history/api/get_sales_history.dart'; import '../../../../database/db_utils/db_sale_order.dart'; import '../../../../database/models/sale_order.dart'; import '../../../../network/api_helper/api_status.dart'; import '../../../../network/api_helper/comman_response.dart'; import '../../../../utils/helper.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/custom_appbar.dart'; import '../../../../widgets/search_widget.dart'; import 'package:flutter/material.dart'; import 'sales_data_item.dart'; class SalesHistory extends StatefulWidget { static int pageSize = 1; const SalesHistory({Key? key}) : super(key: key); @override State<SalesHistory> createState() => _SalesHistoryState(); } class _SalesHistoryState extends State<SalesHistory> { bool isUserOnline = false; late int pageKey; //Offline data list List<SaleOrder> orderFromLocalDB = []; List<SaleOrder> offlineOrders = []; String searchTerm = ""; late TextEditingController _searchsalesController; // late PagingController<int, SaleOrder> _pagingController; late ScrollController _scrollCtrl; bool isLoading = false; //Online data List List<SaleOrder> salesOrders = []; @override void initState() { //Adding listener for pagination _searchsalesController = TextEditingController(); // _pagingController = PagingController(firstPageKey: 1); _scrollCtrl = ScrollController(); pageKey = 1; _getOrdersToShow(); super.initState(); } @override void dispose() { // _pagingController.dispose(); _searchsalesController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { /// ui screen return Scaffold( body: SafeArea( child: Column( mainAxisSize: MainAxisSize.min, children: [ const CustomAppbar(title: SALES_HISTORY_TXT), hightSpacer10, searchBarWidget(), hightSpacer10, isUserOnline ? _showUserOnlineData(context) : _showLocalDBData(context), ], ), ), ); } ///Function to fetch all the orders from db. Future<void> getSales() async { orderFromLocalDB = await DbSaleOrder().getOrders(); offlineOrders = orderFromLocalDB.reversed.toList(); setState(() {}); } ///Function to filter the orders as per the search keyword. void filterSalesData(String searchText) { offlineOrders = orderFromLocalDB .where((element) => element.id.toLowerCase().contains(searchText) || element.customer.name.toLowerCase().contains(searchText) || element.customer.phone.toLowerCase().contains(searchText)) .toList(); offlineOrders = offlineOrders.reversed.toList(); if (searchText.trim().isEmpty) { offlineOrders = orderFromLocalDB.reversed.toList(); // _pagingController.appendPage(salesOrders, 1); pageKey = 1; _fetchsalesData(); } if (searchText.trim().length > 2) { SalesHistory.pageSize = 1; salesOrders.clear(); _fetchsalesData(); } setState(() {}); } ///Function to fetch the offline orders from db, which is not synced. Future<void> getOfflineOrdersFromDb() async { orderFromLocalDB = await DbSaleOrder().getOfflineOrders(); offlineOrders = orderFromLocalDB.reversed.toList(); setState(() {}); } ///Function to fetch the sales data from server in page form. Future<void> _fetchsalesData() async { int page = pageKey; try { //Sales Details api call CommanResponse commanResponse = await GetSalesHistory() .getSalesHistory(page, _searchsalesController.text.trim()); //If success response from api means internet is also available if (commanResponse.status!) { //Casting the custom response into actual response var salesData = commanResponse.message as List<SaleOrder>; //Adding all the sales data from api into the online sales details list. salesOrders.addAll(salesData); //Check whether the page is last or not bool isLastPage = salesOrders.length >= SalesHistory.pageSize; //If page is not last then increment the key (page value) by 1. if (!isLastPage) { //Incrementing the page by 1. pageKey = page + 1; setState(() {}); } } else if (commanResponse.status! == false && commanResponse.apiStatus == ApiStatus.NO_DATA_AVAILABLE) { salesOrders.clear(); setState(() {}); } //If internet connection is not available else if (commanResponse.status! == false && commanResponse.apiStatus == ApiStatus.NO_INTERNET) { //Fetch all the orders from db and display it in UI. await getSales(); } } catch (error) { log('Exception caught :: $error'); setState(() {}); } } void _getOrdersToShow() async { isUserOnline = await Helper.isNetworkAvailable(); if (isUserOnline) { //Fetch the offline & not synced orders from db and display it in UI. // _pagingController.addPageRequestListener((pageKey) { // print("PAGEKEY: $pageKey"); // _fetchsalesData(pageKey); // }); _fetchsalesData(); _scrollCtrl.addListener(() { // print("PAGEKEY: $pageKey"); // print("PIXELS: ${_scrollCtrl.position.pixels}"); // print("EXTENT: ${_scrollCtrl.position.maxScrollExtent}"); if (_scrollCtrl.position.pixels == _scrollCtrl.position.maxScrollExtent) { _fetchsalesData(); } }); await getOfflineOrdersFromDb(); } else { await getSales(); } } Widget _showLocalDBData(BuildContext context) { return offlineOrders.isEmpty ? Center( child: Text( NO_ORDERS_FOUND_MSG, style: getTextStyle(fontSize: MEDIUM_FONT_SIZE), ), ) : ListView.builder( shrinkWrap: true, physics: const AlwaysScrollableScrollPhysics(), primary: true, itemCount: offlineOrders.length, itemBuilder: (context, position) { return SalesDataItem( saleOrder: offlineOrders[position], ); }); } Widget _showUserOnlineData(BuildContext context) { return Expanded( child: Stack( children: [ _buildDataList(), _loader(), ], ), ); // return RefreshIndicator( // onRefresh: () => Future.sync( // () => _pagingController.refresh(), // ), // child: PagedListView<int, SaleOrder>( // primary: false, // shrinkWrap: true, // physics: NeverScrollableScrollPhysics(), // pagingController: _pagingController, // builderDelegate: PagedChildBuilderDelegate<SaleOrder>( // noItemsFoundIndicatorBuilder: (context) { // return Center( // child: Text( // NO_ORDERS_FOUND_MSG, // style: getTextStyle(fontSize: MEDIUM_FONT_SIZE), // ), // ); // }, itemBuilder: (context, item, position) { // return SalesDataItem(saleOrder: item); // }), // ), // ); } /// search bar widget at top Widget searchBarWidget() => Padding( padding: horizontalSpace(), child: SearchWidget( searchHint: SEARCH_HINT_TXT, searchTextController: _searchsalesController, onTextChanged: (text) { filterSalesData(text); }, onSubmit: (text) { filterSalesData(text); }, )); Widget _loader() { return isLoading ? const Align( alignment: FractionalOffset.bottomCenter, child: SizedBox( width: 70.0, height: 70.0, child: Padding( padding: EdgeInsets.all(5.0), child: Center(child: CircularProgressIndicator())), ), ) : const SizedBox( width: 0.0, height: 0.0, ); } Widget _buildDataList() { return ListView.builder( shrinkWrap: true, physics: const AlwaysScrollableScrollPhysics(), // primary: true, // padding: const EdgeInsets.all(16.0), // The itemBuilder callback is called once per suggested word pairing, // and places each suggestion into a ListTile row. // For even rows, the function adds a ListTile row for the word pairing. // For odd rows, the function adds a Divider widget to visually // separate the entries. Note that the divider may be difficult // to see on smaller devices. controller: _scrollCtrl, itemCount: salesOrders.length, itemBuilder: (context, i) { // Add a one-pixel-high divider widget before each row in theListView. return SalesDataItem(saleOrder: salesOrders[i]); }); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history/ui/sales_details.dart
import 'package:flutter/material.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../database/models/sale_order.dart'; import '../../../../utils/helper.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/comman_tile_options.dart'; import '../../../../widgets/custom_appbar.dart'; import 'sales_details_item.dart'; import 'sales_header_data.dart'; // ignore: must_be_immutable class SalesDetailsScreen extends StatefulWidget { SaleOrder? saleOrder; SalesDetailsScreen({Key? key, this.saleOrder}) : super(key: key); @override State<SalesDetailsScreen> createState() => _SalesDetailsScreenState(); } class _SalesDetailsScreenState extends State<SalesDetailsScreen> { @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ const CustomAppbar(title: SALES_DETAILS_TXT), hightSpacer30, Padding( padding: horizontalSpace(x: 13), child: Row( children: [ Expanded( flex: 2, child: SalesHeaderAndData( heading: SALES_ID, content: widget.saleOrder!.id, )), Expanded( flex: 2, child: SalesHeaderAndData( heading: SALE_AMOUNT_TXT, content: '$appCurrency ${widget.saleOrder!.orderAmount}', headingColor: BLACK_COLOR, contentColor: MAIN_COLOR, crossAlign: CrossAxisAlignment.center, )), Expanded( flex: 1, child: SalesHeaderAndData( heading: PAYMENT_STATUS, content: widget.saleOrder!.paymentStatus, crossAlign: CrossAxisAlignment.end, contentColor: Helper.getPaymentStatusColor( widget.saleOrder!.paymentStatus), )), ], )), hightSpacer20, Padding( padding: horizontalSpace(x: 13), child: SalesHeaderAndData( heading: DATE_TIME, content: '${widget.saleOrder!.date} ${widget.saleOrder!.time}', )), Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ hightSpacer20, Padding( padding: horizontalSpace(x: 13), child: Text( CUSTOMER_INFO, style: getTextStyle(fontWeight: FontWeight.w500), )), hightSpacer5, CommanTileOptions( isCheckBoxEnabled: false, isDeleteButtonEnabled: false, isSubtitle: true, customer: widget.saleOrder!.customer, ) ], ), hightSpacer20, Padding( padding: horizontalSpace(x: 13), child: Text( '$ITEMS_SUMMARY (${widget.saleOrder!.items.length} $ITEM_TXT)', style: getTextStyle(fontWeight: FontWeight.w500), )), hightSpacer10, ListView.builder( shrinkWrap: true, physics: const ClampingScrollPhysics(), itemCount: widget.saleOrder!.items.length, itemBuilder: (context, position) { return SalesDetailsItems( product: widget.saleOrder!.items[position], ); }) ], )), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/sales_history/ui/sales_details_item.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../database/models/order_item.dart'; import '../../../../utils/helper.dart'; import '../../../../utils/ui_utils/card_border_shape.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class SalesDetailsItems extends StatefulWidget { OrderItem? product; SalesDetailsItems({Key? key, this.product}) : super(key: key); @override State<SalesDetailsItems> createState() => _SalesDetailsItemsState(); } class _SalesDetailsItemsState extends State<SalesDetailsItems> { bool isUserOnline = true; @override void initState() { _checkUserAvailability(); super.initState(); } _checkUserAvailability() async { isUserOnline = await Helper.isNetworkAvailable(); setState(() {}); } @override Widget build(BuildContext context) { return Card( shape: cardBorderShape(), margin: mediumPaddingAll(), child: Container( padding: horizontalSpace(), child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( flex: 2, child: Container( decoration: BoxDecoration( // border: Border.all( // color: GREY_COLOR, // ), borderRadius: BorderRadius.circular(20)), padding: verticalSpace(), child: _getOrderedProductImage()), ), widthSpacer(10), Expanded( flex: 4, child: Container( height: 85, padding: verticalSpace(x: 5), child: Column( // mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( widget.product!.orderedQuantity > 0 ? '${widget.product!.name} x ${widget.product!.orderedQuantity.round()}' : widget.product!.name, style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.normal), ), Text( '$ITEM_CODE_TXT - ${widget.product!.id}', style: getTextStyle( fontWeight: FontWeight.normal, color: DARK_GREY_COLOR), ), const Spacer(), Text( '$appCurrency ${widget.product!.price}', style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, color: MAIN_COLOR, fontWeight: FontWeight.w500), ), ], ), ), ) ]), )); } _getOrderedProductImage() { if (isUserOnline && widget.product!.productImageUrl!.isNotEmpty) { log('Image Url : ${widget.product!.productImageUrl!}'); return ClipRRect( borderRadius: BorderRadius.circular(8), // Image border child: SizedBox( // Image radius height: 80, child: Image.network(widget.product!.productImageUrl!, fit: BoxFit.cover), ), ); } else { log('Local image'); return widget.product!.productImage.isEmpty ? SvgPicture.asset( PRODUCT_IMAGE_, height: 30, width: 30, fit: BoxFit.contain, ) : ClipRRect( borderRadius: BorderRadius.circular(8), // Image border child: SizedBox( // Image radius height: 80, child: Image.memory(widget.product!.productImage, fit: BoxFit.cover), ), ); // Image.memory(widget.product!.productImage); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/forgot_password
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/forgot_password/ui/forgot_password.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../utils/ui_utils/textfield_border_decoration.dart'; import '../../../../../widgets/button.dart'; import '../../../../../widgets/text_field_widget.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../network/api_constants/api_paths.dart'; import '../../../service/forgot_password/api/forgot_password_api.dart'; import 'verify_otp.dart'; class ForgotPassword extends StatefulWidget { const ForgotPassword({Key? key}) : super(key: key); @override State<ForgotPassword> createState() => _ForgotPasswordState(); } class _ForgotPasswordState extends State<ForgotPassword> { late TextEditingController _emailCtrl, _urlCtrl; @override void initState() { super.initState(); _emailCtrl = TextEditingController(); _urlCtrl = TextEditingController(); _urlCtrl.text = "getpos.in"; } @override void dispose() { _emailCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { /// MAIN BODY return Scaffold( resizeToAvoidBottomInset: true, body: SafeArea( child: Padding( padding: smallPaddingAll(), child: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: Column( children: [ Row( children: [ InkWell( onTap: () => Navigator.pop(context), child: Padding( padding: smallPaddingAll(), child: SvgPicture.asset( BACK_IMAGE, color: BLACK_COLOR, width: 25, ), ), ), ], ), hightSpacer50, hightSpacer50, // hightSpacer50, // appLogo Image.asset(APP_ICON, width: 100, height: 100), hightSpacer50, hightSpacer25, headingLblWidget(), hightSpacer15, instanceUrlTxtboxSection(context), hightSpacer15, forgotPassTxtSection(), hightSpacer32, otpBtnWidget(), ], ), ), ), )); } ///Input field for entering the instance URL Widget instanceUrlTxtboxSection(context) => Container( margin: horizontalSpace(), padding: smallPaddingAll(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: leftSpace(x: 10), child: Text( URL_TXT, style: getTextStyle(fontSize: MEDIUM_MINUS_FONT_SIZE), ), ), hightSpacer15, TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _urlCtrl, hintText: URL_HINT, ), ], ), ); /// HANDLE FORGOT PASS BTN CLICK Future<void> _handleForgotPassBtnClick() async { String url = "https://${_urlCtrl.text}/api/"; try { Helper.showLoaderDialog(context); CommanResponse response = await ForgotPasswordApi() .sendResetPasswordMail(_emailCtrl.text.trim(), url.trim()); if (response.status!) { if (!mounted) return; Helper.hideLoader(context); Navigator.push(context, MaterialPageRoute(builder: (context) => const VerifyOtp())); } else { if (!mounted) return; Helper.hideLoader(context); Helper.showPopup(context, response.message); } } catch (e) { log('Exception ocurred in Forgot Password :: $e'); } } /// FORGOT PASSWORD SECTION Widget forgotPassTxtSection() => Container( margin: horizontalSpace(), padding: smallPaddingAll(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: leftSpace(x: 10), child: Text( FORGOT_EMAIL_TXT, style: getTextStyle(fontSize: MEDIUM_MINUS_FONT_SIZE), ), ), hightSpacer15, TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _emailCtrl, hintText: FORGOT_EMAIL_HINT, ), ], ), ); /// SUBMIT BTN WIDGET Widget otpBtnWidget() => Center( child: ButtonWidget( onPressed: () async { await _handleForgotPassBtnClick(); }, width: MediaQuery.of(context).size.width, title: FORGOT_BTN_TXT, colorBG: MAIN_COLOR, ), ); /// HEADER HEADING SECTION Widget headingLblWidget() => Center( child: Text( FORGOT_PASSWORD_TITLE.toUpperCase(), style: getTextStyle( fontWeight: FontWeight.bold, fontSize: LARGE_FONT_SIZE, color: MAIN_COLOR), ), ); }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/forgot_password
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/forgot_password/ui/verify_otp.dart
import 'package:flutter/material.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../widgets/button.dart'; import '../../../../constants/asset_paths.dart'; class VerifyOtp extends StatefulWidget { const VerifyOtp({Key? key}) : super(key: key); @override State<VerifyOtp> createState() => _VerifyOtpState(); } class _VerifyOtpState extends State<VerifyOtp> { double txtBorderWidth = 0.3; late TextEditingController _otpCtrl; @override void initState() { super.initState(); _otpCtrl = TextEditingController(); } @override void dispose() { _otpCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { Widget verifyOtpBtnWidget = Center( child: ButtonWidget( onPressed: () { Navigator.popUntil(context, (route) => route.isFirst); }, title: FORGOT_BTN_TXT, colorBG: MAIN_COLOR, width: MediaQuery.of(context).size.width, ), ); return Scaffold( body: SafeArea( child: Column( children: [ hightSpacer50, hightSpacer50, hightSpacer50, // appLogo, Image.asset(APP_ICON, width: 100, height: 100), hightSpacer50, hightSpacer50, Center( child: Text( VERIFY_OTP_TITLE.toUpperCase(), style: getTextStyle( fontWeight: FontWeight.bold, fontSize: LARGE_FONT_SIZE, color: MAIN_COLOR), ), ), hightSpacer45, Center( child: Padding( padding: horizontalSpace(x: 32), child: Text( VERIFY_OTP_MSG, textAlign: TextAlign.center, style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.w400, ), ), ), ), hightSpacer40, verifyOtpBtnWidget, hightSpacer32, ], ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/parked_orders
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/parked_orders/ui/order_detail_screen.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:nb_posx/core/mobile/create_order_new/ui/cart_screen.dart'; import 'package:nb_posx/core/mobile/home/ui/product_list_home.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../database/db_utils/db_parked_order.dart'; import '../../../../../database/models/order_item.dart'; import '../../../../../database/models/park_order.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../widgets/product_shimmer_widget.dart'; import '../../add_products/ui/added_product_item.dart'; import 'widget/header_data.dart'; class OrderDetailScreen extends StatefulWidget { final ParkOrder order; const OrderDetailScreen({Key? key, required this.order}) : super(key: key); @override State<OrderDetailScreen> createState() => _OrderDetailScreenState(); } class _OrderDetailScreenState extends State<OrderDetailScreen> { double totalAmount = 0.0; double subTotalAmount = 0.0; double taxAmount = 0.0; int totalItems = 0; double taxPercentage = 0; @override void initState() { super.initState(); _configureTaxAndTotal(widget.order.items); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Stack( children: [ SingleChildScrollView( physics: const BouncingScrollPhysics(), padding: const EdgeInsets.only(left: 10, right: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // const CustomAppbar( // title: "Parked order", // hideSidemenu: true, // ), Stack( alignment: Alignment.center, children: [ Align( alignment: Alignment.topLeft, child: InkWell( onTap: () => Navigator.pop(context), child: Padding( padding: smallPaddingAll(), child: SvgPicture.asset( BACK_IMAGE, color: BLACK_COLOR, width: 25, ), ), ), ), Center( child: Text( 'Parked Order', style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, color: DARK_GREY_COLOR), ), ), Align( alignment: Alignment.topRight, child: Stack(alignment: Alignment.topCenter, children: [ IconButton( onPressed: (() { if (widget.order != null) { Navigator.push( context, MaterialPageRoute( builder: (context) => CartScreen(order: widget.order))); } else { Helper.showPopup(context, "Your cart is empty"); } }), icon: SvgPicture.asset( CART_ICON, height: 25, width: 25, ), ), Container( padding: const EdgeInsets.all(6), margin: const EdgeInsets.only(left: 20), decoration: const BoxDecoration( shape: BoxShape.circle, color: MAIN_COLOR), child: Text( widget.order != null ? widget.order.items.length .toInt() .toString() : "0", style: getTextStyle( fontSize: SMALL_FONT_SIZE, color: WHITE_COLOR), )) ])) ], ), hightSpacer20, Padding( padding: horizontalSpace(x: 13), child: Row( children: [ Expanded( flex: 2, child: ParkedOrderHeaderData( heading: "Customer Name", headingColor: DARK_GREY_COLOR, content: widget.order.customer.name, )), Expanded( flex: 2, child: ParkedOrderHeaderData( heading: "Mobile", content: widget.order.customer.phone, headingColor: DARK_GREY_COLOR, // crossAlign: CrossAxisAlignment.center, )), InkWell( onTap: () => _handleOrderDelete(context, "Do you want to delete this parked order?"), child: Container( decoration: BoxDecoration( color: MAIN_COLOR, borderRadius: BorderRadius.circular(20)), padding: miniPaddingAll(), child: SvgPicture.asset( DELETE_IMAGE, color: WHITE_COLOR, width: 15, ), ), ), ], )), Padding( padding: paddingXY(x: 13), child: Row( children: [ Expanded( flex: 2, child: ParkedOrderHeaderData( heading: "Date & Time", headingColor: DARK_GREY_COLOR, content: Helper.getFormattedDateTime( widget.order.transactionDateTime), )), ], )), Padding( padding: paddingXY(x: 13, y: 0), child: Row( children: [ Expanded( flex: 2, child: ParkedOrderHeaderData( heading: "Order Amount", headingColor: DARK_GREY_COLOR, content: "$appCurrency ${totalAmount.toStringAsFixed(2)}", contentColor: MAIN_COLOR, )), ], )), hightSpacer15, Padding( padding: paddingXY(x: 16, y: 16), child: Text( "Items", style: getTextStyle( fontWeight: FontWeight.bold, fontSize: MEDIUM_PLUS_FONT_SIZE, color: BLACK_COLOR), ), ), productList(widget.order.items) ], ), ), Padding( padding: const EdgeInsets.only(left: 10, right: 10), child: Align( alignment: Alignment.bottomLeft, child: Row( children: [ _getAddMoreBtn(), _getCheckoutBtn(), ], ), )) ], )), ); } Widget productList(List<OrderItem> prodList) { return Padding( padding: horizontalSpace(), child: ListView.separated( separatorBuilder: (context, index) { return const Divider(); }, shrinkWrap: true, itemCount: prodList.isEmpty ? 10 : prodList.length, primary: false, itemBuilder: (context, position) { if (prodList.isEmpty) { return const ProductShimmer(); } else { return InkWell( onTap: () { // _openItemDetailDialog(context, prodList[position]); }, child: AddedProductItem( product: prodList[position], onDelete: () => _handleItemDelete( context, "Are you sure you want to delete this item?", prodList[position]), onItemAdd: () { setState(() { if (prodList[position].orderedQuantity < prodList[position].stock) { prodList[position].orderedQuantity = prodList[position].orderedQuantity + 1; _updateOrderPriceAndSave(); } }); }, onItemRemove: () { setState(() { if (prodList[position].orderedQuantity > 0) { prodList[position].orderedQuantity = prodList[position].orderedQuantity - 1; if (prodList[position].orderedQuantity == 0) { widget.order.items.remove(prodList[position]); if (prodList.isEmpty) { DbParkedOrder().deleteOrder(widget.order); Navigator.pop(context, "reload"); } else { _updateOrderPriceAndSave(); } } else { _updateOrderPriceAndSave(); } } }); }, ), ); } }), ); } Widget _getCheckoutBtn() { return Expanded( child: Container( margin: paddingXY(x: 5, y: 5), height: 60, decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: MAIN_COLOR, ), child: Row( children: [ widthSpacer(15), Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( widget.order.items.length > 1 ? "${widget.order.items.length} Items" : "${widget.order.items.length} Item", style: getTextStyle( fontSize: SMALL_FONT_SIZE, color: WHITE_COLOR, fontWeight: FontWeight.normal), ), Text("$appCurrency ${totalAmount.toStringAsFixed(2)}", style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.w600, color: WHITE_COLOR)) ], ), Expanded( child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => CartScreen(order: widget.order))); }, child: Text("Checkout", textAlign: TextAlign.right, style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.w400, color: WHITE_COLOR)), ), ), widthSpacer(15) ], ), ), ); } Widget _getAddMoreBtn() { return InkWell( onTap: () { //Get.to(NewCreateOrder(order: widget.order)); Navigator.push( context, MaterialPageRoute( builder: (context) => ProductListHome( parkedOrder: widget.order, isForNewOrder: true, ))); }, child: Container( margin: paddingXY(x: 5, y: 0), padding: paddingXY(), height: 60, width: MediaQuery.of(context).size.width / 4, decoration: BoxDecoration( color: GREEN_COLOR, borderRadius: BorderRadius.circular(5)), child: Text( "Add more products", textAlign: TextAlign.center, style: getTextStyle( color: WHITE_COLOR, fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.normal), ), ), ); } Future<void> _handleOrderDelete(BuildContext context, String msg) async { var res = await Helper.showConfirmationPopup(context, msg, OPTION_YES, hasCancelAction: true); if (res != OPTION_CANCEL.toLowerCase()) { bool result = await DbParkedOrder().deleteOrder(widget.order); if (result) { if (!mounted) return; await Helper.showConfirmationPopup( context, "Parked order deleted successfully", OPTION_OK); if (!mounted) return; Navigator.pop(context, "reload"); } else { if (!mounted) return; await Helper.showConfirmationPopup(context, "Something went wrong, Please try again later!!!", OPTION_OK); } } } Future<void> _handleItemDelete( BuildContext context, String msg, OrderItem itemToRemove) async { var res = await Helper.showConfirmationPopup(context, msg, OPTION_YES, hasCancelAction: true); if (res != OPTION_CANCEL.toLowerCase()) { bool result = await DbParkedOrder().removeOrderItem(widget.order, itemToRemove); if (result) { if (!mounted) return; await Helper.showConfirmationPopup( context, "Parked Order Item Deleted Successfully", OPTION_OK); if (widget.order.items.isEmpty) { if (!mounted) return; _handleOrderDelete( context, "Removing order as no Item in order remaining!!!"); } else { setState(() {}); } } else { if (!mounted) return; await Helper.showConfirmationPopup(context, "Something went wrong, Please try again later!!!", OPTION_OK); } } } void _updateOrderPriceAndSave() { double orderAmount = 0; for (OrderItem item in widget.order.items) { orderAmount += item.orderedPrice * item.orderedQuantity; } widget.order.orderAmount = orderAmount; _configureTaxAndTotal(widget.order.items); DbParkedOrder().saveOrder(widget.order); } //TODO:: Siddhant - Need to correct the tax calculation logic here. _configureTaxAndTotal(List<OrderItem> items) { totalAmount = 0.0; subTotalAmount = 0.0; taxAmount = 0.0; totalItems = 0; taxPercentage = 0; for (OrderItem item in items) { //taxPercentage = taxPercentage + (item.tax * item.orderedQuantity); log('Tax Percentage after adding ${item.name} :: $taxPercentage'); subTotalAmount = subTotalAmount + (item.orderedPrice * item.orderedQuantity); log('SubTotal after adding ${item.name} :: $subTotalAmount'); if (item.attributes.isNotEmpty) { for (var attribute in item.attributes) { //taxPercentage = taxPercentage + attribute.tax; //log('Tax Percentage after adding ${attribute.name} :: $taxPercentage'); if (attribute.options.isNotEmpty) { for (var option in attribute.options) { if (option.selected) { //taxPercentage = taxPercentage + option.tax; subTotalAmount = subTotalAmount + (option.price * item.orderedQuantity); log('SubTotal after adding ${attribute.name} :: $subTotalAmount'); } } } } } } //taxAmount = (subTotalAmount / 100) * taxPercentage; totalAmount = subTotalAmount + taxAmount; widget.order.orderAmount = totalAmount; log('Subtotal :: $subTotalAmount'); log('Tax percentage :: $taxAmount'); log('Tax Amount :: $taxAmount'); log('Total :: $totalAmount'); setState(() {}); //return taxPercentage; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/parked_orders
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/parked_orders/ui/orderlist_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import './widget/parked_data_item.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../database/db_utils/db_parked_order.dart'; import '../../../../../database/models/park_order.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../widgets/custom_appbar.dart'; import '../../../../../widgets/search_widget.dart'; import 'order_detail_screen.dart'; class OrderListScreen extends StatefulWidget { const OrderListScreen({Key? key}) : super(key: key); @override State<OrderListScreen> createState() => _OrderListScreenState(); } class _OrderListScreenState extends State<OrderListScreen> { late TextEditingController searchCtrl; List<ParkOrder> orderFromLocalDB = []; List<ParkOrder> parkedOrders = []; @override void initState() { searchCtrl = TextEditingController(); super.initState(); getParkedOrders(); } @override void dispose() { searchCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: SingleChildScrollView( primary: true, child: Column( children: [ const CustomAppbar( title: "Parked Orders", hideSidemenu: true, ), hightSpacer10, Padding( padding: horizontalSpace(), child: SearchWidget( inputFormatters: [ FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(12) ], searchHint: 'Enter customer mobile no.', searchTextController: searchCtrl, onTextChanged: (text) { if (text.length >= 3) { filterSalesData(text); } else { getParkedOrders(); } }, onSubmit: (text) { if (text.length >= 3) { filterSalesData(text); } else { getParkedOrders(); } }, )), hightSpacer10, parkedOrders.isNotEmpty ? ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), primary: false, itemCount: parkedOrders.length, itemBuilder: (context, position) { return ParkedDataItem( saleOrder: parkedOrders[position], onClick: () async { var res = await Navigator.push( context, MaterialPageRoute( builder: (context) => OrderDetailScreen( order: parkedOrders[position], ), ), ); if (res == "reload") { getParkedOrders(); } }, onDelete: () => _handleDelete(context, parkedOrders[position])); }) : Center( child: Text( NO_ORDERS_FOUND_MSG, style: getTextStyle(fontSize: MEDIUM_FONT_SIZE), ), ), ], ), )), ); } Future<void> getParkedOrders() async { orderFromLocalDB = await DbParkedOrder().getOrders(); parkedOrders = orderFromLocalDB.reversed.toList(); setState(() {}); } ///Function to filter the orders as per the search keyword. void filterSalesData(String searchText) { if (searchText.trim().isEmpty) { parkedOrders = orderFromLocalDB.reversed.toList(); } else { parkedOrders = orderFromLocalDB.where((element) => //element.id.toLowerCase().contains(searchText) || //element.customer.name.toLowerCase().contains(searchText) || element.customer.phone.toLowerCase().contains(searchText)).toList(); parkedOrders = parkedOrders.reversed.toList(); } setState(() {}); } Future<void> _handleDelete(BuildContext context, ParkOrder order) async { var res = await Helper.showConfirmationPopup( context, "Do you want to delete this parked order", OPTION_YES, hasCancelAction: true); if (res != OPTION_CANCEL.toLowerCase()) { bool result = await DbParkedOrder().deleteOrder(order); if (result) { if (!mounted) return; await Helper.showConfirmationPopup( context, "Parked Order Deleted Successfully", OPTION_OK); getParkedOrders(); } else { if (!mounted) return; await Helper.showConfirmationPopup( context, SOMETHING_WENT_WRONG, OPTION_OK); } } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/parked_orders/ui
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/parked_orders/ui/widget/header_data.dart
import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import 'package:flutter/material.dart'; // ignore: must_be_immutable class ParkedOrderHeaderData extends StatefulWidget { String? heading; String? content; Color? headingColor; Color? contentColor; CrossAxisAlignment crossAlign; ParkedOrderHeaderData( {Key? key, this.heading, this.content, this.crossAlign = CrossAxisAlignment.start, this.headingColor = BLACK_COLOR, this.contentColor = BLACK_COLOR}) : super(key: key); @override State<ParkedOrderHeaderData> createState() => _ParkedOrderHeaderDataState(); } class _ParkedOrderHeaderDataState extends State<ParkedOrderHeaderData> { @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: widget.crossAlign, children: [ Text(widget.heading!, style: getTextStyle( fontWeight: FontWeight.w500, color: widget.headingColor)), hightSpacer5, Text( widget.content!, style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE, color: widget.contentColor, fontWeight: FontWeight.w500), ) ], ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/parked_orders/ui
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/parked_orders/ui/widget/parked_data_item.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:intl/intl.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../database/models/park_order.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class ParkedDataItem extends StatelessWidget { ParkOrder? saleOrder; Function onDelete; Function onClick; ParkedDataItem( {Key? key, this.saleOrder, required this.onDelete, required this.onClick}) : super(key: key); @override Widget build(BuildContext context) { String dateTime = "${saleOrder!.date} ${saleOrder!.time}"; String date = DateFormat('EEEE, d LLLL y') .format(DateTime.parse(dateTime)) .toString(); String time = DateFormat().add_jm().format(DateTime.parse(dateTime)).toString(); return InkWell( onTap: () => onClick(), child: Container( decoration: BoxDecoration( // color: GREY_COLOR, border: Border.all(color: GREY_COLOR), borderRadius: BorderRadius.circular(10), ), margin: mediumPaddingAll(), padding: mediumPaddingAll(), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text( saleOrder!.customer.name, // '${saleOrder!.date} ${saleOrder!.time}', style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.w600), ), const Spacer(), Text( saleOrder!.customer.phone, // '${saleOrder!.date} ${saleOrder!.time}', style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.w600), ), ], ), hightSpacer4, Row( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "$date, $time", // '$PARKED_ORDER_ID - ${saleOrder!.id}', style: getItalicStyle(fontSize: SMALL_FONT_SIZE), ), hightSpacer7, Text( '$appCurrency ${saleOrder!.orderAmount.toStringAsFixed(2)}', style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, color: MAIN_COLOR), ), ], ), const Spacer(), InkWell( onTap: () => onDelete(), child: Padding( padding: mediumPaddingAll(), child: SvgPicture.asset( DELETE_IMAGE, color: MAIN_COLOR, width: 15, ), ), ) ], ), ], ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/login
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/login/ui/login.dart
import 'dart:developer'; import 'dart:io'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:nb_posx/core/mobile/home/ui/product_list_home.dart'; import 'package:nb_posx/core/service/login/api/verify_instance_service.dart'; import 'package:nb_posx/database/db_utils/db_instance_url.dart'; import 'package:nb_posx/network/api_constants/api_paths.dart'; import 'package:package_info_plus/package_info_plus.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../utils/ui_utils/textfield_border_decoration.dart'; import '../../../../../widgets/button.dart'; import '../../../../../widgets/text_field_widget.dart'; import '../../../../constants/asset_paths.dart'; import '../../../service/login/api/login_api_service.dart'; import '../../forgot_password/ui/forgot_password.dart'; import '../../webview_screens/enums/topic_types.dart'; import '../../webview_screens/ui/webview_screen.dart'; class Login extends StatefulWidget { const Login({Key? key}) : super(key: key); @override State<Login> createState() => _LoginState(); } class _LoginState extends State<Login> { late TextEditingController _emailCtrl, _passCtrl, _urlCtrl; String? version; @override void initState() { super.initState(); _emailCtrl = TextEditingController(); _passCtrl = TextEditingController(); _urlCtrl = TextEditingController(); _emailCtrl.text = "[email protected]"; _passCtrl.text = "demouser@123"; _urlCtrl.text = "getpos.in"; _getAppVersion(); } @override void dispose() { _emailCtrl.dispose(); _passCtrl.dispose(); super.dispose(); } /// HANDLE BACK BTN PRESS ON LOGIN SCREEN /* _showExitConfirmationDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Close App Confirmation'), content: Text('Are you sure you want to close the app?'), actions: <Widget>[ TextButton( onPressed: () { Navigator.of(context).pop(); // Close the dialog }, child: Text('No'), ), TextButton( onPressed: () { Navigator.of(context).pop(); // Close the dialog // You can add your code here to exit the app // For example, you can use SystemNavigator.pop() to exit the app. }, child: Text('Yes'), ), ], ); }, ); }*/ @override Widget build(BuildContext context) { return //WillPopScope( // onWillPop: _showExitConfirmationDialog(context), // child: WillPopScope( onWillPop: () async { CommanResponse res = await VerificationUrl.checkAppStatus(); if (res.message == true) { _onBackPressed() {} return true; } else { Helper.showPopup( context, "Please update your app to latest version", barrierDismissible: true); return false; } }, child: Scaffold( resizeToAvoidBottomInset: true, backgroundColor: WHITE_COLOR, body: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: Column( children: [ hightSpacer50, Image.asset(APP_ICON, width: 100, height: 100), hightSpacer50, instanceUrlTxtboxSection(context), hightSpacer20, headingLblWidget(context), hightSpacer15, emailTxtBoxSection(context), hightSpacer10, passwordTxtBoxSection(context), hightSpacer10, forgotPasswordSection(context), hightSpacer30, termAndPolicySection(context), hightSpacer32, loginBtnWidget(context), hightSpacer25 // const Spacer(), // Center( // child: Text( // version ?? APP_VERSION_FALLBACK, // style: getHintStyle(), // )), // hightSpacer10 ], )), )); } /// HANDLE LOGIN BTN ACTION Future<void> login(String email, String password, String url) async { { if (email.isEmpty) { Helper.showPopup(context, "Please enter email"); } else if (password.isEmpty) { Helper.showPopup(context, "Please enter password"); } else { try { Helper.showLoaderDialog(context); CommanResponse res = await VerificationUrl.checkAppStatus(); if (res.message == true) { CommanResponse response = await LoginService.login(email, password, url); print(response); if (response.status!) { //Adding static data into the database // await addDataIntoDB(); if (!mounted) return; Helper.hideLoader(context); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => ProductListHome())); } else { if (!mounted) return; Helper.hideLoader(context); Helper.showPopup(context, response.message!); } } else { Helper.showPopup( context, "Please update your app to latest version", barrierDismissible: true); } } catch (e) { Helper.hideLoader(context); log('Exception Caught :: $e'); debugPrintStack(); Helper.showSnackBar(context, SOMETHING_WRONG); } } } } Future<void> _getAppVersion() async { PackageInfo packageInfo = await PackageInfo.fromPlatform(); setState(() { version = "$APP_VERSION - ${packageInfo.version}"; }); } ///Input field for entering the instance URL Widget instanceUrlTxtboxSection(context) => Container( margin: horizontalSpace(), padding: smallPaddingAll(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: leftSpace(x: 10), child: Text( URL_TXT, style: getTextStyle(fontSize: MEDIUM_MINUS_FONT_SIZE), ), ), hightSpacer15, TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _urlCtrl, hintText: URL_HINT, ), ], ), ); /// LOGIN BUTTON Widget loginBtnWidget(context) => Center( child: ButtonWidget( onPressed: () async { await DbInstanceUrl().deleteUrl(); String url = "https://${_urlCtrl.text}/api/"; await login(_emailCtrl.text, _passCtrl.text, url); }, title: LOGIN_TXT, colorBG: MAIN_COLOR, width: MediaQuery.of(context).size.width, ), ); /// EMAIL SECTION Widget emailTxtBoxSection(context) => Container( margin: horizontalSpace(), padding: smallPaddingAll(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: leftSpace(x: 10), child: Text( EMAIL_TXT, style: getTextStyle(fontSize: MEDIUM_MINUS_FONT_SIZE), ), ), hightSpacer15, TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _emailCtrl, hintText: EMAIL_HINT, ), ], ), ); /// PASSWORD SECTION Widget passwordTxtBoxSection(context) => Container( margin: horizontalSpace(), padding: smallPaddingAll(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: leftSpace(x: 10), child: Text( PASSWORD_TXT, style: getTextStyle(fontSize: MEDIUM_MINUS_FONT_SIZE), ), ), hightSpacer15, TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _passCtrl, hintText: PASSWORD_HINT, password: true, ), ], ), ); /// FORGOT PASSWORD SECTION Widget forgotPasswordSection(context) => Row( mainAxisAlignment: MainAxisAlignment.end, children: [ InkWell( onTap: () { _emailCtrl.clear(); _passCtrl.clear(); Navigator.push( context, MaterialPageRoute( builder: (context) => const ForgotPassword())); }, child: Padding( padding: rightSpace(), child: Text( FORGET_PASSWORD_SMALL_TXT, style: getTextStyle( color: MAIN_COLOR, fontSize: MEDIUM_MINUS_FONT_SIZE, fontWeight: FontWeight.normal), ), ), ), ], ); /// TERM AND CONDITION SECTION Widget termAndPolicySection(context) => Padding( padding: horizontalSpace(x: 40), child: RichText( textAlign: TextAlign.center, text: TextSpan( text: BY_SIGNING_IN, style: getTextStyle( color: DARK_GREY_COLOR, fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.normal), children: <TextSpan>[ TextSpan( recognizer: TapGestureRecognizer() ..onTap = () { Navigator.push( context, MaterialPageRoute( builder: (context) => WebViewScreen( topicTypes: TopicTypes.TERMS_AND_CONDITIONS, apiUrl: "https://${_urlCtrl.text}/api/", ))); }, text: TERMS_CONDITIONS, style: getTextStyle( color: DARK_GREY_COLOR, fontWeight: FontWeight.bold, fontSize: MEDIUM_FONT_SIZE)), TextSpan( text: AND_TXT, style: getTextStyle( color: DARK_GREY_COLOR, fontWeight: FontWeight.normal, fontSize: MEDIUM_FONT_SIZE)), TextSpan( recognizer: TapGestureRecognizer() ..onTap = () { Navigator.push( context, MaterialPageRoute( builder: (context) => WebViewScreen( topicTypes: TopicTypes.PRIVACY_POLICY, apiUrl: "https://${_urlCtrl.text}/api/", ))); }, text: PRIVACY_POLICY, style: getTextStyle( color: DARK_GREY_COLOR, fontWeight: FontWeight.bold, fontSize: MEDIUM_FONT_SIZE)), ]), ), ); /// LOGIN TXT(HEADING) IN CENTER Widget headingLblWidget(context) => Center( child: Text( LOGIN_TXT.toUpperCase(), style: getTextStyle( color: MAIN_COLOR, fontWeight: FontWeight.bold, fontSize: LARGE_FONT_SIZE, ), ), ); /// SUB LOGIN TXT(SUBHEADING) IN CENTER Widget subHeadingLblWidget(context) => Center( child: Text( ACCESS_YOUR_ACCOUNT, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w500, color: BLACK_COLOR), ), ); ///Method to check whether the API URL is correct. /* bool isValidInstanceUrl() { String url = "https://${_urlCtrl.text}/api/"; return Helper.isValidUrl(url); }*/ Future<bool> _onBackPressed() async { var res = await Helper.showConfirmationPopup( context, CLOSE_APP_QUESTION, OPTION_YES, hasCancelAction: true); return false; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/checkout
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/checkout/ui/checkout_screen.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:intl/intl.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../database/db_utils/db_hub_manager.dart'; import '../../../../database/models/hub_manager.dart'; import '../../../../database/models/park_order.dart'; import '../../../../database/models/sale_order.dart'; import '../../../../utils/helper.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/custom_appbar.dart'; import '../../../../widgets/long_button_widget.dart'; import '../../sale_success/ui/sale_success_screen.dart'; // ignore: must_be_immutable class CheckoutScreen extends StatefulWidget { // Customer? selectedCustomer; // List<OrderItem> orderedProducts; ParkOrder order; CheckoutScreen({Key? key, required this.order}) : super(key: key); @override State<CheckoutScreen> createState() => _CheckoutScreenState(); } class _CheckoutScreenState extends State<CheckoutScreen> { bool _isCODSelected = false; double totalAmount = 0.0; int totalItems = 0; late HubManager? hubManager; // String? transactionID; late String paymentMethod; // late TextEditingController _transactionIdCtrl; // bool _isEWalletEnabled = false; @override void initState() { super.initState(); _getHubManager(); totalAmount = Helper().getTotal(widget.order.items); totalItems = widget.order.items.length; } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: ListView( children: [ const CustomAppbar(title: CHECKOUT_TXT_SMALL), // hightSpacer10, Padding( padding: paddingXY(x: 16), child: Row( children: [ getPaymentOption( PAYMENT_CASH_ICON, CASH_PAYMENT_TXT, _isCODSelected), widthSpacer(16), getPaymentOption( PAYMENT_CARD_ICON, CARD_PAYMENT_TXT, _isCODSelected), ], ), ), ], ), ), bottomNavigationBar: LongButton( buttonTitle: CONFIRM_PAYMENT, isAmountAndItemsVisible: true, totalAmount: '$totalAmount', totalItems: '$totalItems', onTap: () => createSale(_isCODSelected?"Card":"Cash"), ), ); } getPaymentOption(String icon, String title, bool selected,) { return Expanded( child: InkWell( onTap: () { setState(() { if (!selected) { _isCODSelected = !_isCODSelected; } }); }, child: Container( height: 180, decoration: BoxDecoration( color: selected ? OFF_WHITE_COLOR : WHITE_COLOR, border: Border.all( color: selected ? MAIN_COLOR : DARK_GREY_COLOR, width: 0.4), borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_20)), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( icon, height: 80, ), hightSpacer20, Text(title, style: getTextStyle( fontSize: LARGE_FONT_SIZE, color: DARK_GREY_COLOR)), ], ), ), ), ); } createSale(String paymentMethod) async { paymentMethod =paymentMethod; if(paymentMethod=="Card"){ return Helper.showPopup(context, "Comming soon" ); }else{ DateTime currentDateTime = DateTime.now(); String date = DateFormat('EEEE d, LLLL y').format(currentDateTime).toString(); log('Date : $date'); String time = DateFormat().add_jm().format(currentDateTime).toString(); log('Time : $time'); String orderId = await Helper.getOrderId(); log('Order No : $orderId'); SaleOrder saleOrder = SaleOrder( id: orderId, orderAmount: totalAmount, date: date, time: time, customer: widget.order.customer, manager: hubManager!, items: widget.order.items, transactionId: '', paymentMethod: paymentMethod, paymentStatus: "Paid", transactionSynced: false, parkOrderId: "${widget.order.transactionDateTime.millisecondsSinceEpoch}", tracsactionDateTime: currentDateTime); if (!mounted) return; Navigator.push( context, MaterialPageRoute( builder: (context) => SaleSuccessScreen(placedOrder: saleOrder))); }} void _getHubManager() async { hubManager = await DbHubManager().getManager(); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/checkout
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/checkout/ui/payment_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/svg.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../utils/ui_utils/card_border_shape.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../utils/ui_utils/text_styles/edit_text_hint_style.dart'; import '../../../../utils/ui_utils/textfield_border_decoration.dart'; // ignore: must_be_immutable class PaymentWidget extends StatefulWidget { final String? svgIconPath; final String? title; final bool? isCODPayment; final bool? isMPesa; final bool? isEWallet; bool? isChecked; TextEditingController? textEditingController; Function(bool isPaymentOptionChanged)? isSelected; PaymentWidget( {Key? key, this.svgIconPath, this.title, this.isCODPayment = false, this.isEWallet = false, this.isMPesa = false, this.isChecked, this.isSelected, this.textEditingController}) : super(key: key); @override State<PaymentWidget> createState() => _PaymentWidgetState(); } class _PaymentWidgetState extends State<PaymentWidget> { @override Widget build(BuildContext context) { return Card( shape: cardBorderShape(radius: CARD_BORDER_SIDE_RADIUS_08), child: Column( children: [ ListTile( leading: SizedBox( height: 50, width: 50, child: Card( elevation: 0.0, color: WHITE_COLOR, shape: cardBorderShape(radius: CARD_BORDER_SIDE_RADIUS_08), child: Padding( padding: mediumPaddingAll(), child: SvgPicture.asset( widget.svgIconPath!, height: 20, width: 20, fit: BoxFit.contain, )), )), title: Text( widget.title!, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w600, ), ), trailing: InkWell( onTap: () => widget.isSelected!(!widget.isChecked!), child: widget.isChecked! ? Container( clipBehavior: Clip.antiAlias, decoration: BoxDecoration( border: Border.all(color: MAIN_COLOR), // border: Border.all(color: Colors.yellow.shade800), color: MAIN_COLOR, // color: Colors.yellow.shade800, borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_08), ), child: const Icon( Icons.check, size: 20.0, color: WHITE_COLOR, )) : Container( decoration: BoxDecoration( border: Border.all(color: BLACK_COLOR), borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_08), ), child: const Icon( null, size: 20.0, ), ), ), ), Visibility( visible: widget.isChecked!, child: SizedBox( height: 0.5, child: Container( color: GREY_COLOR, ), )), Visibility(visible: widget.isChecked!, child: _getBottomWidget) ], ), ); } Widget get _getBottomWidget { if (widget.isCODPayment!) { return Padding( padding: mediumPaddingAll(), child: Text( CASH_PAYMENT_MSG, style: getTextStyle(fontWeight: FontWeight.normal), )); } else if (widget.isMPesa!) { return Padding( padding: mediumPaddingAll(), child: SizedBox( height: 80, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( TRANSACTION_TXT, style: getTextStyle(fontSize: SMALL_PLUS_FONT_SIZE), ), Container( decoration: txtFieldBorderDecoration, child: TextFormField( inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.allow(RegExp("[a-z,A-Z,0-9]")), LengthLimitingTextInputFormatter(12) ], style: getTextStyle( color: GREY_COLOR, fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.w600), controller: widget.textEditingController, cursorColor: LIGHT_GREY_COLOR, autocorrect: false, textInputAction: TextInputAction.next, decoration: InputDecoration( hintText: ENTER_UR_TRANSACTION_ID, hintStyle: getHintStyle(), focusColor: LIGHT_GREY_COLOR, contentPadding: leftSpace(), border: InputBorder.none, ), ), ), ], ), ), ); } else { return Container(); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/select_customer
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/select_customer/ui/selected_customer_widget.dart
import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../database/models/customer.dart'; import '../../../../utils/ui_utils/card_border_shape.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; // ignore: must_be_immutable class SelectedCustomerWidget extends StatefulWidget { Function? onDelete; Function? onTapChangeCustomer; Customer? selectedCustomer; SelectedCustomerWidget( {Key? key, this.onDelete, this.onTapChangeCustomer, this.selectedCustomer}) : super(key: key); @override State<SelectedCustomerWidget> createState() => _SelectedCustomerWidgetState(); } class _SelectedCustomerWidgetState extends State<SelectedCustomerWidget> { @override Widget build(BuildContext context) { return Padding( padding: horizontalSpace(), child: Card( child: Padding( padding: const EdgeInsets.only(top: 15, left: 10, right: 10), child: Column( children: [ Align( alignment: AlignmentDirectional.topStart, child: Text( SELECT_CUSTOMER_TXT, style: getTextStyle(), )), hightSpacer10, ListTile( contentPadding: horizontalSpace(x: 0), leading: SizedBox( height: 70, width: 70, child: Card( color: MAIN_COLOR.withOpacity(0.1), shape: cardBorderShape(), elevation: 0.0, child: Container(), // child: Padding( // padding: mediumPaddingAll(), // child: widget.selectedCustomer!.profileImage.isEmpty // ? SvgPicture.asset( // HOME_CUSTOMER_IMAGE, // height: 35, // width: 35, // fit: BoxFit.contain, // ) // : Image.memory( // widget.selectedCustomer!.profileImage, // )), ), ), title: Text( widget.selectedCustomer!.name, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w600), maxLines: 1, overflow: TextOverflow.ellipsis, ), subtitle: Text( widget.selectedCustomer!.phone, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ), trailing: IconButton( onPressed: () => widget.onDelete!(), icon: Padding( padding: miniPaddingAll(), child: SvgPicture.asset( DELETE_IMAGE, height: 35, width: 35, fit: BoxFit.contain, ))), ), hightSpacer10, const Divider( height: 1, color: GREY_COLOR, ), TextButton( onPressed: () => widget.onTapChangeCustomer!(), child: Text( CHANGE_CUSTOMER_TXT, style: getTextStyle(color: MAIN_COLOR), )) ], )), )); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/select_customer
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/select_customer/ui/select_customer.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import '../../../../constants/app_constants.dart'; import '../../../../database/db_utils/db_customer.dart'; import '../../../../database/models/customer.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/button.dart'; import '../../../../widgets/comman_tile_options.dart'; import '../../../../widgets/custom_appbar.dart'; import '../../../../widgets/search_widget.dart'; import '../../../../widgets/shimmer_widget.dart'; // ignore: must_be_immutable class SelectCustomerScreenOld extends StatefulWidget { const SelectCustomerScreenOld({Key? key}) : super(key: key); @override State<SelectCustomerScreenOld> createState() => _SelectCustomerScreenOldState(); } class _SelectCustomerScreenOldState extends State<SelectCustomerScreenOld> { // bool _value = false; int selectedPosition = -1; Customer? selectedCustomer; List<Customer> customers = []; TextEditingController searchCustomerController = TextEditingController(); bool isCustomersFound = true; @override void initState() { super.initState(); getCustomersFromDB(); } @override void dispose() { searchCustomerController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: SingleChildScrollView( physics: customers.isEmpty ? const NeverScrollableScrollPhysics() : const ScrollPhysics(), child: Column(children: [ const CustomAppbar(title: SELECT_CUSTOMER_TXT), Padding( padding: mediumPaddingAll(), child: SearchWidget( searchHint: SEARCH_HINT_TXT, searchTextController: searchCustomerController, onTextChanged: (text) { log('Changed text :: $text'); if (text.isNotEmpty) { filterCustomerData(text); } else { getCustomersFromDB(); } }, onSubmit: (text) { if (text.isNotEmpty) { filterCustomerData(text); } else { getCustomersFromDB(); } }, )), isCustomersFound ? ListView.builder( shrinkWrap: true, itemCount: customers.isEmpty ? 10 : customers.length, primary: false, itemBuilder: (context, position) { if (customers.isEmpty) { return const ShimmerWidget(); } else { return CommanTileOptions( isCheckBoxEnabled: true, isDeleteButtonEnabled: false, isSubtitle: true, checkBoxValue: selectedPosition == position, customer: customers[position], onCheckChanged: (value) { selectedPosition = position; selectedCustomer = customers[position]; setState(() {}); }, ); } }) : Center( child: Text( NO_DATA_FOUND, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w600), )), ])), ), bottomNavigationBar: Visibility( visible: selectedCustomer != null, child: Padding( padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10), child: ButtonWidget( width: MediaQuery.of(context).size.width, onPressed: () { Navigator.pop(context, selectedCustomer); }, fontSize: MEDIUM_FONT_SIZE, title: SELECT_CONTINUE_TXT)), ), ); } ///Function to get the customer data from api ///If not available from api then load from local database Future<void> getCustomersFromDB() async { //Fetch the data from local database customers = await DbCustomer().getCustomers(); isCustomersFound = customers.isNotEmpty; setState(() {}); } void filterCustomerData(String searchText) async { await getCustomersFromDB(); customers = customers .where((element) => element.name.toLowerCase().contains(searchText.toLowerCase()) || element.phone.toLowerCase().contains(searchText.toLowerCase())) .toList(); isCustomersFound = customers.isNotEmpty; setState(() {}); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/select_customer
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/select_customer/ui/new_select_customer.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:nb_posx/core/mobile/home/ui/product_list_home.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../database/db_utils/db_customer.dart'; import '../../../../database/models/customer.dart'; import '../../../../network/api_helper/comman_response.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../utils/ui_utils/textfield_border_decoration.dart'; import '../../../../widgets/button.dart'; import '../../../../widgets/custom_appbar.dart'; import '../../../../widgets/customer_tile.dart'; import '../../../../widgets/search_widget.dart'; import '../../../../widgets/shimmer_widget.dart'; import '../../../../widgets/text_field_widget.dart'; import '../../../service/select_customer/api/create_customer.dart'; import '../../../service/select_customer/api/get_customer.dart'; class NewSelectCustomer extends StatefulWidget { const NewSelectCustomer({Key? key}) : super(key: key); @override State<NewSelectCustomer> createState() => _NewSelectCustomerState(); } class _NewSelectCustomerState extends State<NewSelectCustomer> { Customer? selectedCustomer; List<Customer> customers = []; List<Customer> filteredCustomer = []; late TextEditingController searchCtrl; late TextEditingController _emailCtrl, _phoneCtrl, _nameCtrl; @override void initState() { searchCtrl = TextEditingController(); _emailCtrl = TextEditingController(); _nameCtrl = TextEditingController(); _phoneCtrl = TextEditingController(); // getCustomersFromDB(0); super.initState(); } @override void dispose() { searchCtrl.dispose(); _emailCtrl.dispose(); _nameCtrl.dispose(); _phoneCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: SingleChildScrollView( child: Column( children: [ // hightSpacer40, const CustomAppbar(title: CUSTOMERS_TXT, hideSidemenu: true), hightSpacer30, Padding( padding: horizontalSpace(), child: SearchWidget( inputFormatters: [ FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(12) ], searchHint: SEARCH_HINT_TXT, searchTextController: searchCtrl, keyboardType: TextInputType.phone, onTextChanged: (text) { if (text.isNotEmpty && text.isNotEmpty) { filterCustomerData(text); } //else { // getCustomersFromDB(0); // } }, onSubmit: (text) { if (text.isNotEmpty && text.isNotEmpty) { filterCustomerData(text); } //else { // getCustomersFromDB(0); // } }, ), ), hightSpacer15, filteredCustomer.isNotEmpty ? ListView.builder( shrinkWrap: true, itemCount: customers.isEmpty ? 10 : customers.length, primary: false, itemBuilder: (context, position) { if (customers.isEmpty) { return const ShimmerWidget(); } else { return CustomerTile( isCheckBoxEnabled: true, isDeleteButtonEnabled: false, customer: customers[position], isSubtitle: true, isHighlighted: true, onCheckChanged: (p0) { Navigator.pop(context, customers[position]); }, ); } }) : customers.isEmpty && searchCtrl.text.length < 10 ? Container() // ? Center( // child: Text( // SEARCH_CUSTOMER_MSG_TXT, // style: getTextStyle( // fontSize: SMALL_PLUS_FONT_SIZE, // fontWeight: FontWeight.w400, // ), // )) : _addNewCustomerUI(), ], ), ), ), ); } ///Function to get the customer data from api ///If not available from api then load from local database Future<void> getCustomersFromDB(val) async { //Fetch the data from local database customers = await DbCustomer().getCustomerNo(searchCtrl.text); if (val == 0) setState(() {}); } void filterCustomerData(String searchText) async { _phoneCtrl.text = searchText; await getCustomersFromDB(1); filteredCustomer = customers .where((element) => element.name.toLowerCase().contains(searchText.toLowerCase()) || element.phone.toLowerCase().contains(searchText.toLowerCase())) .toList(); if (filteredCustomer.isEmpty) { await _askCustomerAPI(searchText); } setState(() {}); } _addNewCustomerUI() { return SingleChildScrollView(child:Column( children: [ Center( child: Padding( padding: const EdgeInsets.fromLTRB(32, 16, 32, 32), child: Text( "No records were found. Please add the details below in order to continue.", style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500, color: MAIN_COLOR), ), )), Center( child: Text( "Add Customer", style: getTextStyle( fontSize: LARGE_PLUS_FONT_SIZE, fontWeight: FontWeight.w600, ), )), hightSpacer20, IgnorePointer (ignoring: true,child: Padding( padding: horizontalSpace(x: 20), child: TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _phoneCtrl, hintText: "Phone No.", txtColor: BLACK_COLOR)), ), hightSpacer20, Padding( padding: horizontalSpace(x: 20), child: TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _nameCtrl, hintText: "Enter Name", txtColor: BLACK_COLOR), ), hightSpacer20, Padding( padding: horizontalSpace(x: 20), child: TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _emailCtrl, hintText: "Enter Email (optional)", txtColor: BLACK_COLOR), ), hightSpacer30, SizedBox( width: MediaQuery.of(context).size.width - 40, child: ButtonWidget( onPressed: () { if (_nameCtrl.text.isNotEmpty && _phoneCtrl.text.isNotEmpty) { _newCustomerAPI(); } }, title: "Add and Create Order", )), hightSpacer20, SizedBox( width: MediaQuery.of(context).size.width - 40, child: ButtonWidget( onPressed: () { Navigator.pop(context); }, colorBG: DARK_GREY_COLOR, title: "Cancel", )), ], )); } Future<void> _newCustomerAPI() async { CommanResponse response = await CreateCustomer() .createNew(_phoneCtrl.text, _nameCtrl.text, _emailCtrl.text); if (response.status!) { filterCustomerData(_phoneCtrl.text); } else { Customer tempCustomer = Customer( // profileImage: image, // ward: Ward(id: "1", name: "1"), email: _emailCtrl.text.trim(), id: _phoneCtrl.text.trim(), name: _nameCtrl.text.trim(), phone: _phoneCtrl.text.trim(), isSynced: false, modifiedDateTime: DateTime.now()); List<Customer> customers = []; customers.add(tempCustomer); await DbCustomer().addCustomers(customers); filterCustomerData(_phoneCtrl.text); } } Future<void> _askCustomerAPI(String searchText) async { CommanResponse response = await GetCustomer().getByMobileno(searchText); if (response.status! && response.message == SUCCESS) { filterCustomerData(searchText); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/home
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/home/ui/home_tile.dart
import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; class HomeTile extends StatelessWidget { final String title, asset; final Widget nextScreen; final Function onReturn; const HomeTile( {Key? key, required this.title, required this.asset, required this.nextScreen, required this.onReturn}) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: () async { await Navigator.push( context, MaterialPageRoute(builder: (context) => nextScreen)); onReturn(); }, child: Container( decoration: BoxDecoration( color: OFF_WHITE_COLOR, border: Border.all(color: MAIN_COLOR, width: 0.4), borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_30)), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Card( elevation: 1, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(100)), child: SvgPicture.asset( asset, height: HOME_TILE_ASSET_HEIGHT, ), ), hightSpacer20, Text(title, style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.w500)), ], ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/home
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/home/ui/home.dart
import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/route_manager.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../database/db_utils/db_categories.dart'; import '../../../../../database/db_utils/db_hub_manager.dart'; import '../../../../../database/db_utils/db_sale_order.dart'; import '../../../../../database/models/hub_manager.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/helpers/sync_helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../create_order_new/ui/new_create_order.dart'; import '../../customers/ui/customers.dart'; import '../../finance/ui/finance.dart'; import '../../my_account/ui/my_account.dart'; import '../../parked_orders/ui/orderlist_screen.dart'; import '../../products/ui/products.dart'; import '../../transaction_history/view/transaction_screen.dart'; import 'home_tile.dart'; class Home extends StatefulWidget { const Home({Key? key}) : super(key: key); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { bool syncNowActive = true; late String managerName; late Uint8List profilePic; @override void initState() { super.initState(); managerName = "John"; profilePic = Uint8List.fromList([]); _getManagerName(); _checkForSyncNow(); _checkForRedirects(); } _checkForSyncNow() async { var offlineOrders = await DbSaleOrder().getOfflineOrders(); // debugPrint("OFFLINE ORDERS: ${offlineOrders.length}"); syncNowActive = offlineOrders.isEmpty; var categories = await DbCategory().getCategories(); debugPrint("Category: ${categories.length}"); setState(() {}); } _getManagerName() async { HubManager manager = await DbHubManager().getManager() as HubManager; managerName = manager.name; profilePic = manager.profileImage; setState(() {}); } @override Widget build(BuildContext context) { return Scaffold( // endDrawer: MainDrawer( // menuItem: Helper.getMenuItemList(context), // ), body: Builder( builder: (ctx) => SafeArea( child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: mediumPaddingAll(), child: SvgPicture.asset( MENU_ICON, color: WHITE_COLOR, width: 20, ), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ hightSpacer30, Text( WELCOME_BACK, style: getTextStyle( fontSize: SMALL_FONT_SIZE, color: MAIN_COLOR, fontWeight: FontWeight.w500, ), ), hightSpacer5, Text( managerName, style: getTextStyle( fontSize: LARGE_FONT_SIZE, color: DARK_GREY_COLOR), overflow: TextOverflow.ellipsis, ), hightSpacer30, ], ), ), InkWell( onTap: () => _openSideMenu(ctx), child: Padding( padding: mediumPaddingAll(), child: SvgPicture.asset( MENU_ICON, color: BLACK_COLOR, width: 20, ), ), ) ], ), Padding( padding: const EdgeInsets.fromLTRB( HOME_TILE_PADDING_LEFT, HOME_TILE_PADDING_TOP, HOME_TILE_PADDING_RIGHT, HOME_TILE_PADDING_BOTTOM), child: GridView.count( crossAxisCount: HOME_TILE_GRID_COUNT, mainAxisSpacing: HOME_TILE_VERTICAL_SPACING, crossAxisSpacing: HOME_TILE_HORIZONTAL_SPACING, shrinkWrap: true, childAspectRatio: .9, physics: const ScrollPhysics(), children: [ HomeTile( title: CREATE_ORDER_TXT, asset: CREATE_ORDER_IMAGE, nextScreen: NewCreateOrder(), onReturn: () {}, ), // HomeTile( // title: CREATE_ORDER_TXT, // asset: CREATE_ORDER_IMAGE, // nextScreen: const CreateOrderScreen(), // onReturn: () => _checkForSyncNow(), // ), HomeTile( title: PRODUCTS_TXT, asset: PRODUCT_IMAGE, nextScreen: const Products(), onReturn: () {}, ), HomeTile( title: CUSTOMERS_TXT, asset: CUSTOMER_IMAGE, nextScreen: const Customers(), onReturn: () {}, ), HomeTile( title: MY_ACCOUNT_TXT, asset: HOME_USER_IMAGE, nextScreen: const MyAccount(), onReturn: () {}, ), HomeTile( title: SALES_HISTORY_TXT, asset: SALES_IMAGE, nextScreen: const TransactionScreen(), // nextScreen: const SalesHistory(), onReturn: () {}, ), HomeTile( title: FINANCE_TXT, asset: FINANCE_IMAGE, nextScreen: const Finance(), onReturn: () {}, ), ], ), ), ], ), )), ), ); } /// /// Show the Active status of the Sync now Btn /// void manageSync(bool value) async { if (syncNowActive == false) { if (await Helper.isNetworkAvailable()) { Helper.showLoaderDialog(context); await SyncHelper().syncNowFlow(); _checkForSyncNow(); _getManagerName(); if (!mounted) return; Helper.hideLoader(context); } else { Helper.showSnackBar(context, NO_INTERNET); } } } void _openSideMenu(BuildContext context) { Scaffold.of(context).openEndDrawer(); } void _checkForRedirects() { if (Get.arguments != null && Get.arguments == "parked_order") { Future.delayed( Duration.zero, () => Get.to(() => const OrderListScreen(), duration: const Duration(milliseconds: 1))); } else if (Get.arguments != null && Get.arguments == "create_new_order") { Future.delayed(Duration.zero, () => Get.to(() => NewCreateOrder())); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/home
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/home/ui/product_list_home.dart
// ignore_for_file: use_build_context_synchronously import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_expandable_fab/flutter_expandable_fab.dart'; import 'package:flutter_svg/svg.dart'; import 'package:nb_posx/constants/asset_paths.dart'; import 'package:nb_posx/core/mobile/create_order_new/ui/cart_screen.dart'; import 'package:nb_posx/core/mobile/finance/ui/finance.dart'; import 'package:nb_posx/core/mobile/my_account/ui/my_account.dart'; import 'package:nb_posx/widgets/search_widget.dart'; import 'package:showcaseview/showcaseview.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../database/db_utils/db_categories.dart'; import '../../../../database/db_utils/db_hub_manager.dart'; import '../../../../database/models/category.dart'; import '../../../../database/models/customer.dart'; import '../../../../database/models/hub_manager.dart'; import '../../../../database/models/order_item.dart'; import '../../../../database/models/park_order.dart'; import '../../../../database/models/product.dart'; import '../../../../network/api_helper/comman_response.dart'; import '../../../../utils/helper.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/item_options.dart'; import '../../../service/login/api/verify_instance_service.dart'; import '../../customers/ui/customers.dart'; import '../../select_customer/ui/new_select_customer.dart'; import '../../transaction_history/view/transaction_screen.dart'; class ProductListHome extends StatefulWidget { final bool isForNewOrder; final ParkOrder? parkedOrder; const ProductListHome( {super.key, this.isForNewOrder = false, this.parkedOrder}); @override State<ProductListHome> createState() => _ProductListHomeState(); } class _ProductListHomeState extends State<ProductListHome> { final _key = GlobalKey<ExpandableFabState>(); final GlobalKey _focusKey = GlobalKey(); late TextEditingController _searchTxtController; List<Product> products = []; List<Category> categories = []; late String managerName = ''; //bool _isFABOpened = false; ParkOrder? parkOrder; Customer? _selectedCust; final _scrollController = ScrollController(); double _scrollToOffset(int index) { // Calculate the scroll offset for the given index // You'll need to adjust this based on your actual item heights double itemHeight = 250; return itemHeight * index; } void _scrollToIndex(int index) { double offset = _scrollToOffset(index); _scrollController.animateTo(offset, duration: const Duration(seconds: 1), curve: Curves.easeInOutSine); } // Define the fixed height for an item // double _height = 0.0; // void _scrollToIndex(index) { // _scrollController.animateTo(_height * index, // duration: const Duration(seconds: 1), curve: Curves.easeInOutSine); // } @override void initState() { super.initState(); verify(); // _height = MediaQuery.of(context).size.height; _searchTxtController = TextEditingController(); if (widget.parkedOrder != null) { parkOrder = widget.parkedOrder; _selectedCust = widget.parkedOrder!.customer; } if (widget.isForNewOrder && _selectedCust == null) { Future.delayed(Duration.zero, () => goToSelectCustomer()); } _getManagerName(); getProducts(); //throw Exception(); } @override Widget build(BuildContext context) { return SafeArea( child: GestureDetector( onTap: () { final state = _key.currentState; if (state != null) { debugPrint('isOpen:${state.isOpen}'); if (state.isOpen) { state.toggle(); } } }, child: Scaffold( body: ShowCaseWidget( builder: Builder( builder: ((context) => SingleChildScrollView( controller: _scrollController, physics: const BouncingScrollPhysics(), padding: const EdgeInsets.only(left: 10, right: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // SizedBox( // height: MediaQuery.of(context).size.height, // width: MediaQuery.of(context).size.width, // child: ModalBarrier( // dismissible: true, // color: _isModalVisible ? Colors.black.withOpacity(0.5) : Colors.transparent, // ) // ), hightSpacer30, Visibility( visible: !widget.isForNewOrder, child: Stack( //mainAxisSize: MainAxisSize.min, children: [ Align( alignment: Alignment.center, child: Column( children: [ Text(WELCOME_BACK, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, color: MAIN_COLOR, fontWeight: FontWeight.w600, )), hightSpacer5, Text( managerName, style: getTextStyle( fontSize: LARGE_FONT_SIZE, color: DARK_GREY_COLOR), overflow: TextOverflow.ellipsis, ), ], )), /* Align( alignment: Alignment.topRight, child: Stack( children: [ Showcase( key: _focusKey, description: 'Tap here to create the new order', child: IconButton( onPressed: (() async { await Navigator.push( context, MaterialPageRoute( builder: (context) => const ProductListHome( isForNewOrder: true))); setState(() {}); }), icon: SvgPicture.asset( NEW_ORDER_ICON, height: 25, width: 25, ))), ], )),*/ ], )), Visibility( visible: widget.isForNewOrder, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ InkWell( onTap: () => Navigator.pop(context), child: Padding( padding: smallPaddingAll(), child: SvgPicture.asset( BACK_IMAGE, color: BLACK_COLOR, width: 25, ), ), ), Text( _selectedCust != null ? _selectedCust!.name : '', style: getTextStyle( fontSize: LARGE_FONT_SIZE, color: MAIN_COLOR), overflow: TextOverflow.ellipsis, ), Stack( alignment: Alignment.topCenter, children: [ IconButton( onPressed: (() async { if (parkOrder != null && parkOrder!.items.isNotEmpty) { await Navigator.push( context, MaterialPageRoute( builder: (context) => CartScreen( order: parkOrder!))); setState(() {}); } else { Helper.showPopup( context, "Your cart is empty"); } }), icon: SvgPicture.asset( CART_ICON, height: 25, width: 25, ), ), Visibility( visible: parkOrder != null && parkOrder!.items.isNotEmpty, child: Container( padding: const EdgeInsets.all(6), margin: const EdgeInsets.only( left: 20), decoration: const BoxDecoration( shape: BoxShape.circle, color: MAIN_COLOR), child: Text( parkOrder != null ? parkOrder!.items.length .toInt() .toString() : "0", style: getTextStyle( fontSize: SMALL_FONT_SIZE, color: WHITE_COLOR), ))) ]) ], )), hightSpacer15, SearchWidget( onTap: () { final state = _key.currentState; if (state != null) { debugPrint('isOpen:${state.isOpen}'); if (state.isOpen) { state.toggle(); } } }, searchHint: 'Search product / category', searchTextController: _searchTxtController, onTextChanged: ((changedtext) { final state = _key.currentState; if (state != null) { debugPrint('isOpen:${state.isOpen}'); if (state.isOpen) { state.toggle(); } } if (changedtext.length < 3) { getProducts(); // _filterProductsCategories(changedtext); } }), submit: () { if (_searchTxtController.text.length >= 3) { _filterProductsCategories( _searchTxtController.text); } else { getProducts(); } }, ), hightSpacer20, SizedBox( height: 100, child: ListView.builder( physics: const BouncingScrollPhysics(), shrinkWrap: true, scrollDirection: Axis.horizontal, itemCount: categories.length, itemBuilder: (context, position) { return GestureDetector( onTap: (() { final state = _key.currentState; if (state != null) { debugPrint('isOpen:${state.isOpen}'); if (state.isOpen) { state.toggle(); } } _scrollToIndex(position); }), child: Column( mainAxisSize: MainAxisSize.min, children: [ Container( margin: const EdgeInsets.only(left: 5), height: 60, clipBehavior: Clip.antiAliasWithSaveLayer, decoration: const BoxDecoration( shape: BoxShape.circle), child: categories[position] .items .first .productImage .isEmpty ? Image.asset( PIZZA_IMAGE, fit: BoxFit.fill, ) : Image.memory( categories[position] .items .first .productImage, fit: BoxFit.fill, ), ), hightSpacer10, Text( categories[position].name, style: getTextStyle( fontWeight: FontWeight.normal, fontSize: SMALL_PLUS_FONT_SIZE), ) ], )); })), categories.isEmpty ? const Center( child: Text( "No items found", style: TextStyle(fontWeight: FontWeight.bold), )) : _getCategoryItems(), hightSpacer45 ], ))))), floatingActionButtonLocation: ExpandableFab.location, floatingActionButton: Visibility( visible: !widget.isForNewOrder, child: ExpandableFab( key: _key, onOpen: (() { // setState(() { // _isFABOpened = true; // }); }), onClose: (() { // setState(() { // _isFABOpened = false; // }); }), type: ExpandableFabType.up, distance: 80, backgroundColor: LIGHT_BLACK_COLOR, child: SvgPicture.asset( FAB_MAIN_ICON, height: 55, width: 55, ), closeButtonStyle: ExpandableFabCloseButtonStyle( child: SvgPicture.asset( FAB_MAIN_ICON, height: 55, width: 55, )), children: [ SizedBox( height: 70, width: 70, child: FloatingActionButton( heroTag: 'finance', onPressed: (() async { await Navigator.push( context, MaterialPageRoute( builder: (context) => const Finance())); _key.currentState!.toggle(); setState(() {}); }), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8))), backgroundColor: WHITE_COLOR, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( FAB_FINANCE_ICON, color: BLACK_COLOR, height: 25, width: 25, ), hightSpacer5, Text('Finance', style: getTextStyle( fontSize: SMALL_FONT_SIZE, fontWeight: FontWeight.w600)) ], )), ), SizedBox( height: 70, width: 70, child: FloatingActionButton( heroTag: 'account', onPressed: (() async { await Navigator.push( context, MaterialPageRoute( builder: (context) => const MyAccount())); _key.currentState!.toggle(); setState(() {}); }), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8))), backgroundColor: WHITE_COLOR, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( FAB_ACCOUNT_ICON, color: BLACK_COLOR, height: 25, width: 25, ), hightSpacer5, Text('My Profile', textAlign: TextAlign.center, style: getTextStyle( fontSize: SMALL_FONT_SIZE, fontWeight: FontWeight.w600)) ], )), ), SizedBox( height: 70, width: 70, child: FloatingActionButton( heroTag: 'transactions', onPressed: (() async { await Navigator.push( context, MaterialPageRoute( builder: (context) => const TransactionScreen())); _key.currentState!.toggle(); setState(() {}); }), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8))), backgroundColor: WHITE_COLOR, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( FAB_HISTORY_ICON, color: BLACK_COLOR, height: 25, width: 25, ), hightSpacer5, Text('History', textAlign: TextAlign.center, style: getTextStyle( fontSize: SMALL_FONT_SIZE, fontWeight: FontWeight.w600)) ], )), ), SizedBox( height: 70, width: 70, child: FloatingActionButton( heroTag: 'customers', onPressed: (() async { await Navigator.push( context, MaterialPageRoute( builder: (context) => const Customers())); _key.currentState!.toggle(); setState(() {}); }), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8))), backgroundColor: WHITE_COLOR, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( FAB_CUSTOMERS_ICON, color: BLACK_COLOR, height: 25, width: 25, ), hightSpacer5, Text('Customer', style: getTextStyle( fontSize: SMALL_FONT_SIZE, fontWeight: FontWeight.w600)) ], )), ), // SizedBox( // height: 70, // width: 70, // child: FloatingActionButton( // heroTag: 'products', // onPressed: (() { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => const Products())); // }), // shape: const RoundedRectangleBorder( // borderRadius: BorderRadius.all(Radius.circular(8))), // backgroundColor: WHITE_COLOR, // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: [ // SvgPicture.asset( // FAB_PRODUCTS_ICON, // color: BLACK_COLOR, // height: 25, // width: 25, // ), // hightSpacer5, // Text('Product', // style: getTextStyle( // fontSize: SMALL_FONT_SIZE, // fontWeight: FontWeight.normal)) // ], // )), // ), SizedBox( height: 70, width: 70, child: FloatingActionButton( heroTag: 'create order', onPressed: (() async { await Navigator.push( context, MaterialPageRoute( builder: (context) => const ProductListHome( isForNewOrder: true))); _key.currentState!.toggle(); setState(() {}); }), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8))), backgroundColor: WHITE_COLOR, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( FAB_ORDERS_ICON, color: BLACK_COLOR, height: 25, width: 25, ), hightSpacer5, Text('Order', style: getTextStyle( fontSize: SMALL_FONT_SIZE, fontWeight: FontWeight.w600)) ], )), ), // SizedBox( // height: 70, // width: 70, // child: FloatingActionButton( // heroTag: 'home', // onPressed: (() { // _key.currentState!.toggle(); // }), // shape: const RoundedRectangleBorder( // borderRadius: BorderRadius.all(Radius.circular(8))), // backgroundColor: WHITE_COLOR, // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: [ // SvgPicture.asset( // FAB_HOME_ICON, // color: BLACK_COLOR, // height: 25, // width: 25, // ), // hightSpacer5, // Text('Home', // style: getTextStyle( // fontSize: SMALL_FONT_SIZE, // fontWeight: FontWeight.w600)) // ], // )), // ), ], )), ), )); } _getCategoryItems() { return ListView.builder( shrinkWrap: true, primary: false, itemCount: categories.length, itemBuilder: ((context, catPosition) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ hightSpacer20, Text(categories[catPosition].name, style: getTextStyle(fontSize: LARGE_MINUS_FONT_SIZE)), hightSpacer10, GridView.builder( shrinkWrap: true, primary: false, itemCount: categories[catPosition].items.length, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, crossAxisSpacing: 4.0, mainAxisSpacing: 4.0), itemBuilder: ((context, itemPosition) { return GestureDetector( onTap: () { final state = _key.currentState; if (state != null) { debugPrint('isOpen:${state.isOpen}'); if (state.isOpen) { state.toggle(); } } if (widget.isForNewOrder) { if (categories[catPosition] .items[itemPosition] .stock > 0) { var item = OrderItem.fromJson( categories[catPosition] .items[itemPosition] .toJson()); log('Selected Item :: $item'); _openItemDetailDialog(context, item); } else { Helper.showPopup( context, 'Sorry, item is not in stock.'); } } else { Helper.showPopup( context, "Please select customer first"); WidgetsBinding.instance.addPostFrameCallback((_) { ShowCaseWidget.of(context) .startShowCase([_focusKey]); }); setState(() { _scrollController.jumpTo(0); }); } }, child: ColorFiltered( colorFilter: ColorFilter.mode( categories[catPosition] .items[itemPosition] .stock > 0 ? Colors.transparent : Colors.white.withOpacity(0.6), BlendMode.screen), child: Stack( alignment: Alignment.topCenter, children: [ Align( alignment: Alignment.bottomCenter, child: Container( margin: paddingXY(x: 5, y: 5), padding: paddingXY(y: 0, x: 10), width: 145, height: 90, decoration: BoxDecoration( color: MAIN_COLOR.withOpacity(0.04), borderRadius: BorderRadius.circular(10)), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ hightSpacer40, SizedBox( //height: 30, child: Text( categories[catPosition] .items[itemPosition] .name, maxLines: 1, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: getTextStyle( // color: DARK_GREY_COLOR, fontWeight: FontWeight.w500, fontSize: SMALL_PLUS_FONT_SIZE), ), ), hightSpacer4, Text( "$appCurrency ${categories[catPosition].items[itemPosition].price.toStringAsFixed(2)}", textAlign: TextAlign.center, style: getTextStyle( color: MAIN_COLOR, fontSize: SMALL_PLUS_FONT_SIZE), ), ], ), ), ), Container( decoration: BoxDecoration( border: Border.all(color: WHITE_COLOR), shape: BoxShape.circle), child: Container( margin: const EdgeInsets.only( left: 5, right: 5), height: 55, clipBehavior: Clip.antiAliasWithSaveLayer, decoration: const BoxDecoration( shape: BoxShape.circle), child: categories[catPosition] .items[itemPosition] .productImage .isEmpty ? Image.asset(BURGAR_IMAGE) : Image.memory(categories[catPosition] .items[itemPosition] .productImage), )), Container( padding: const EdgeInsets.all(6), margin: const EdgeInsets.only(left: 45), decoration: const BoxDecoration( shape: BoxShape.circle, color: GREEN_COLOR), child: Text( categories[catPosition] .items[itemPosition] .stock .toInt() .toString(), style: getTextStyle( fontSize: SMALL_FONT_SIZE, color: WHITE_COLOR), )) ], ))); })), hightSpacer30 ], ); })); } Future<void> getProducts() async { //Fetching data from DbProduct database // products = await DbProduct().getProducts(); // categories = Category.getCategories(products); categories = await DbCategory().getCategories(); setState(() {}); } void _filterProductsCategories(String searchTxt) { categories = categories .where((element) => element.items.any((element) => element.name.toLowerCase().contains(searchTxt.toLowerCase())) || element.name.toLowerCase().contains(searchTxt.toLowerCase())) .toList(); setState(() {}); } _getManagerName() async { HubManager manager = await DbHubManager().getManager() as HubManager; managerName = manager.name; //profilePic = manager.profileImage; setState(() {}); } verify() async { CommanResponse res = await VerificationUrl.checkAppStatus(); if (res.message == true) { _getManagerName(); getProducts(); } else { Helper.showPopup(context, "Please update your app to latest version", barrierDismissible: true); } } _openItemDetailDialog(BuildContext context, OrderItem product) async { product.orderedPrice = product.price; if (product.orderedQuantity == 0) { product.orderedQuantity = 1; } var res = await showDialog( context: context, builder: (context) { return ItemOptions(orderItem: product); }); if (res == true) { if (parkOrder == null) { HubManager manager = await DbHubManager().getManager() as HubManager; parkOrder = ParkOrder( id: _selectedCust!.id, date: Helper.getCurrentDate(), time: Helper.getCurrentTime(), customer: _selectedCust!, items: [], orderAmount: 0, manager: manager, transactionDateTime: DateTime.now()); } setState(() { if (product.orderedQuantity > 0 && !parkOrder!.items.contains(product)) { OrderItem newItem = product; parkOrder!.items.add(newItem); _calculateOrderAmount(); } else if (product.orderedQuantity == 0) { parkOrder!.items.remove(product); _calculateOrderAmount(); } }); // DbParkedOrder().saveOrder(parkOrder!); } return res; } void _calculateOrderAmount() { double amount = 0; for (var item in parkOrder!.items) { amount += item.orderedPrice * item.orderedQuantity; } parkOrder!.orderAmount = amount; } void goToSelectCustomer() async { var data = await Navigator.push(context, MaterialPageRoute(builder: (context) => const NewSelectCustomer())); if (data != null) { getProducts(); setState(() { _selectedCust = data; }); } else { if (!mounted) return; Navigator.pop(context); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/splash
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/splash/view/splash_screen.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:nb_posx/core/mobile/login/ui/login.dart'; import 'package:nb_posx/utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../main.dart'; import '../../home/ui/product_list_home.dart'; class SplashScreen extends StatefulWidget { const SplashScreen({super.key}); @override State<SplashScreen> createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> { @override void initState() { super.initState(); Timer( const Duration(seconds: 3), (() => Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => isUserLoggedIn ? ProductListHome() : const Login())))); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( backgroundColor: MAIN_COLOR, body: Padding( padding: const EdgeInsets.only(left: 15, right: 15), child: Stack( children: [ Center( child: Image.asset( APP_ICON, width: 200, height: 200, )), const SizedBox(height: 15), Padding( padding: const EdgeInsets.only(bottom: 30), child: Align( alignment: Alignment.bottomCenter, child: Text( POWERED_BY_TXT, style: getTextStyle(color: WHITE_COLOR, fontSize: 16.0), ))) ], ), ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/customers
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/customers/ui/customers.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:nb_posx/core/service/customer/api/customer_api_service.dart'; import 'package:nb_posx/network/api_helper/comman_response.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../database/db_utils/db_customer.dart'; import '../../../../../database/models/customer.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../widgets/custom_appbar.dart'; import '../../../../../widgets/customer_tile.dart'; import '../../../../../widgets/search_widget.dart'; import '../../../../../widgets/shimmer_widget.dart'; class Customers extends StatefulWidget { const Customers({Key? key}) : super(key: key); @override State<Customers> createState() => _CustomersState(); } class _CustomersState extends State<Customers> { List<Customer> customers = []; late TextEditingController searchCustomerController; bool isCustomersFound = true; @override void initState() { super.initState(); searchCustomerController = TextEditingController(); getCustomersFromDB(0); } @override void dispose() { searchCustomerController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( // endDrawer: MainDrawer( // menuItem: Helper.getMenuItemList(context), // ), body: SafeArea( child: SingleChildScrollView( child: Column( children: [ const CustomAppbar(title: CUSTOMERS_TXT, hideSidemenu: true), hightSpacer30, Padding( padding: horizontalSpace(), child: SearchWidget( searchHint: SEARCH_HINT_TXT, searchTextController: searchCustomerController, keyboardType: TextInputType.phone, inputFormatters: [FilteringTextInputFormatter.digitsOnly,LengthLimitingTextInputFormatter(12)], onTextChanged: (text) { (text) { if (text.length > 10) { searchCustomerController.text = text.substring(0, 10); searchCustomerController.selection = TextSelection.fromPosition( TextPosition(offset: searchCustomerController.text.length), ); } }; if (text.isNotEmpty) { filterCustomerData(text); } else { getCustomersFromDB(0); } }, onSubmit: (text) { if (text.isNotEmpty) { filterCustomerData(text); } else { getCustomersFromDB(0); } }, ), ), hightSpacer15, isCustomersFound ? ListView.builder( shrinkWrap: true, itemCount: customers.isEmpty ? 10 : customers.length, primary: false, itemBuilder: (context, position) { if (customers.isEmpty) { return const ShimmerWidget(); } else { return CustomerTile( isCheckBoxEnabled: false, isDeleteButtonEnabled: false, customer: customers[position], isSubtitle: true, isHighlighted: true, ); } }) : Center( child: Text( NO_DATA_FOUND, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.bold, ), )), // Visibility( // visible: isCustomersFound, // child: ListView.builder( // shrinkWrap: true, // itemCount: customers.isEmpty ? 10 : customers.length, // primary: false, // itemBuilder: (context, position) { // if (customers.isEmpty) { // return const ShimmerWidget(); // } else { // return CustomerTile( // isCheckBoxEnabled: false, // isDeleteButtonEnabled: false, // customer: customers[position], // isSubtitle: true, // ); // } // })), // Visibility( // visible: !isCustomersFound, // child: Center( // child: Text( // NO_DATA_FOUND, // style: getTextStyle( // fontSize: SMALL_PLUS_FONT_SIZE, // fontWeight: FontWeight.w600, // ), // ))), ], ), ), ), ); } ///Function to get the customer data from api ///If not available from api then load from local database Future<void> getCustomersFromDB(val) async { //Fetch the data from local database customers = await DbCustomer().getCustomers(); isCustomersFound = customers.isNotEmpty; if (val == 0) setState(() {}); } void filterCustomerData(String searchText) async { await getCustomersFromDB(1); customers = customers .where((element) => //element.name.toLowerCase().contains(searchText.toLowerCase()) || element.phone.toLowerCase().contains(searchText.toLowerCase())) .toList(); isCustomersFound = customers.isNotEmpty; if (!isCustomersFound) { CommanResponse response = await CustomerService().getCustomers(searchTxt: searchText); } setState(() {}); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/change_password
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/change_password/ui/password_updated.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/button.dart'; class PasswordUpdated extends StatefulWidget { const PasswordUpdated({Key? key}) : super(key: key); @override State<PasswordUpdated> createState() => _PasswordUpdatedState(); } class _PasswordUpdatedState extends State<PasswordUpdated> { late TextEditingController _newPassCtrl, _confirmPassCtrl; @override void initState() { super.initState(); _newPassCtrl = TextEditingController(); _confirmPassCtrl = TextEditingController(); } @override void dispose() { _newPassCtrl.dispose(); _confirmPassCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { Widget passwordUpdatedBtnWidget = SizedBox( width: 300, child: ButtonWidget( onPressed: () { Navigator.of(context).popUntil((route) => route.isFirst); }, title: PASSWORD_UPDATED_BTN_TXT, colorBG: MAIN_COLOR, width: 350, //width: MediaQuery.of(context).size.width / 2.5, ), ); return Scaffold( body: SingleChildScrollView( child: Column( children: [ hightSpacer50, hightSpacer50, hightSpacer50, Image.asset(APP_ICON, width: 100, height: 100), hightSpacer50, // appLogo, hightSpacer50, Center( child: Text( PASSWORD_UPDATED_TITLE.toUpperCase(), style: getTextStyle( color: MAIN_COLOR, fontWeight: FontWeight.bold, fontSize: LARGE_FONT_SIZE), ), ), hightSpacer50, Center( child: SvgPicture.asset( SUCCESS_IMAGE, height: 120, width: 100, fit: BoxFit.contain, ), ), hightSpacer40, Center( child: Text( PASSWORD_UPDATED_MSG, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w400), ), ), hightSpacer40, passwordUpdatedBtnWidget, ], ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/change_password
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/change_password/ui/change_password.dart
import 'package:flutter/material.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../network/api_helper/comman_response.dart'; import '../../../../utils/helper.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../utils/ui_utils/textfield_border_decoration.dart'; import '../../../../widgets/button.dart'; import '../../../../widgets/custom_appbar.dart'; import '../../../../widgets/text_field_widget.dart'; import '../../../service/change_password/api/change_hubmanager_password.dart'; import 'password_updated.dart'; class ChangePassword extends StatefulWidget { final bool verifiedOtp; const ChangePassword({Key? key, this.verifiedOtp = false}) : super(key: key); @override State<ChangePassword> createState() => _ChangePasswordState(); } class _ChangePasswordState extends State<ChangePassword> { late TextEditingController _newPassCtrl, _confirmPassCtrl; @override void initState() { super.initState(); _newPassCtrl = TextEditingController(); _confirmPassCtrl = TextEditingController(); } @override void dispose() { _newPassCtrl.dispose(); _confirmPassCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { /// change pass btn widget Widget changePasswordBtnWidget = Center( child: ButtonWidget( onPressed: () async { await _handleChangePassBtnAction(); }, title: CHANGE_PASSWORD_BTN_TXT, colorBG: MAIN_COLOR, width: MediaQuery.of(context).size.width, ), ); /// main area return Scaffold( body: SingleChildScrollView( child: Column( children: [ hightSpacer40, const CustomAppbar( title: "", backBtnColor: BLACK_COLOR, hideSidemenu: true, ), hightSpacer20, Image.asset(APP_ICON, width: 100, height: 100), hightSpacer20, hightSpacer50, // appLogo, hightSpacer50, Center( child: Text( CHANGE_PASSWORD_TITLE.toUpperCase(), style: getTextStyle( fontWeight: FontWeight.bold, color: MAIN_COLOR, fontSize: LARGE_FONT_SIZE), ), ), hightSpacer5, widget.verifiedOtp ? Center( child: Text( CHANGE_PASSWORD_OTP_VERIFY_MSG, style: getTextStyle( color: WHITE_COLOR, fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ), ) : Container(), Center( child: Text( CHANGE_PASSWORD_SET_MSG, style: getTextStyle( color: WHITE_COLOR, fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), ), ), hightSpacer45, Container( margin: horizontalSpace(), padding: smallPaddingAll(), child: TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _newPassCtrl, hintText: CHANGE_NEW_PASSWORD_HINT, password: true, ), ), hightSpacer20, Container( margin: horizontalSpace(), padding: smallPaddingAll(), child: TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: _confirmPassCtrl, hintText: CHANGE_CONFIRM_PASSWORD_HINT, password: true, ), ), hightSpacer32, changePasswordBtnWidget, ], ), ), ); } /// change password btn click Future<void> _handleChangePassBtnAction() async { String newPass = _newPassCtrl.text.trim(); String confirmPass = _confirmPassCtrl.text.trim(); if (newPass.isEmpty || confirmPass.isEmpty) { Helper.showPopup(context, "Please enter password"); } else { if (newPass.isNotEmpty && confirmPass.isNotEmpty && newPass == confirmPass) { CommanResponse response = await ChangeHubManagerPassword().changePassword(newPass); if (response.status!) { if (!mounted) return; Navigator.push(context, MaterialPageRoute(builder: (context) => const PasswordUpdated())); } else { if (!mounted) return; Helper.showPopup(context, response.message); } } else if (newPass != confirmPass) { Helper.showPopup(context, passwordMismatch); } else { Helper.showPopup(context, invalidPasswordMsg); } } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order/bloc/createorderbloc_bloc.dart
// import 'package:nb_pos/database/models/customer.dart'; // import 'package:nb_pos/database/models/product.dart'; // import 'package:bloc/bloc.dart'; // import 'package:equatable/equatable.dart'; // part 'createorderbloc_event.dart'; // part 'createorderbloc_state.dart'; // class CreateOrderBloc extends Bloc<CreateOrderEvent, CreateOrderState> { // CreateOrderBloc() : super(CreateOrderInitialState()) { // on<CreateOrderEvent>((event, emit) {}); // on<CreateOrderInitialEvent>( // (event, emit) => emit(CreateOrderInitialState())); // on<CreateOrderLoadingEvent>( // (event, emit) => emit(CreateOrderLoadingState())); // on<CreateOrderSelectCustomerEvent>( // (event, emit) => emit(CreateOrderSelectCustomerState())); // on<CreateOrderCustomerSelectedEvent>( // (event, emit) => emit(CreateOrderCustomerSelectedState())); // on<CreateOrderAddProductsEvent>( // (event, emit) => emit(CreateOrderAddProductsState())); // on<CreateOrderProductsAddedEvent>( // (event, emit) => emit(CreateOrderProductsAddedState())); // on<CreateOrderCheckoutEvent>( // (event, emit) => emit(CreateOrderCheckoutState())); // on<CreateOrderSelectCustomerErrorEvent>( // (event, emit) => emit(CreateOrderSelectCustomerErrorState())); // on<CreateOrderSelectProductsErrorEvent>( // (event, emit) => emit(CreateOrderSelectProductsErrorState())); // on<CreateOrderSelectedCustomerDeletedEvent>( // (event, emit) => emit(CreateOrderSelectedCustomerDeletedState())); // on<CreateOrderSelectedProductDeletedEvent>( // (event, emit) => emit(CreateOrderSelectedProductDeletedState())); // on<CreateOrderAddProductInCartEvent>((event, emit) async { // Product productData = event.product; // List<Product> orderedProducts = event.orders; // if (productData.orderedQuantity + 1 <= productData.stock) { // if (orderedProducts.any((element) => element.id == productData.id)) { // int indexOfProduct = orderedProducts // .indexWhere((element) => element.id == productData.id); // Product tempProduct = orderedProducts.elementAt(indexOfProduct); // productData.orderedQuantity = tempProduct.orderedQuantity + 1; // orderedProducts.removeAt(indexOfProduct); // orderedProducts.insert(indexOfProduct, productData); // } else { // productData.orderedQuantity = productData.orderedQuantity + 1; // orderedProducts.add(productData); // } // emit(CreateOrderAddProductSuccessState(orderedProducts)); // } else { // emit(CreateOrderInSufficientStockState()); // } // }); // on<CreateOrderRemoveProductFromCartEvent>((event, emit) async { // Product productData = event.product; // List<Product> orderedProducts = event.orders; // if (orderedProducts.any((element) => element.id == productData.id)) { // productData.orderedQuantity = productData.orderedQuantity - 1; // } // if (productData.orderedQuantity == 0) { // orderedProducts.removeWhere((element) => element.id == productData.id); // } // emit(CreateOrderRemoveProductFromCartState(orderedProducts)); // }); // on<CreateOrderDeleteProductFromCartEvent>((event, emit) async { // final Product product = event.product; // final List<Product> orderedProducts = event.orders; // product.orderedQuantity = 0; // orderedProducts.removeWhere((element) => element.id == product.id); // emit(CreateOrderDeleteProductFromCartState(orderedProducts)); // }); // on<CreateOrderProceedToCheckoutEvent>((event, emit) { // Customer? customer = event.customer; // List<Product> orders = event.orders; // if (customer != null) { // if (orders.isNotEmpty) { // emit(CreateOrderCheckoutState()); // } else { // emit(CreateOrderSelectProductsErrorState()); // } // } else { // emit(CreateOrderSelectCustomerErrorState()); // } // emit(CreateOrderProceedToCheckoutState()); // }); // on<CreateOrderAddMoreProductsEvent>( // (event, emit) => emit(CreateOrderAddMoreProductsState())); // on<CreateOrderChangeCustomerEvent>( // (event, emit) => emit(CreateOrderChangeCustomerState())); // on<CreateOrderDeleteSelectedCustomerEvent>((event, emit) async { // emit(CreateOrderDeleteSelectedCustomerState()); // }); // } // }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order/bloc/createorderbloc_event.dart
// part of 'createorderbloc_bloc.dart'; // abstract class CreateOrderEvent extends Equatable { // CreateOrderEvent(); // @override // List<Object> get props => []; // } // ///Create Order Initial Event // class CreateOrderInitialEvent extends CreateOrderEvent { // CreateOrderInitialEvent(); // @override // List<Object> get props => []; // } // ///Create Order Select Customer Event // class CreateOrderSelectCustomerEvent extends CreateOrderEvent { // CreateOrderSelectCustomerEvent(); // @override // List<Object> get props => []; // } // ///Create Order Add Product Event // class CreateOrderAddProductsEvent extends CreateOrderEvent { // CreateOrderAddProductsEvent(); // @override // List<Object> get props => []; // } // ///Create Order Checkout Event // class CreateOrderCheckoutEvent extends CreateOrderEvent { // CreateOrderCheckoutEvent(); // @override // List<Object> get props => []; // } // ///Create Order Customer Selected Event // class CreateOrderCustomerSelectedEvent extends CreateOrderEvent { // CreateOrderCustomerSelectedEvent(); // @override // List<Object> get props => []; // } // ///Create Order Checkout Event // class CreateOrderProductsAddedEvent extends CreateOrderEvent { // CreateOrderProductsAddedEvent(); // @override // List<Object> get props => []; // } // ///Create Order Checkout Event // class CreateOrderLoadingEvent extends CreateOrderEvent { // CreateOrderLoadingEvent(); // @override // List<Object> get props => []; // } // ///Create Order Select Customer Error Event // class CreateOrderSelectCustomerErrorEvent extends CreateOrderEvent { // CreateOrderSelectCustomerErrorEvent(); // @override // List<Object> get props => []; // } // ///Create Order Select Product Error Event // class CreateOrderSelectProductsErrorEvent extends CreateOrderEvent { // CreateOrderSelectProductsErrorEvent(); // @override // List<Object> get props => []; // } // ///Create Order Selected Customer Delete Event // class CreateOrderSelectedCustomerDeletedEvent extends CreateOrderEvent { // CreateOrderSelectedCustomerDeletedEvent(); // @override // List<Object> get props => []; // } // ///Create Order Selected Product Delete Event // class CreateOrderSelectedProductDeletedEvent extends CreateOrderEvent { // CreateOrderSelectedProductDeletedEvent(); // @override // List<Object> get props => []; // } // ///Create Order Add Product In Cart Event // class CreateOrderAddProductInCartEvent extends CreateOrderEvent { // final Product product; // final List<Product> orders; // CreateOrderAddProductInCartEvent(this.product, this.orders); // @override // List<Object> get props => [product, orders]; // } // ///Create Order Remove Product From Cart Event // class CreateOrderRemoveProductFromCartEvent extends CreateOrderEvent { // final Product product; // final List<Product> orders; // CreateOrderRemoveProductFromCartEvent(this.product, this.orders); // @override // List<Object> get props => [product, orders]; // } // ///Create Order Delete Product From Cart Event // class CreateOrderDeleteProductFromCartEvent extends CreateOrderEvent { // final Product product; // final List<Product> orders; // CreateOrderDeleteProductFromCartEvent(this.product, this.orders); // @override // List<Object> get props => [product, orders]; // } // ///Create Order Proceed to Checkout Event // class CreateOrderProceedToCheckoutEvent extends CreateOrderEvent { // final Customer? customer; // final List<Product> orders; // CreateOrderProceedToCheckoutEvent(this.customer, this.orders); // @override // List<Object> get props => [customer!, orders]; // } // ///Create Order Add More Product Event // class CreateOrderAddMoreProductsEvent extends CreateOrderEvent { // CreateOrderAddMoreProductsEvent(); // @override // List<Object> get props => []; // } // ///Create Order Change Customer Event // class CreateOrderChangeCustomerEvent extends CreateOrderEvent { // CreateOrderChangeCustomerEvent(); // @override // List<Object> get props => []; // } // ///Create Order Delete Selected Customer Event // class CreateOrderDeleteSelectedCustomerEvent extends CreateOrderEvent { // CreateOrderDeleteSelectedCustomerEvent(); // @override // List<Object> get props => []; // } // ///Create Order Add Product Success Event // class CreateOrderAddProductSuccessEvent extends CreateOrderEvent { // CreateOrderAddProductSuccessEvent(); // @override // List<Object> get props => []; // } // ///Create Order Insufficient Stock Event // class CreateOrderInSufficientStockEvent extends CreateOrderEvent { // CreateOrderInSufficientStockEvent(); // @override // List<Object> get props => []; // }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order/bloc/createorderbloc_state.dart
// part of 'createorderbloc_bloc.dart'; // abstract class CreateOrderState extends Equatable { // CreateOrderState(); // } // ///Create Order Initial State // class CreateOrderInitialState extends CreateOrderState { // CreateOrderInitialState(); // @override // List<Object> get props => []; // } // ///Create Order Select Customer State // class CreateOrderSelectCustomerState extends CreateOrderState { // CreateOrderSelectCustomerState(); // @override // List<Object> get props => []; // } // ///Create Order Add Product State // class CreateOrderAddProductsState extends CreateOrderState { // CreateOrderAddProductsState(); // @override // List<Object> get props => []; // } // ///Create Order Checkout State // class CreateOrderCheckoutState extends CreateOrderState { // CreateOrderCheckoutState(); // @override // List<Object> get props => []; // } // ///Create Order Customer Selected State // class CreateOrderCustomerSelectedState extends CreateOrderState { // CreateOrderCustomerSelectedState(); // @override // List<Object> get props => []; // } // ///Create Order Checkout State // class CreateOrderProductsAddedState extends CreateOrderState { // CreateOrderProductsAddedState(); // @override // List<Object> get props => []; // } // ///Create Order Checkout State // class CreateOrderLoadingState extends CreateOrderState { // CreateOrderLoadingState(); // @override // List<Object> get props => []; // } // ///Create Order Select Customer Error State // class CreateOrderSelectCustomerErrorState extends CreateOrderState { // CreateOrderSelectCustomerErrorState(); // @override // List<Object> get props => []; // } // ///Create Order Select Product Error State // class CreateOrderSelectProductsErrorState extends CreateOrderState { // CreateOrderSelectProductsErrorState(); // @override // List<Object> get props => []; // } // ///Create Order Selected Customer Delete State // class CreateOrderSelectedCustomerDeletedState extends CreateOrderState { // CreateOrderSelectedCustomerDeletedState(); // @override // List<Object> get props => []; // } // ///Create Order Selected Product Delete State // class CreateOrderSelectedProductDeletedState extends CreateOrderState { // CreateOrderSelectedProductDeletedState(); // @override // List<Object> get props => []; // } // ///Create Order Add Product In Cart State // class CreateOrderAddProductInCartState extends CreateOrderState { // CreateOrderAddProductInCartState(); // @override // List<Object> get props => []; // } // ///Create Order Remove Product From Cart State // class CreateOrderRemoveProductFromCartState extends CreateOrderState { // final List<Product> orders; // CreateOrderRemoveProductFromCartState(this.orders); // @override // List<Object> get props => [orders]; // } // ///Create Order Delete Product From Cart State // class CreateOrderDeleteProductFromCartState extends CreateOrderState { // final List<Product> orders; // CreateOrderDeleteProductFromCartState(this.orders); // @override // List<Object> get props => [orders]; // } // ///Create Order Proceed to Checkout State // class CreateOrderProceedToCheckoutState extends CreateOrderState { // CreateOrderProceedToCheckoutState(); // @override // List<Object> get props => []; // } // ///Create Order Add More Product State // class CreateOrderAddMoreProductsState extends CreateOrderState { // CreateOrderAddMoreProductsState(); // @override // List<Object> get props => []; // } // ///Create Order Change Customer State // class CreateOrderChangeCustomerState extends CreateOrderState { // CreateOrderChangeCustomerState(); // @override // List<Object> get props => []; // } // ///Create Order Delete Selected Customer State // class CreateOrderDeleteSelectedCustomerState extends CreateOrderState { // CreateOrderDeleteSelectedCustomerState(); // @override // List<Object> get props => []; // } // ///Create Order Add Product Success State // class CreateOrderAddProductSuccessState extends CreateOrderState { // final List<Product> orders; // CreateOrderAddProductSuccessState(this.orders); // @override // List<Object> get props => [orders]; // } // ///Create Order Insufficient Stock State // class CreateOrderInSufficientStockState extends CreateOrderState { // CreateOrderInSufficientStockState(); // @override // List<Object> get props => []; // }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order/ui/create_order.dart
// import 'package:nb_pos/constants/app_constants.dart'; // import 'package:nb_pos/core/add_products/ui/add_products_screen.dart'; // import 'package:nb_pos/core/add_products/ui/added_products_widget.dart'; // import 'package:nb_pos/core/checkout/ui/checkout_screen.dart'; // import 'package:nb_pos/core/create_order/bloc/createorderbloc_bloc.dart'; // import 'package:nb_pos/core/create_order/ui/create_order_options.dart'; // import 'package:nb_pos/core/select_customer/ui/select_customer.dart'; // import 'package:nb_pos/core/select_customer/ui/selected_customer_widget.dart'; // import 'package:nb_pos/database/models/customer.dart'; // import 'package:nb_pos/database/models/product.dart'; // import 'package:nb_pos/utils/helper.dart'; // import 'package:nb_pos/widgets/custom_appbar.dart'; // import 'package:nb_pos/widgets/long_button_widget.dart'; // import 'package:flutter/material.dart'; // import 'package:flutter_bloc/flutter_bloc.dart'; // class CreateOrderScreen extends StatefulWidget { // const CreateOrderScreen({Key? key}) : super(key: key); // @override // _CreateOrderScreenState createState() => _CreateOrderScreenState(); // } // class _CreateOrderScreenState extends State<CreateOrderScreen> { // //Customer to store the selected customer // Customer? selectedCustomer; // //List to store the ordered products // List<Product> orderedProducts = []; // //Order total amount // double totalAmount = 0.0; // //Total ordered items count // int totalItems = 0; // //CreateOrder bloc // late CreateOrderBloc _createOrderBloc; // @override // void initState() { // super.initState(); // //initializing object of CreateOrderBloc // _createOrderBloc = CreateOrderBloc(); // //Adding initial event into bloc // _createOrderBloc.add(CreateOrderInitialEvent()); // } // @override // Widget build(BuildContext context) { // return Scaffold( // body: SafeArea( // child: BlocProvider.value( // value: _createOrderBloc, // child: BlocListener<CreateOrderBloc, CreateOrderState>( // listener: (context, state) async { // //show SnackBar messages, popups, navigator etc here... // //State when select customer // if (state is CreateOrderSelectCustomerState) { // //Navigator to move on Select Customer Screen // var data = await Navigator.push( // context, // MaterialPageRoute( // builder: (context) => const SelectCustomerScreenOld())); // if (data != null) { // selectedCustomer = data; // _createOrderBloc.add(CreateOrderCustomerSelectedEvent()); // } else { // _createOrderBloc.add(CreateOrderInitialEvent()); // } // } // //State for Add Products in Cart // else if (state is CreateOrderAddProductsState) { // //Navigator to move on Add Products Screen // var orders = await Navigator.push( // context, // MaterialPageRoute( // builder: (context) => AddProductsScreen( // orderedProducts: orderedProducts, // ))); // if (orders != null) { // orderedProducts = orders; // _createOrderBloc.add(CreateOrderProductsAddedEvent()); // } else { // _createOrderBloc.add(CreateOrderInitialEvent()); // } // } // //State for showing error for selecting the customer if not selected // else if (state is CreateOrderSelectCustomerErrorState) { // //If user press on Proceed button and customer is not selected then show error // Helper.showSnackBar(context, SELECT_CUSTOMER_ERROR); // _createOrderBloc.add(CreateOrderInitialEvent()); // } // //State for showing error for selecting the customer if not selected // else if (state is CreateOrderSelectProductsErrorState) { // //If user press on Proceed button and products is not added in cart then show error // Helper.showSnackBar(context, SELECT_PRODUCT_ERROR); // _createOrderBloc.add(CreateOrderInitialEvent()); // } // //State for Changing the customer // else if (state is CreateOrderChangeCustomerState) { // //Navigator to move on Select Customer Screen // var data = await Navigator.push( // context, // MaterialPageRoute( // builder: (context) => const SelectCustomerScreenOld())); // if (data != null) { // selectedCustomer = data; // _createOrderBloc.add(CreateOrderCustomerSelectedEvent()); // } else { // _createOrderBloc.add(CreateOrderInitialEvent()); // } // } // //State to add more products in cart // else if (state is CreateOrderAddMoreProductsState) { // //Navigator to move on Add Products Screen // var orders = await Navigator.push( // context, // MaterialPageRoute( // builder: (context) => AddProductsScreen( // orderedProducts: orderedProducts, // ))); // if (orders != null) { // orderedProducts = orders; // _createOrderBloc.add(CreateOrderProductsAddedEvent()); // } else { // _createOrderBloc.add(CreateOrderInitialEvent()); // } // } // //State to show error when insufficient stock // else if (state is CreateOrderInSufficientStockState) { // Helper.showSnackBar(context, INSUFFICIENT_STOCK_ERROR); // _createOrderBloc.add(CreateOrderInitialEvent()); // } // //State to do successful checkout // else if (state is CreateOrderCheckoutState) { // //Navigator to move on Checkout Screen // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => CheckoutScreen( // selectedCustomer: selectedCustomer, // orderedProducts: orderedProducts, // ))); // _createOrderBloc.add(CreateOrderInitialEvent()); // } // }, // child: BlocBuilder<CreateOrderBloc, CreateOrderState>( // builder: (context, state) { // //Initial State // if (state is CreateOrderInitialState) { // totalAmount = Helper().getTotal(orderedProducts); // totalItems = orderedProducts.length; // return loadUI(context, orderedProducts); // } // //Loading state // else if (state is CreateOrderLoadingState) { // //Return Loading UI from here... // return Container(); // } // //Customer selected state // else if (state is CreateOrderCustomerSelectedState) { // return loadUI(context, orderedProducts); // } // //Products added in Cart, when navigator comes back from Add Products screen // else if (state is CreateOrderProductsAddedState) { // return loadUI(context, orderedProducts); // } // //State when products is added in Cart by +1 // else if (state is CreateOrderAddProductSuccessState) { // orderedProducts = state.orders; // _createOrderBloc.add(CreateOrderInitialEvent()); // return loadUI(context, state.orders); // } // //State when product is removed from cart by -1 // else if (state is CreateOrderRemoveProductFromCartState) { // orderedProducts = state.orders; // _createOrderBloc.add(CreateOrderInitialEvent()); // return loadUI(context, state.orders); // } // //State when product is deleted from the cart with all the added quantities // else if (state is CreateOrderDeleteProductFromCartState) { // orderedProducts = state.orders; // _createOrderBloc.add(CreateOrderInitialEvent()); // return loadUI(context, state.orders); // } // //State when selected customer is deleted // else if (state is CreateOrderDeleteSelectedCustomerState) { // selectedCustomer = null; // _createOrderBloc.add(CreateOrderInitialEvent()); // return loadUI(context, orderedProducts); // } // //When no state is matched, then blank screen // //(WARNING : FOR DEBUGGING PURPOSE ONLY) // else { // return Container(); // } // }, // ), // ), // ), // ), // bottomNavigationBar: BlocBuilder<CreateOrderBloc, CreateOrderState>( // bloc: _createOrderBloc, // builder: (context, state) { // totalAmount = Helper().getTotal(orderedProducts); // totalItems = orderedProducts.length; // String bottomButtonText = // selectedCustomer == null && orderedProducts.isEmpty // ? PROCEED_TO_NXT_TXT // : CHECKOUT_TXT; // //Bottom Widget for showing items count, item total and proceed button // return LongButton( // buttonTitle: bottomButtonText, // isAmountAndItemsVisible: true, // totalAmount: '$totalAmount', // totalItems: '$totalItems', // onTap: () => _createOrderBloc.add( // CreateOrderProceedToCheckoutEvent( // selectedCustomer, orderedProducts))); // }), // ); // } // ///Function to load the UI for Create Order Screen // Widget loadUI(BuildContext context, List<Product> orderedProducts) { // return SingleChildScrollView( // child: Column( // children: [ // const CustomAppbar(title: CREATE_ORDER_TXT), // Visibility( // visible: selectedCustomer == null, // child: CreateOrderOptions( // tileTile: SELECT_CUSTOMER_TXT, // onTap: () => // _createOrderBloc.add(CreateOrderSelectCustomerEvent()), // )), // Visibility( // visible: selectedCustomer != null, // child: SelectedCustomerWidget( // selectedCustomer: selectedCustomer, // onDelete: () => _createOrderBloc // .add(CreateOrderDeleteSelectedCustomerEvent()), // onTapChangeCustomer: () => // _createOrderBloc.add(CreateOrderChangeCustomerEvent()), // )), // Visibility( // visible: orderedProducts.isEmpty, // child: CreateOrderOptions( // tileTile: ADD_PRODUCT_TXT, // onTap: () => // _createOrderBloc.add(CreateOrderAddProductsEvent()))), // Visibility( // visible: orderedProducts.isNotEmpty, // child: AddProductsWidget( // orderedProducts: orderedProducts, // onDelete: (product) => _createOrderBloc.add( // CreateOrderDeleteProductFromCartEvent( // product, orderedProducts)), // onItemAdd: (product) => _createOrderBloc.add( // CreateOrderAddProductInCartEvent(product, orderedProducts)), // onItemRemove: (product) => _createOrderBloc.add( // CreateOrderRemoveProductFromCartEvent( // product, orderedProducts)), // onAddMoreProducts: () => // _createOrderBloc.add(CreateOrderAddProductsEvent()), // )), // ], // ), // ); // } // }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/create_order/ui/create_order_options.dart
import 'package:flutter/material.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../utils/ui_utils/card_border_shape.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class CreateOrderOptions extends StatefulWidget { final String tileTile; Function? onTap; CreateOrderOptions({Key? key, required this.tileTile, required this.onTap}) : super(key: key); @override State<CreateOrderOptions> createState() => _CreateOrderOptionsState(); } class _CreateOrderOptionsState extends State<CreateOrderOptions> { @override Widget build(BuildContext context) { return Padding( padding: horizontalSpace(), child: Card( shape: cardBorderShape(), child: ListTile( title: Text( widget.tileTile, style: getTextStyle( fontWeight: FontWeight.w600, fontSize: MEDIUM_PLUS_FONT_SIZE, ), ), trailing: const Icon(Icons.arrow_forward_ios_rounded, color: BLACK_COLOR, size: 15), onTap: () => widget.onTap!(), ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/finance
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/finance/ui/finance.dart
import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../database/db_utils/db_hub_manager.dart'; import '../../../../../database/models/hub_manager.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../widgets/custom_appbar.dart'; import 'package:flutter/material.dart'; import '../../../../../utils/helper.dart'; import '../../../service/finance/api/get_updated_account_details.dart'; class Finance extends StatefulWidget { const Finance({Key? key}) : super(key: key); @override State<Finance> createState() => _FinanceState(); } class _FinanceState extends State<Finance> { late String cashCollected; @override void initState() { super.initState(); cashCollected = "00.00"; _initView(); } _initView() async { if (await Helper.isNetworkAvailable()) { // print("INTERNET AVAILABLE"); Helper.showLoaderDialog(context); await UpdatedHubManagerDetails().getUpdatedAccountDetails(); if (!mounted) return; Helper.hideLoader(context); _getcashCollected(); } else { // print("INTERNET NOT AVAILABLE"); _getcashCollected(); } } _getcashCollected() async { HubManager manager = await DbHubManager().getManager() as HubManager; cashCollected = Helper().formatCurrency(manager.cashBalance); setState(() {}); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: SingleChildScrollView( child: Column( children: [ const CustomAppbar(title: FINANCE_TITLE, hideSidemenu: true), hightSpacer30, Padding( padding: leftSpace(), child: Row( children: [ Text( CASH_BALANCE_TXT, style: getTextStyle( fontWeight: FontWeight.w500, fontSize: MEDIUM_FONT_SIZE, color: DARK_GREY_COLOR), ), ], ), ), hightSpacer10, Padding( padding: const EdgeInsets.only( left: FINANCE_PADDING_LEFT, bottom: FINANCE_PADDING_BOTTOM), child: Row( children: [ Text( "$appCurrency $cashCollected", style: getTextStyle( fontWeight: FontWeight.bold, fontSize: LARGE_PLUS_FONT_SIZE, color: MAIN_COLOR), ), ], ), ), ], ), ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/products
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/products/ui/products.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../database/db_utils/db_categories.dart'; import '../../../../database/models/category.dart'; import '../../../../database/models/product.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../widgets/custom_appbar.dart'; import '../../../../widgets/product_shimmer_widget.dart'; import '../../../../widgets/product_widget.dart'; import '../../../../widgets/search_widget.dart'; import '../../create_order_new/ui/widget/category_item.dart'; class Products extends StatefulWidget { const Products({Key? key}) : super(key: key); @override State<Products> createState() => _ProductsState(); } class _ProductsState extends State<Products> { List<Product> products = []; List<Category> categories = []; late TextEditingController searchProductCtrl; bool isProductGridEnable = true; @override void initState() { super.initState(); searchProductCtrl = TextEditingController(); getProducts(); // ProductsService().getCategoryProduct(); } @override void dispose() { searchProductCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( // endDrawer: MainDrawer( // menuItem: Helper.getMenuItemList(context), // ), body: SafeArea( child: SingleChildScrollView( physics: categories.isEmpty ? const NeverScrollableScrollPhysics() : const ScrollPhysics(), child: Column( children: [ const CustomAppbar(title: PRODUCTS_TXT), hightSpacer15, Padding( padding: horizontalSpace(), child: SearchWidget( searchHint: SEARCH_PRODUCT_TXT, searchTextController: searchProductCtrl, onTextChanged: (text) { if (text.isNotEmpty) { debugPrint("entered text1: $text"); } }, onSubmit: (text) { if (text.isNotEmpty) { debugPrint("entered text2: $text"); } }, ), ), hightSpacer15, isProductGridEnable ? productGrid() : productCategoryList(), ], ), ), ), ); } Widget productCategoryList() { return ListView.separated( separatorBuilder: (context, index) { return const Divider( thickness: 1, ); }, shrinkWrap: true, itemCount: categories.isEmpty ? 10 : categories.length, primary: false, itemBuilder: (context, position) { if (categories.isEmpty) { return const ProductShimmer(); } else { return Column( children: [ // category tile for product InkWell( onTap: () { setState(() { categories[position].isExpanded = !categories[position].isExpanded; }); }, child: Padding( padding: mediumPaddingAll(), child: Row( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( categories[position].name, style: categories[position].isExpanded ? getTextStyle( fontSize: LARGE_FONT_SIZE, color: DARK_GREY_COLOR, fontWeight: FontWeight.w500) : getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, fontWeight: FontWeight.w500, ), ), categories[position].isExpanded ? Container() : Padding( padding: verticalSpace(x: 5), child: Text( "${categories[position].items.length} items", style: getTextStyle( color: MAIN_COLOR, fontWeight: FontWeight.normal, fontSize: SMALL_PLUS_FONT_SIZE), ), ), ], ), const Spacer(), SvgPicture.asset( categories[position].isExpanded ? CATEGORY_OPENED_ICON : CATEGORY_CLOSED_ICON, height: 10, ) ], ), ), ), // Expanded panel for a category categories[position].isExpanded ? productList(categories[position].items) : Container() ], ); } }); } Widget productList(prodList) { return ListView.builder( shrinkWrap: true, itemCount: prodList.isEmpty ? 10 : prodList.length, primary: false, itemBuilder: (context, position) { if (prodList.isEmpty) { return const ProductShimmer(); } else { return CategoryItem( product: prodList[position], ); // return SalesDetailsItems( // product: prodList[position], // ); // return ListTile(title: Text(prodList[position].name)); } }); } Widget productGrid() { return Padding( padding: const EdgeInsets.fromLTRB(16, 12, 16, 12), child: GridView.builder( itemCount: products.isEmpty ? 10 : products.length, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 20, crossAxisSpacing: 16, childAspectRatio: 0.80, ), shrinkWrap: true, physics: const ScrollPhysics(), itemBuilder: (context, position) { if (products.isEmpty) { return const ProductShimmer(); } else { return ProductWidget( title: products[position].name, asset: products[position].productImage, enableAddProductButton: false, product: products[position], ); } }, ), ); } Future<void> getProducts() async { //Fetching data from DbProduct database // products = await DbProduct().getProducts(); // categories = Category.getCategories(products); categories = await DbCategory().getCategories(); setState(() {}); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/products/ui
mirrored_repositories/GETPOS-Flutter-App/lib/core/mobile/products/ui/model/category.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import '../../../../../database/models/product.dart'; class Category { String id; String name; List<Product> itemList; bool isExpanded; Category({ required this.id, required this.name, required this.itemList, this.isExpanded = false, }); Category copyWith({ String? id, String? name, List<Product>? itemList, bool? isExpanded, }) { return Category( id: id ?? this.id, name: name ?? this.name, itemList: itemList ?? this.itemList, isExpanded: isExpanded ?? this.isExpanded, ); } Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'itemList': itemList.map((x) => x.toMap()).toList(), 'isExpanded': isExpanded, }; } factory Category.fromMap(Map<String, dynamic> map) { return Category( id: map['id'] ?? '', name: map['name'] ?? '', itemList: List<Product>.from(map['itemList']?.map((x) => Product.fromMap(x))), isExpanded: map['isExpanded'] ?? false, ); } String toJson() => json.encode(toMap()); factory Category.fromJson(String source) => Category.fromMap(json.decode(source)); @override String toString() { return 'Category(id: $id, name: $name, itemList: $itemList, isExpanded: $isExpanded)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Category && other.id == id && other.name == name && listEquals(other.itemList, itemList) && other.isExpanded == isExpanded; } @override int get hashCode { return id.hashCode ^ name.hashCode ^ itemList.hashCode ^ isExpanded.hashCode; } static List<Category> getCategories(List<Product> products) { List<Category> catList = []; for (Product p in products) { Category cat = Category( id: p.name, name: p.name, itemList: products, isExpanded: false); catList.add(cat); } return catList; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet/home_tablet.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../database/db_utils/db_hub_manager.dart'; import '../../../../database/models/hub_manager.dart'; import '../../../../utils/helper.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import 'create_order/create_order_landscape.dart'; import 'customer/customers_landscape.dart'; import 'my_account/my_account_landscape.dart'; import 'parked_order/orderlist_parked_landscape.dart'; import 'product/products_landscape.dart'; import 'transaction/transaction_screen_landscape.dart'; import 'widget/left_side_menu.dart'; // ignore: must_be_immutable class HomeTablet extends StatelessWidget { HomeTablet({Key? key}) : super(key: key); final selectedTab = "Order".obs; late Size size; @override Widget build(BuildContext context) { size = MediaQuery.of(context).size; _getHubManager(); return Scaffold( resizeToAvoidBottomInset: false, body: SafeArea( child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ LeftSideMenu(selectedView: selectedTab), Container( color: const Color(0xFFF9F8FB), padding: paddingXY(), child: Obx(() => SizedBox( width: size.width - 100, height: size.height, child: _getSelectedView(), )), ) ], )), ); } _getHubManager() async { HubManager manager = await DbHubManager().getManager() as HubManager; Helper.hubManager = manager; } _getSelectedView() { switch (selectedTab.value) { /*case "Home": //return const HomeLandscape(); return CreateOrderLandscape(selectedView: selectedTab);*/ case "Order": return CreateOrderLandscape(selectedView: selectedTab); /* case "Product": return const ProductsLandscape();*/ case "Customer": return const CustomersLandscape(); case "My Profile": return const MyAccountLandscape(); case "History": return TransactionScreenLandscape( selectedView: selectedTab, ); case "Parked Order": return OrderListParkedLandscape(selectedView: selectedTab); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet/my_account/my_account_landscape.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/route_manager.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../database/db_utils/db_hub_manager.dart'; import '../../../../../database/models/hub_manager.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../network/api_helper/comman_response.dart'; import '../../service/finance/api/get_updated_account_details.dart'; import '../../service/login/api/verify_instance_service.dart'; import '../widget/change_password.dart'; import '../widget/finance.dart'; import '../widget/logout_popup.dart'; import '../widget/title_search_bar.dart'; class MyAccountLandscape extends StatefulWidget { const MyAccountLandscape({Key? key}) : super(key: key); @override State<MyAccountLandscape> createState() => _MyAccountLandscapeState(); } class _MyAccountLandscapeState extends State<MyAccountLandscape> { var isChangePasswordVisible = true; double iconWidth = 80; String cashCollected = "00.00"; @override void initState() { verify(); _initView(); super.initState(); } _initView() async { if (await Helper.isNetworkAvailable()) { // print("INTERNET AVAILABLE"); Helper.showLoaderDialog(context); await UpdatedHubManagerDetails().getUpdatedAccountDetails(); if (!mounted) return; Helper.hideLoader(context); _getcashCollected(); } else { // print("INTERNET NOT AVAILABLE"); _getcashCollected(); } } _getcashCollected() async { HubManager manager = await DbHubManager().getManager() as HubManager; cashCollected = Helper().formatCurrency(manager.cashBalance); setState(() {}); } final FocusNode _focusNode = FocusNode(); @override void dispose() { _focusNode.dispose(); super.dispose(); } void _handleTap() { if (_focusNode.hasFocus) { _focusNode.unfocus(); } } @override Widget build(BuildContext context) { return SingleChildScrollView( // color: const Color(0xFFF9F8FB), // padding: paddingXY(), child:GestureDetector (onTap: _handleTap,child:Column( children: [ Column( children: [ hightSpacer20, TitleAndSearchBar( inputFormatter: [FilteringTextInputFormatter.digitsOnly], title: "My Profile", searchBoxVisible: false, onSubmit: (val) {}, onTextChanged: (val) {}, searchCtrl: null, searchHint: "", hideOperatorDetails: true, ), hightSpacer20, Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ widthSpacer(5), SvgPicture.asset( MY_PROFILE_TAB_IMAGE, // color: MAIN_COLOR, width: 25, ), widthSpacer(10), Text( Helper.hubManager!.name, style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.bold), ), ], ), hightSpacer20, Text( Helper.hubManager!.phone, style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.w600), ), ], ), Text( Helper.hubManager!.emailId, style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.w500), ), ], ), hightSpacer10, Divider(thickness: 1, color: DARK_GREY_COLOR.withOpacity(0.3)), hightSpacer20, Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ InkWell( onTap: () { verify(); debugPrint("Change Password clicked"); setState(() { isChangePasswordVisible = true; }); }, child: Column( children: [ SvgPicture.asset( isChangePasswordVisible ? CHANGE_PASS_ACTIVE_TAB_IMAGE : CHANGE_PASS_TAB_IMAGE, // color: MAIN_COLOR, width: iconWidth, ), Text( "Change Password", style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.w500), ), ], ), ), InkWell( onTap: () { verify(); debugPrint("Finance clicked"); setState(() { isChangePasswordVisible = false; }); }, child: Column( children: [ SvgPicture.asset( isChangePasswordVisible ? FINANCE_TAB_IMAGE : FINANCE_ACTIVE_TAB_IMAGE, width: iconWidth, ), Text( "Finance", style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.w500), ), ], ), ), InkWell( onTap: () async { verify(); debugPrint("Logout clicked need to show popup"); await Get.defaultDialog( // contentPadding: paddingXY(x: 0, y: 0), title: "", titlePadding: paddingXY(x: 0, y: 0), // custom: Container(), content: const LogoutPopupView(), ); }, child: Column( children: [ SvgPicture.asset( LOGOUT_TAB_IMAGE, // color: MAIN_COLOR, width: iconWidth, ), Text("Logout", style: getTextStyle( fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.w500)), ], ), ) ], ), Visibility( visible: isChangePasswordVisible, child: const ChangePasswordView(), ), Visibility( visible: !isChangePasswordVisible, child: FinanceView(cashCollected: cashCollected), ), ], ),])) ); } verify() async { CommanResponse res = await VerificationUrl.checkAppStatus(); if (res.message == true) { } else { Helper.showPopup(context, "Please update your app to latest version", barrierDismissible: true); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet/forgot_password/forgot_password_landscape.dart
import 'dart:developer'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:get/route_manager.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../utils/ui_utils/textfield_border_decoration.dart'; import '../../../../../widgets/button.dart'; import '../../../../../widgets/text_field_widget.dart'; import '../../../network/api_constants/api_paths.dart'; import '../../mobile/forgot_password/ui/verify_otp.dart'; import '../../service/forgot_password/api/forgot_password_api.dart'; class ForgotPasswordLandscape extends StatefulWidget { const ForgotPasswordLandscape({Key? key}) : super(key: key); @override State<ForgotPasswordLandscape> createState() => _ForgotPasswordLandscapeState(); } class _ForgotPasswordLandscapeState extends State<ForgotPasswordLandscape> { late TextEditingController _emailCtrl; late TextEditingController _urlCtrl; @override void initState() { super.initState(); _emailCtrl = TextEditingController(); _urlCtrl = TextEditingController(); _urlCtrl.text = "getpos.in"; // _getAppVersion(); } @override void dispose() { _emailCtrl.dispose(); super.dispose(); } /// TITLE TXT(HEADING) IN CENTER /// Widget get headingLblWidget => Center( child: Text( "Forgot Password", style: getTextStyle( // color: MAIN_COLOR, fontWeight: FontWeight.bold, fontSize: 26.0, ), ), ); Widget get subHeadingLblWidget => Center( child: Text( FORGOT_SUB_MSG, textAlign: TextAlign.center, style: getTextStyle( // color: MAIN_COLOR, fontWeight: FontWeight.w400, fontSize: LARGE_MINUS_FONT_SIZE, ), ), ); /// EMAIL SECTION Widget get emailTxtboxSection => Container( margin: horizontalSpace(), padding: smallPaddingAll(), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: leftSpace(x: 10), child: Text( "Email", style: getTextStyle(fontSize: MEDIUM_MINUS_FONT_SIZE), ), ), hightSpacer15, TextFieldWidget( boxDecoration: txtFieldBoxShadowDecoration, txtCtrl: _emailCtrl, verticalContentPadding: 16, hintText: "Enter registered email id", ), ]), ); ///Input field for entering the instance URL Widget instanceUrlTxtboxSection(context) => Container( margin: horizontalSpace(), padding: smallPaddingAll(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: leftSpace(x: 10), child: Text( URL_TXT, style: getTextStyle(fontSize: MEDIUM_MINUS_FONT_SIZE), ), ), hightSpacer15, TextFieldWidget( boxDecoration: txtFieldBoxShadowDecoration, txtCtrl: _urlCtrl, hintText: URL_HINT, ), ], ), ); /// LOGIN BUTTON Widget get cancelBtnWidget => SizedBox( // width: double.infinity, child: ButtonWidget( onPressed: () => Get.back(), title: "Cancel", colorBG: DARK_GREY_COLOR, width: 200, height: 60, fontSize: LARGE_PLUS_FONT_SIZE, ), ); Widget get continueBtnWidget => SizedBox( // width: double.infinity, child: ButtonWidget( onPressed: () async { await _handleForgotPassBtnClick(); }, title: "Continue", colorBG: MAIN_COLOR, width: 200, height: 60, fontSize: LARGE_PLUS_FONT_SIZE, ), ); @override Widget build(BuildContext context) { return WillPopScope( onWillPop: _onBackPressed, child: Scaffold( resizeToAvoidBottomInset: false, backgroundColor: WHITE_COLOR, body: Stack( children: [ // SvgPicture.asset( // LOGIN_IMAGE, // ), Center( child: Container( width: 550, padding: paddingXY(), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ headingLblWidget, hightSpacer50, SizedBox( width: 450, child: subHeadingLblWidget, ), hightSpacer50, instanceUrlTxtboxSection(context), hightSpacer20, emailTxtboxSection, hightSpacer20, hightSpacer20, Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [cancelBtnWidget, continueBtnWidget], ), ], ), ), ) ], ), ), ); } /// HANDLE BACK BTN PRESS ON LOGIN SCREEN Future<bool> _onBackPressed() async { var res = await Helper.showConfirmationPopup( context, CLOSE_APP_QUESTION, OPTION_YES, hasCancelAction: true); if (res != OPTION_CANCEL) { exit(0); } return false; } /// HANDLE FORGOT PASS BTN CLICK Future<void> _handleForgotPassBtnClick() async { String url = "https://${_urlCtrl.text}/api/"; try { Helper.showLoaderDialog(context); CommanResponse response = await ForgotPasswordApi() .sendResetPasswordMail(_emailCtrl.text.trim(), url.trim()); if (response.status!) { if (!mounted) return; Helper.hideLoader(context); Navigator.push(context, MaterialPageRoute(builder: (context) => const VerifyOtp())); } else { if (!mounted) return; Helper.hideLoader(context); Helper.showPopup(context, response.message); } } catch (e) { log('Exception ocurred in Forgot Password :: $e'); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet/login/login_landscape.dart
import 'dart:developer'; import 'dart:io'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:get/route_manager.dart'; import 'package:nb_posx/core/service/login/api/verify_instance_service.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../network/api_helper/comman_response.dart'; import '../../../../../utils/helper.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../utils/ui_utils/textfield_border_decoration.dart'; import '../../../../../widgets/button.dart'; import '../../../../../widgets/text_field_widget.dart'; import '../../../database/db_utils/db_instance_url.dart'; import '../../../network/api_constants/api_paths.dart'; import '../../mobile/webview_screens/enums/topic_types.dart'; import '../../mobile/webview_screens/ui/webview_screen.dart'; import '../../service/login/api/login_api_service.dart'; import '../forgot_password/forgot_password_landscape.dart'; import '../home_tablet.dart'; class LoginLandscape extends StatefulWidget { const LoginLandscape({Key? key}) : super(key: key); @override State<LoginLandscape> createState() => _LoginLandscapeState(); } class _LoginLandscapeState extends State<LoginLandscape> { late TextEditingController _emailCtrl, _passCtrl, _urlCtrl; late BuildContext ctx; @override void initState() { super.initState(); _emailCtrl = TextEditingController(); _passCtrl = TextEditingController(); _urlCtrl = TextEditingController(); _emailCtrl.text = "[email protected]"; _passCtrl.text = "demouser@123"; _urlCtrl.text = "getpos.in"; // _getAppVersion(); } @override void dispose() { _emailCtrl.dispose(); _passCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { ctx = context; return WillPopScope( onWillPop: _onBackPressed, child: Scaffold( resizeToAvoidBottomInset: true, backgroundColor: WHITE_COLOR, body: Stack( children: [ Center( child: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: Container( width: 550, padding: paddingXY(), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ headingLblWidget(), hightSpacer50, instanceUrlTxtboxSection(context), hightSpacer50, subHeadingLblWidget(), hightSpacer50, emailTxtboxSection(), hightSpacer20, passwordTxtboxSection(), hightSpacer20, forgotPasswordSection(), hightSpacer20, termAndPolicySection, hightSpacer32, loginBtnWidget(), ], ), )), ) ], ), ), ); } /// HANDLE LOGIN BTN ACTION Future<void> login(String email, String password, String url) async { try { Helper.showLoaderDialog(context); /// CommanResponse res = await VerificationUrl.checkAppStatus(); if(res.message==true){ CommanResponse response = await LoginService.login(email, password, url); if (response.status!) { //Adding static data into the database // await addDataIntoDB(); if (!mounted) return; Helper.hideLoader(ctx); Get.offAll(() => HomeTablet()); } else { if (!mounted) return; Helper.hideLoader(ctx); Helper.showPopup(ctx, response.message!); }} else{ Helper.showPopup(context, "Please update your app to latest version", barrierDismissible: true); } } catch (e) { Helper.hideLoader(ctx); log('Exception Caught :: $e'); Helper.showSnackBar(context, SOMETHING_WRONG); }} /// HANDLE BACK BTN PRESS ON LOGIN SCREEN Future<bool> _onBackPressed() async { var res = await Helper.showConfirmationPopup( context, CLOSE_APP_QUESTION, OPTION_YES, hasCancelAction: true); return false; } ///Input field for entering the instance URL Widget instanceUrlTxtboxSection(context) => Padding( // margin: horizontalSpace(), padding: smallPaddingAll(), child: SizedBox( height: 55, child: TextFieldWidget( boxDecoration: txtFieldBoxShadowDecoration, txtCtrl: _urlCtrl, verticalContentPadding: 16, hintText: URL_HINT, ), ), ); /// LOGIN TXT(HEADING) IN CENTER /// Widget headingLblWidget() => Center( // child: Text( // "POS", // style: getTextStyle( // color: MAIN_COLOR, // fontWeight: FontWeight.bold, // fontSize: 72.0, // ), // ), child: Image.asset( APP_ICON, height: 150, width: 150, ), ); Widget subHeadingLblWidget() => Center( child: Text( LOGIN_TXT, style: getTextStyle( // color: MAIN_COLOR, fontWeight: FontWeight.bold, fontSize: LARGE_FONT_SIZE, ), ), ); /// EMAIL SECTION Widget emailTxtboxSection() => Padding( // margin: horizontalSpace(), padding: smallPaddingAll(), child: SizedBox( height: 55, child: TextFieldWidget( boxDecoration: txtFieldBoxShadowDecoration, txtCtrl: _emailCtrl, verticalContentPadding: 16, hintText: "Enter your email", ), ), ); /// PASSWORD SECTION Widget passwordTxtboxSection() => Padding( padding: smallPaddingAll(), child: SizedBox( height: 55, child: TextFieldWidget( boxDecoration: txtFieldBoxShadowDecoration, txtCtrl: _passCtrl, verticalContentPadding: 16, hintText: "Enter your password", password: true, ), ), ); /// FORGOT PASSWORD SECTION Widget forgotPasswordSection() => Row( mainAxisAlignment: MainAxisAlignment.end, children: [ InkWell( onTap: () { _emailCtrl.clear(); _passCtrl.clear(); Navigator.push( ctx, MaterialPageRoute( builder: (context) => const ForgotPasswordLandscape())); }, child: Padding( padding: rightSpace(), child: Text( FORGET_PASSWORD_SMALL_TXT, style: getTextStyle( color: MAIN_COLOR, fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.w600), ), ), ), ], ); /// TERM AND CONDITION SECTION Widget get termAndPolicySection => Padding( padding: horizontalSpace(x: 80), child: RichText( textAlign: TextAlign.center, text: TextSpan( text: BY_SIGNING_IN, style: getTextStyle( color: DARK_GREY_COLOR, fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.normal), children: <TextSpan>[ TextSpan( recognizer: TapGestureRecognizer() ..onTap = () { Navigator.push( ctx, MaterialPageRoute( builder: (context) => WebViewScreen( topicTypes: TopicTypes.TERMS_AND_CONDITIONS, apiUrl: "https://${_urlCtrl.text}/api/"))); }, text: TERMS_CONDITIONS, style: getTextStyle( color: DARK_GREY_COLOR, fontWeight: FontWeight.bold, fontSize: LARGE_MINUS_FONT_SIZE)), TextSpan( text: AND_TXT, style: getTextStyle( color: DARK_GREY_COLOR, fontWeight: FontWeight.normal, fontSize: LARGE_MINUS_FONT_SIZE)), TextSpan( recognizer: TapGestureRecognizer() ..onTap = () { { Navigator.push( ctx, MaterialPageRoute( builder: (context) => WebViewScreen( topicTypes: TopicTypes.PRIVACY_POLICY, apiUrl: "https://${_urlCtrl.text}/api/"))); } }, text: PRIVACY_POLICY, style: getTextStyle( color: DARK_GREY_COLOR, fontWeight: FontWeight.bold, fontSize: LARGE_MINUS_FONT_SIZE)), ]), ), ); /// LOGIN BUTTON Widget loginBtnWidget() => SizedBox( width: double.infinity, child: ButtonWidget( onPressed: () async { await DbInstanceUrl().deleteUrl(); String url = "https://${_urlCtrl.text}/api/"; await login(_emailCtrl.text, _passCtrl.text, url); }, title: "Log In", colorBG: MAIN_COLOR, // width: MediaQuery.of(context).size.width - 150, height: 60, fontSize: LARGE_PLUS_FONT_SIZE, ), ); ///Method to check whether the API URL is correct. /* bool isValidInstanceUrl() { String url = "https://${_urlCtrl.text}/api/"; return Helper.isValidUrl(url); }*/ }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet/product/products_landscape.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/svg.dart'; import 'package:get/get.dart'; import 'package:get/route_manager.dart'; import '../../../../configs/theme_config.dart'; import '../../../../constants/app_constants.dart'; import '../../../../constants/asset_paths.dart'; import '../../../../database/db_utils/db_categories.dart'; import '../../../../database/models/category.dart'; import '../../../../database/models/customer.dart'; import '../../../../database/models/product.dart'; import '../../../../utils/ui_utils/padding_margin.dart'; import '../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../widget/create_customer_popup.dart'; import '../widget/select_customer_popup.dart'; import '../widget/title_search_bar.dart'; class ProductsLandscape extends StatefulWidget { const ProductsLandscape({Key? key}) : super(key: key); @override State<ProductsLandscape> createState() => _ProductsLandscapeState(); } class _ProductsLandscapeState extends State<ProductsLandscape> { late TextEditingController searchCtrl; late Size size; Customer? customer; List<Product> products = []; List<Category> categories = []; @override void initState() { searchCtrl = TextEditingController(); super.initState(); getProducts(); } @override void dispose() { searchCtrl.dispose(); _focusNode.dispose(); super.dispose(); } final FocusNode _focusNode = FocusNode(); void _handleTap() { if (_focusNode.hasFocus) { _focusNode.unfocus(); } } @override Widget build(BuildContext context) { size = MediaQuery.of(context).size; return SingleChildScrollView( child:GestureDetector (onTap: _handleTap,child: Column( children: [ Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.max, children: [ TitleAndSearchBar( inputFormatter: [], focusNode: _focusNode, title: "Choose Category", onSubmit: (text) { if (text.length >= 3) { _filterProductsCategories(text); } else { getProducts(); } }, onTextChanged: (changedtext) { if (changedtext.length >= 3) { _filterProductsCategories(changedtext); } else { getProducts(); } }, searchCtrl: searchCtrl, searchHint: "Search product", searchBoxWidth: size.width / 4, ), hightSpacer20, getCategoryListWidget(), hightSpacer20, ListView.builder( primary: false, shrinkWrap: true, itemCount: categories.length, itemBuilder: (context, index) { return Column( children: [ getCategoryItemsWidget(categories[index]), hightSpacer10 ], ); }, ), ], )]))); } getCategoryItemsWidget(Category cat) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( cat.name, style: getTextStyle( fontSize: LARGE_FONT_SIZE, ), ), hightSpacer10, SizedBox( height: 140, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: cat.items.length, itemBuilder: (BuildContext context, index) { return Container( margin: const EdgeInsets.only(left: 8, right: 8), child: InkWell( onTap: () { // var item = // OrderItem.fromJson(cat.items[index].toJson()); // _openItemDetailDialog(context, item); debugPrint("Item clicked $index"); }, child: Stack( alignment: Alignment.topCenter, children: [ Align( alignment: Alignment.bottomCenter, child: Container( margin: paddingXY(x: 5, y: 5), padding: paddingXY(y: 0, x: 10), width: 145, height: 105, decoration: BoxDecoration( color: WHITE_COLOR, borderRadius: BorderRadius.circular(10)), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ hightSpacer25, SizedBox( child: Text( cat.items[index].name, maxLines: 2, overflow: TextOverflow.ellipsis, style: getTextStyle( color: DARK_GREY_COLOR, fontWeight: FontWeight.w500, fontSize: SMALL_PLUS_FONT_SIZE), ), ), hightSpacer5, Text( "$appCurrency ${cat.items[index].price}", textAlign: TextAlign.right, style: getTextStyle( color: MAIN_COLOR, fontSize: MEDIUM_FONT_SIZE), ), ], ), ), ), Container( height: 60, width: 60, decoration: const BoxDecoration(shape: BoxShape.circle), clipBehavior: Clip.antiAliasWithSaveLayer, child: cat.items[index].productImage.isNotEmpty ? Image.memory(cat.items[index].productImage, fit: BoxFit.fill) : SvgPicture.asset( PRODUCT_IMAGE, ), ), ], ), )); }), ), ], ); } getCategoryListWidget() { return SizedBox( height: 100, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: categories.length, itemBuilder: (BuildContext context, index) { return InkWell( child: Container( margin: paddingXY(y: 5), width: 70, decoration: BoxDecoration( color: WHITE_COLOR, borderRadius: BorderRadius.circular(10), ), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: [ categories[index].image.isNotEmpty ? Image.memory( categories[index].image, height: 45, width: 45, ) : Image.asset( BURGAR_IMAGE, height: 45, width: 45, ), Text( categories[index].name, maxLines: 1, overflow: TextOverflow.ellipsis, style: getTextStyle( fontWeight: FontWeight.w600, ), ), ], ), ), ); }), ); } _handleCustomerPopup() async { final result = await Get.defaultDialog( // contentPadding: paddingXY(x: 0, y: 0), title: "", titlePadding: paddingXY(x: 0, y: 0), // custom: Container(), content: SelectCustomerPopup( customer: customer, ), ); if (result.runtimeType == String) { customer = await Get.defaultDialog( // contentPadding: paddingXY(x: 0, y: 0), title: "", titlePadding: paddingXY(x: 0, y: 0), // custom: Container(), content: CreateCustomerPopup( phoneNo: result, ), ); } if (customer != null) { debugPrint("Customer selected"); } setState(() {}); } Future<void> getProducts() async { //Fetching data from DbProduct database categories = await DbCategory().getCategories(); setState(() {}); } void _filterProductsCategories(String searchTxt) { categories = categories .where((element) => element.items.any((element) => element.name.toLowerCase().contains(searchTxt.toLowerCase())) || element.name.toLowerCase().contains(searchTxt.toLowerCase())) .toList(); setState(() {}); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet/widget/create_customer_popup.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/route_manager.dart'; import 'package:nb_posx/network/api_helper/comman_response.dart'; import 'package:nb_posx/utils/helper.dart'; import '../../../../../configs/theme_config.dart'; import '../../../../../constants/app_constants.dart'; import '../../../../../constants/asset_paths.dart'; import '../../../../../database/models/customer.dart'; import '../../../../../utils/ui_utils/padding_margin.dart'; import '../../../../../utils/ui_utils/spacer_widget.dart'; import '../../../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../../../../../utils/ui_utils/textfield_border_decoration.dart'; import '../../../../../widgets/text_field_widget.dart'; import '../../../database/db_utils/db_customer.dart'; import '../../service/select_customer/api/create_customer.dart'; // ignore: must_be_immutable class CreateCustomerPopup extends StatefulWidget { String phoneNo; CreateCustomerPopup({Key? key, required this.phoneNo}) : super(key: key); @override State<CreateCustomerPopup> createState() => _CreateCustomerPopupState(); } class _CreateCustomerPopupState extends State<CreateCustomerPopup> { late TextEditingController phoneCtrl, emailCtrl, nameCtrl; Customer? customer; bool customerFound = false; @override void initState() { nameCtrl = TextEditingController(); phoneCtrl = TextEditingController(); emailCtrl = TextEditingController(); phoneCtrl.text = widget.phoneNo; super.initState(); } @override void dispose() { phoneCtrl.dispose(); emailCtrl.dispose(); nameCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return SingleChildScrollView( child: Column(children: [ Align( alignment: Alignment.topRight, child: InkWell( onTap: () { Get.back(); }, child: Padding( padding: const EdgeInsets.only(right: 10), child: SvgPicture.asset( CROSS_ICON, color: BLACK_COLOR, width: 20, height: 20, ), ), ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16), child: Column( children: [ Text( "Add Customer", style: getTextStyle( fontSize: LARGE_PLUS_FONT_SIZE, fontWeight: FontWeight.bold, color: BLACK_COLOR), ), hightSpacer30, Container( width: 400, // height: 100, padding: horizontalSpace(), child: IgnorePointer( child: TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: phoneCtrl, hintText: "Enter phone no.", txtColor: DARK_GREY_COLOR, ))), hightSpacer20, Container( width: 400, // height: 100, padding: horizontalSpace(), child: TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: nameCtrl, hintText: "Enter name", txtColor: DARK_GREY_COLOR, )), hightSpacer20, Container( width: 400, // height: 100, padding: horizontalSpace(), child: TextFieldWidget( boxDecoration: txtFieldBorderDecoration, txtCtrl: emailCtrl, hintText: "Enter email (optional)", txtColor: DARK_GREY_COLOR, )), hightSpacer40, InkWell( onTap: () { _newCustomerAPI(); customer = Customer( id: emailCtrl.text, name: nameCtrl.text ?? "Guest", email: emailCtrl.text, phone: phoneCtrl.text, isSynced: false, modifiedDateTime: DateTime.now() // ward: Ward(id: "01", name: "name"), // profileImage: Uint8List.fromList([]), ); if (customer != null) { Get.back(result: customer); } }, child: Container( width: 380, height: 50, decoration: BoxDecoration( color: MAIN_COLOR, // phoneCtrl.text.length == 10 && nameCtrl.text.isNotEmpty // ? MAIN_COLOR // : MAIN_COLOR.withOpacity(0.3), // border: Border.all(width: 1, color: MAIN_COLOR.withOpacity(0.3)), borderRadius: BorderRadius.circular(10), ), child: Center( child: Text( "Add & Create Order", textAlign: TextAlign.center, style: getTextStyle( fontSize: LARGE_FONT_SIZE, color: WHITE_COLOR, fontWeight: FontWeight.w600), ), ), ), ), SizedBox( height: 20, ) ], ), ), ])); } Future<void> _newCustomerAPI() async { CommanResponse response = await CreateCustomer() .createNew(phoneCtrl.text, nameCtrl.text, emailCtrl.text); if (response.status!) { } else { Customer tempCustomer = Customer( // profileImage: image, // ward: Ward(id: "1", name: "1"), email: emailCtrl.text.trim(), id: phoneCtrl.text.trim(), name: nameCtrl.text.trim(), phone: phoneCtrl.text.trim(), isSynced: false, modifiedDateTime: DateTime.now()); List<Customer> customers = []; customers.add(tempCustomer); await DbCustomer().addCustomers(customers); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet
mirrored_repositories/GETPOS-Flutter-App/lib/core/tablet/widget/left_side_menu_old.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/get.dart'; import '../../../configs/theme_config.dart'; import '../../../constants/app_constants.dart'; import '../../../constants/asset_paths.dart'; import '../../../utils/ui_utils/padding_margin.dart'; import '../../../utils/ui_utils/spacer_widget.dart'; import '../../../utils/ui_utils/text_styles/custom_text_style.dart'; import '../home/home_landscape.dart'; // ignore: must_be_immutable class LeftSideMenu extends StatefulWidget { RxString selectedView; LeftSideMenu({Key? key, required this.selectedView}) : super(key: key); @override State<LeftSideMenu> createState() => _LeftSideMenuState(); } class _LeftSideMenuState extends State<LeftSideMenu> { @override Widget build(BuildContext context) { return Container( width: 80, height: Get.size.height, color: WHITE_COLOR, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, // mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container( padding: morePaddingAll(), decoration: const BoxDecoration( color: MAIN_COLOR, borderRadius: BorderRadius.only( topLeft: Radius.circular(15), topRight: Radius.circular(15))), child: Text( "POS", textAlign: TextAlign.center, style: getTextStyle( color: WHITE_COLOR, fontSize: MEDIUM_PLUS_FONT_SIZE), ), ), _leftMenuSectionItem("Home", CREATE_ORDER_IMAGE, 50, () { debugPrint("Home"); Get.off(const HomeLandscape(), duration: const Duration(milliseconds: 0)); }), _leftMenuSectionItem("Order", CREATE_ORDER_IMAGE, 50, () { debugPrint("order"); }), _leftMenuSectionItem("Product", PRODUCT_IMAGE, 50, () {}), _leftMenuSectionItem("Customer", HOME_USER_IMAGE, 50, () {}), _leftMenuSectionItem("History", SALES_IMAGE, 50, () {}), _leftMenuSectionItem("Finance", FINANCE_IMAGE, 50, () { // Get.off(const FinanceLandscape(), // duration: const Duration(milliseconds: 0)); }), _leftMenuSectionItem("Logout", LOGOUT_IMAGE, 25, () { Get.defaultDialog( onCancel: () => Get.back(), title: "Do you want to logout?", content: Container(), confirm: const Text("Yes"), confirmTextColor: MAIN_COLOR, cancel: const Text("Cancel")); }), ], ), ); } _leftMenuSectionItem( String title, String iconData, double width, Function() action) { return InkWell( onTap: () => action(), child: Container( margin: paddingXY(y: 5), height: 75, decoration: BoxDecoration( color: title.toLowerCase() == widget.selectedView.toLowerCase() ? MAIN_COLOR : WHITE_COLOR, borderRadius: BorderRadius.circular(5), boxShadow: const [BoxShadow(blurRadius: 0.05)], border: Border.all(width: 1, color: GREY_COLOR), ), child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ SvgPicture.asset( iconData, // color: MAIN_COLOR, width: width, ), Text( title, style: getTextStyle( fontWeight: FontWeight.w400, color: title.toLowerCase() == widget.selectedView.toLowerCase() ? WHITE_COLOR : BLACK_COLOR, ), ), hightSpacer10, ], ), ), ); } }
0