first commit

This commit is contained in:
2026-02-07 15:57:09 +07:00
commit 157096f164
1153 changed files with 415766 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
class IncomeCategory {
IncomeCategory({
this.id,
this.categoryName,
this.businessId,
this.categoryDescription,
this.status,
this.createdAt,
this.updatedAt,
});
IncomeCategory.fromJson(dynamic json) {
id = json['id'];
categoryName = json['categoryName'];
businessId = json['business_id'];
categoryDescription = json['categoryDescription'];
status = json['status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
num? id;
String? categoryName;
num? businessId;
String? categoryDescription;
bool? status;
String? createdAt;
String? updatedAt;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['id'] = id;
map['categoryName'] = categoryName;
map['business_id'] = businessId;
map['categoryDescription'] = categoryDescription;
map['status'] = status;
map['created_at'] = createdAt;
map['updated_at'] = updatedAt;
return map;
}
}

View File

@@ -0,0 +1,96 @@
class Income {
Income({
this.id,
this.account,
this.amount,
this.incomeCategoryId,
this.userId,
this.businessId,
this.incomeFor,
this.paymentTypeId,
this.paymentType,
this.referenceNo,
this.note,
this.incomeDate,
this.createdAt,
this.updatedAt,
this.category,
});
Income.fromJson(dynamic json) {
id = json['id'];
account = json['account'];
amount = json['amount'] as num;
incomeCategoryId = json['income_category_id'];
userId = json['user_id'];
businessId = json['business_id'];
incomeFor = json['incomeFor'];
paymentTypeId = json["payment_type_id"];
paymentType = json['paymentType'];
referenceNo = json['referenceNo'];
note = json['note'];
incomeDate = json['incomeDate'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
category = json['category'] != null ? Category.fromJson(json['category']) : null;
}
num? id;
num? account;
num? amount;
num? incomeCategoryId;
num? userId;
num? businessId;
String? incomeFor;
int? paymentTypeId;
String? paymentType;
String? referenceNo;
String? note;
String? incomeDate;
String? createdAt;
String? updatedAt;
Category? category;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['id'] = id;
map['account'] = account;
map['amount'] = amount;
map['expense_category_id'] = incomeCategoryId;
map['user_id'] = userId;
map['business_id'] = businessId;
map['expanseFor'] = incomeFor;
map['paymentType'] = paymentType;
map['referenceNo'] = referenceNo;
map['note'] = note;
map['incomeDate'] = incomeDate;
map['created_at'] = createdAt;
map['updated_at'] = updatedAt;
if (category != null) {
map['category'] = category?.toJson();
}
return map;
}
}
class Category {
Category({
this.id,
this.categoryName,
});
Category.fromJson(dynamic json) {
id = json['id'];
categoryName = json['categoryName'];
}
num? id;
String? categoryName;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['id'] = id;
map['categoryName'] = categoryName;
return map;
}
}

View File

@@ -0,0 +1,21 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../Provider/transactions_provider.dart';
import '../Model/income_modle.dart';
import '../Repo/income_repo.dart';
final incomeRepoProvider = Provider<IncomeRepo>(
(ref) => IncomeRepo(),
);
final filteredIncomeProvider = FutureProvider.family.autoDispose<List<Income>, FilterModel>(
(ref, filter) {
final repo = ref.read(incomeRepoProvider);
return repo.fetchAllIncome(
type: filter.duration,
fromDate: filter.fromDate,
toDate: filter.toDate,
);
},
);

View File

@@ -0,0 +1,7 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../Model/income_category.dart';
import '../Repo/income_category_repo.dart';
IncomeCategoryRepo incomeCategoryRepo = IncomeCategoryRepo();
final incomeCategoryProvider = FutureProvider.autoDispose<List<IncomeCategory>>((ref) => incomeCategoryRepo.fetchAllIncomeCategory());

View File

@@ -0,0 +1,70 @@
//ignore_for_file: file_names, unused_element, unused_local_variable
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:mobile_pos/Screens/Income/Providers/income_category_provider.dart';
import '../../../Const/api_config.dart';
import '../../../Repository/constant_functions.dart';
import '../../../http_client/custome_http_client.dart';
import '../../../http_client/customer_http_client_get.dart';
import '../Model/income_category.dart';
class IncomeCategoryRepo {
Future<List<IncomeCategory>> fetchAllIncomeCategory() async {
CustomHttpClientGet clientGet = CustomHttpClientGet(client: http.Client());
final uri = Uri.parse('${APIConfig.url}/income-categories');
try {
final response = await clientGet.get(url: uri);
if (response.statusCode == 200) {
final parsedData = jsonDecode(response.body) as Map<String, dynamic>;
final categoryList = parsedData['data'] as List<dynamic>;
return categoryList.map((category) => IncomeCategory.fromJson(category)).toList();
} else {
// Handle specific error cases based on response codes
throw Exception('Failed to fetch categories: ${response.statusCode}');
}
} catch (error) {
// Handle unexpected errors gracefully
rethrow; // Re-throw to allow further handling upstream
}
}
Future<void> addIncomeCategory({
required WidgetRef ref,
required BuildContext context,
required String categoryName,
}) async {
final uri = Uri.parse('${APIConfig.url}/income-categories');
CustomHttpClient customHttpClient = CustomHttpClient(client: http.Client(), context: context, ref: ref);
var responseData = await customHttpClient.post(
url: uri,
body: {
'categoryName': categoryName,
},
);
EasyLoading.dismiss();
try {
final parsedData = jsonDecode(responseData.body);
if (responseData.statusCode == 200) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Added successful!')));
var data1 = ref.refresh(incomeCategoryProvider);
Navigator.pop(context);
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Category creation failed: ${parsedData['message']}')));
}
} catch (error) {
// Handle unexpected errors gracefully
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('An error occurred: $error')));
}
}
}

View File

@@ -0,0 +1,120 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import '../../../Const/api_config.dart';
import '../../../http_client/custome_http_client.dart';
import '../../../http_client/customer_http_client_get.dart';
import '../../../widgets/multipal payment mathods/multi_payment_widget.dart';
import '../Model/income_modle.dart';
class IncomeRepo {
Future<List<Income>> fetchAllIncome({
String? type,
String? fromDate,
String? toDate,
}) async {
final client = CustomHttpClientGet(client: http.Client());
final Map<String, String> queryParams = {};
if (type != null && type.isNotEmpty) {
queryParams['duration'] = type;
}
if (type == 'custom_date') {
if (fromDate != null && fromDate.isNotEmpty) {
queryParams['from_date'] = fromDate;
}
if (toDate != null && toDate.isNotEmpty) {
queryParams['to_date'] = toDate;
}
}
final Uri uri = Uri.parse('${APIConfig.url}/incomes').replace(
queryParameters: queryParams.isNotEmpty ? queryParams : null,
);
print('Request URI: $uri');
final response = await client.get(url: uri);
if (response.statusCode == 200) {
final parsed = jsonDecode(response.body) as Map<String, dynamic>;
final list = parsed['data'] as List<dynamic>;
return list.map((json) => Income.fromJson(json)).toList();
} else {
throw Exception('Failed to fetch Due List. Status code: ${response.statusCode}');
}
}
Future<void> createIncome({
required WidgetRef ref,
required BuildContext context,
required num amount,
required num incomeCategoryId,
required String incomeFor, // Renamed from expanseFor
required String referenceNo,
required String incomeDate, // Renamed from expenseDate
required String note,
required List<PaymentEntry> payments, // <<< Updated parameter
}) async {
final uri = Uri.parse('${APIConfig.url}/incomes');
// Build the request body as a Map<String, String> for form-data
Map<String, String> requestBody = {
'amount': amount.toString(),
'income_category_id': incomeCategoryId.toString(),
'incomeFor': incomeFor,
'referenceNo': referenceNo,
'incomeDate': incomeDate,
'note': note,
};
// Add payments in the format: payments[index][key]
for (int i = 0; i < payments.length; i++) {
final payment = payments[i];
final paymentAmount = num.tryParse(payment.amountController.text) ?? 0;
if (payment.type != null && paymentAmount > 0) {
requestBody['payments[$i][type]'] = payment.type!;
requestBody['payments[$i][amount]'] = paymentAmount.toString();
if (payment.type == 'cheque' && payment.chequeNumberController.text.isNotEmpty) {
requestBody['payments[$i][cheque_number]'] = payment.chequeNumberController.text;
}
}
}
try {
CustomHttpClient customHttpClient = CustomHttpClient(client: http.Client(), context: context, ref: ref);
var responseData = await customHttpClient.post(
url: uri,
body: requestBody, // Send the Map directly
// Set to false to send as x-www-form-urlencoded
addContentTypeInHeader: false,
);
final parsedData = jsonDecode(responseData.body);
EasyLoading.dismiss();
if (responseData.statusCode == 200 || responseData.statusCode == 201) {
// Refresh income-related providers
Navigator.pop(context, true);
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(parsedData['message'] ?? 'Income created successfully')));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Income creation failed: ${parsedData['message']}')));
return;
}
} catch (error) {
EasyLoading.dismiss();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('An error occurred: $error')));
}
}
}

View File

@@ -0,0 +1,316 @@
// ignore_for_file: unused_result
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:iconly/iconly.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/Screens/Income/Model/income_category.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';
import '../../GlobalComponents/glonal_popup.dart';
import '../../constant.dart';
import '../../service/check_user_role_permission_provider.dart';
import '../../widgets/multipal payment mathods/multi_payment_widget.dart';
import 'Repo/income_repo.dart';
import 'income_category_list.dart';
// ignore: must_be_immutable
class AddIncome extends ConsumerStatefulWidget {
const AddIncome({
super.key,
});
@override
// ignore: library_private_types_in_public_api
_AddIncomeState createState() => _AddIncomeState();
}
class _AddIncomeState extends ConsumerState<AddIncome> {
IncomeCategory? selectedCategory;
final dateController = TextEditingController();
TextEditingController incomeForNameController = TextEditingController();
TextEditingController incomeAmountController = TextEditingController();
TextEditingController incomeNoteController = TextEditingController();
TextEditingController incomeRefController = TextEditingController();
final GlobalKey<MultiPaymentWidgetState> _paymentKey = GlobalKey<MultiPaymentWidgetState>();
@override
void initState() {
super.initState();
}
@override
void dispose() {
dateController.dispose();
incomeForNameController.dispose();
incomeAmountController.dispose();
incomeNoteController.dispose();
incomeRefController.dispose();
super.dispose();
}
DateTime selectedDate = DateTime.now();
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context, initialDate: selectedDate, firstDate: DateTime(2015, 8), lastDate: DateTime(2101));
if (picked != null && picked != selectedDate) {
setState(() {
selectedDate = picked;
});
}
}
GlobalKey<FormState> formKey = GlobalKey<FormState>();
bool validateAndSave() {
final form = formKey.currentState;
if (form!.validate()) {
form.save();
return true;
}
return false;
}
@override
Widget build(BuildContext context) {
final permissionService = PermissionService(ref);
return GlobalPopup(
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.white,
title: Text(
lang.S.of(context).addIncome,
),
centerTitle: true,
iconTheme: const IconThemeData(color: Colors.black),
elevation: 0.0,
),
body: SingleChildScrollView(
child: SizedBox(
width: context.width(),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
key: formKey,
child: Column(
children: [
///_______date________________________________
SizedBox(
height: 48,
child: FormField(
builder: (FormFieldState<dynamic> field) {
return InputDecorator(
decoration: kInputDecoration.copyWith(
suffixIcon: const Icon(IconlyLight.calendar, color: kGreyTextColor),
contentPadding: const EdgeInsets.all(8),
labelText: lang.S.of(context).incomeDate,
hintText: lang.S.of(context).enterExpenseDate,
),
child: Text(
'${DateFormat.d().format(selectedDate)} ${DateFormat.MMM().format(selectedDate)} ${DateFormat.y().format(selectedDate)}',
),
);
},
).onTap(() => _selectDate(context)),
),
const SizedBox(height: 20),
///_________category_______________________________________________
TextFormField(
readOnly: true,
controller: TextEditingController(
text: selectedCategory?.categoryName ?? lang.S.of(context).selectCategory),
onTap: () async {
selectedCategory = await const IncomeCategoryList().launch(context);
setState(() {});
},
decoration: kInputDecoration.copyWith(
contentPadding: const EdgeInsets.symmetric(vertical: 14.0, horizontal: 10.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
borderSide: BorderSide(color: kBorderColor, width: 1),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
borderSide: BorderSide(color: kBorderColor, width: 1),
),
suffixIcon: const Icon(Icons.keyboard_arrow_down),
),
),
const SizedBox(height: 20),
///________Income_for_______________________________________________
TextFormField(
showCursor: true,
controller: incomeForNameController,
validator: (value) {
if (value.isEmptyOrNull) {
return lang.S.of(context).pleaseEnterName;
}
return null;
},
onSaved: (value) {
incomeForNameController.text = value!;
},
decoration: kInputDecoration.copyWith(
floatingLabelBehavior: FloatingLabelBehavior.always,
labelText: lang.S.of(context).incomeFor,
hintText: lang.S.of(context).enterName,
),
),
const SizedBox.square(dimension: 20),
///_________________Total Amount_____________________________
TextFormField(
controller: incomeAmountController,
readOnly: (_paymentKey.currentState?.getPaymentEntries().length ?? 1) > 1,
inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}'))],
validator: (value) {
if (value.isEmptyOrNull) {
return lang.S.of(context).pleaseEnterAmount;
}
final total = double.tryParse(value ?? '') ?? 0.0;
if (total <= 0) {
return lang.S.of(context).amountMustBeGreaterThanZero;
}
return null;
},
decoration: kInputDecoration.copyWith(
fillColor: (_paymentKey.currentState?.getPaymentEntries().length ?? 1) > 1
? Colors.grey.shade100
: Colors.white,
filled: true,
border: const OutlineInputBorder(),
errorBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
labelText: lang.S.of(context).amount,
floatingLabelBehavior: FloatingLabelBehavior.always,
hintText: '0.00',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 20),
///_______reference_________________________________
TextFormField(
showCursor: true,
controller: incomeRefController,
validator: (value) {
return null; // Reference is optional
},
onSaved: (value) {
incomeRefController.text = value!;
},
decoration: kInputDecoration.copyWith(
border: const OutlineInputBorder(),
labelText: lang.S.of(context).referenceNo,
floatingLabelBehavior: FloatingLabelBehavior.always,
hintText: lang.S.of(context).enterRefNumber,
),
),
const SizedBox(height: 20),
///_________note____________________________________________________
TextFormField(
showCursor: true,
controller: incomeNoteController,
validator: (value) {
return null; // Note is optional
},
onSaved: (value) {
incomeNoteController.text = value!;
},
decoration: kInputDecoration.copyWith(
border: const OutlineInputBorder(),
labelText: lang.S.of(context).note,
hintText: lang.S.of(context).enterNote,
),
),
const SizedBox(height: 20),
MultiPaymentWidget(
key: _paymentKey,
totalAmountController: incomeAmountController,
showChequeOption: true,
onPaymentListChanged: () {
setState(() {
// Rebuild to update readOnly status of amount field
});
},
),
const SizedBox(height: 20),
///_______button_________________________________
ElevatedButton.icon(
iconAlignment: IconAlignment.end,
onPressed: () async {
if (validateAndSave()) {
if (!permissionService.hasPermission(Permit.incomesCreate.value)) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.red,
content: Text(lang.S.of(context).youDonNotHavePermissionToCreateIncome),
),
);
return;
}
final totalIncome = double.tryParse(incomeAmountController.text) ?? 0.0;
final payments = _paymentKey.currentState?.getPaymentEntries();
if (selectedCategory == null) {
EasyLoading.showError(lang.S.of(context).pleaseSelectACategory);
return;
}
if (totalIncome <= 0) {
EasyLoading.showError(lang.S.of(context).amountMustBeGreaterThanZero);
return;
}
if (payments == null || payments.isEmpty) {
EasyLoading.showError(lang.S.of(context).canNotRetrievePaymentDetails);
return;
}
EasyLoading.show();
IncomeRepo repo = IncomeRepo();
await repo.createIncome(
ref: ref,
context: context,
amount: totalIncome,
incomeCategoryId: selectedCategory?.id ?? 0,
incomeFor: incomeForNameController.text,
referenceNo: incomeRefController.text,
incomeDate: selectedDate.toString(),
note: incomeNoteController.text,
payments: payments, // Pass the payment list
);
}
},
icon: const Icon(
Icons.arrow_forward,
color: Colors.white,
),
label: Text(lang.S.of(context).continueButton),
),
],
)),
),
),
),
),
);
}
}

View File

@@ -0,0 +1,114 @@
// ignore_for_file: unused_result
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mobile_pos/Screens/Income/Repo/income_category_repo.dart';
import 'package:mobile_pos/constant.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';
import '../../GlobalComponents/glonal_popup.dart';
import '../../http_client/custome_http_client.dart';
import '../../service/check_user_role_permission_provider.dart';
class AddIncomeCategory extends StatefulWidget {
const AddIncomeCategory({Key? key}) : super(key: key);
@override
// ignore: library_private_types_in_public_api
_AddIncomeCategoryState createState() => _AddIncomeCategoryState();
}
class _AddIncomeCategoryState extends State<AddIncomeCategory> {
bool showProgress = false;
TextEditingController nameController = TextEditingController();
GlobalKey<FormState> key = GlobalKey();
@override
Widget build(BuildContext context) {
return Consumer(builder: (context, ref, __) {
//final allCategory = ref.watch(expanseCategoryProvider);
final permissionService = PermissionService(ref);
return GlobalPopup(
child: Scaffold(
backgroundColor: kWhite,
appBar: AppBar(
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: const Icon(Icons.close)),
title: Text(
lang.S.of(context).addIncomeCategory,
),
iconTheme: const IconThemeData(color: Colors.black),
centerTitle: true,
backgroundColor: Colors.white,
elevation: 0.0,
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Visibility(
visible: showProgress,
child: const CircularProgressIndicator(
color: kMainColor,
strokeWidth: 5.0,
),
),
Form(
key: key,
child: TextFormField(
validator: (value) {
if (value?.trim().isEmptyOrNull ?? true) {
//return 'Enter expanse category name';
return lang.S.of(context).enterIncomeCategoryName;
}
return null;
},
controller: nameController,
decoration: InputDecoration(
border: const OutlineInputBorder(),
floatingLabelBehavior: FloatingLabelBehavior.always,
labelText: lang.S.of(context).categoryName,
),
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
if (!permissionService.hasPermission(Permit.incomeCategoriesCreate.value)) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.red,
content: Text(lang.S.of(context).youDoNotHavePermissionToCreateIncomeCategory),
),
);
return;
}
if (key.currentState?.validate() ?? false) {
EasyLoading.show();
final incomeRepo = IncomeCategoryRepo();
await incomeRepo.addIncomeCategory(
ref: ref,
context: context,
categoryName: nameController.text.trim(),
);
}
},
child: Text(lang.S.of(context).save),
),
],
),
),
),
),
);
});
}
}

View File

@@ -0,0 +1,154 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';
import '../../GlobalComponents/glonal_popup.dart';
import '../../constant.dart';
import '../../http_client/custome_http_client.dart';
import '../../widgets/empty_widget/_empty_widget.dart';
import '../../service/check_user_role_permission_provider.dart';
import 'Providers/income_category_provider.dart';
import 'add_income_category.dart';
class IncomeCategoryList extends StatefulWidget {
const IncomeCategoryList({Key? key, this.mainContext}) : super(key: key);
final BuildContext? mainContext;
@override
// ignore: library_private_types_in_public_api
_IncomeCategoryListState createState() => _IncomeCategoryListState();
}
class _IncomeCategoryListState extends State<IncomeCategoryList> {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Consumer(builder: (context, ref, _) {
final data = ref.watch(incomeCategoryProvider);
final permissionService = PermissionService(ref);
return GlobalPopup(
child: Scaffold(
backgroundColor: kWhite,
appBar: AppBar(
title: Text(
lang.S.of(context).incomeCategories,
),
iconTheme: const IconThemeData(color: Colors.black),
centerTitle: true,
backgroundColor: Colors.white,
elevation: 0.0,
),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Expanded(
flex: 3,
child: AppTextField(
textFieldType: TextFieldType.NAME,
decoration: InputDecoration(
hintText: lang.S.of(context).search,
prefixIcon: Icon(
Icons.search,
color: kGreyTextColor.withOpacity(0.5),
),
),
),
),
const SizedBox(
width: 10.0,
),
Expanded(
flex: 1,
child: GestureDetector(
onTap: () {
const AddIncomeCategory().launch(context);
},
child: Container(
padding: const EdgeInsets.only(left: 20.0, right: 20.0),
height: 48.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
border: Border.all(color: kBorderColor),
),
child: const Icon(
Icons.add,
color: kGreyTextColor,
),
),
),
),
],
),
const SizedBox(height: 10),
data.when(data: (data) {
if (!permissionService.hasPermission(Permit.incomeCategoriesRead.value)) {
return Center(child: PermitDenyWidget());
}
return Expanded(
child: ListView.builder(
physics: AlwaysScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: data.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Text(
data[index].categoryName ?? '',
style: theme.textTheme.titleMedium?.copyWith(
color: kGreyTextColor,
),
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: kBackgroundColor,
padding: EdgeInsets.symmetric(vertical: 5, horizontal: 12),
minimumSize: Size(
50,
25,
),
),
child: Text(
lang.S.of(context).select,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
//'Select',
onPressed: () {
// const AddExpense().launch(context);
Navigator.pop(
context,
data[index],
);
},
),
],
),
);
},
),
);
}, error: (error, stackTrace) {
return Text(error.toString());
}, loading: () {
return const CircularProgressIndicator();
})
],
),
),
),
);
});
}
}

View File

@@ -0,0 +1,349 @@
// import 'package:flutter/material.dart';
// import 'package:flutter_feather_icons/flutter_feather_icons.dart';
// import 'package:flutter_riverpod/flutter_riverpod.dart';
// import 'package:intl/intl.dart';
// import 'package:mobile_pos/Provider/profile_provider.dart';
// import 'package:mobile_pos/Screens/Income/Providers/all_income_provider.dart';
// import 'package:mobile_pos/Screens/Income/Providers/income_category_provider.dart';
// import 'package:mobile_pos/generated/l10n.dart' as lang;
// import 'package:nb_utils/nb_utils.dart';
//
// import '../../GlobalComponents/glonal_popup.dart';
// import '../../constant.dart';
// import '../../currency.dart';
// import '../../http_client/custome_http_client.dart';
// import '../../service/check_actions_when_no_branch.dart';
// import '../../widgets/empty_widget/_empty_widget.dart';
// import '../../service/check_user_role_permission_provider.dart';
// import 'add_income.dart';
//
// class IncomeList extends StatefulWidget {
// const IncomeList({super.key});
//
// static bool isDateInRange({
// required String? incomeDate,
// required DateTime fromDate,
// required DateTime toDate,
// }) {
// try {
// final parsedDate = DateTime.tryParse(incomeDate?.substring(0, 10) ?? '');
// if (parsedDate == null) return false;
// final toDateOnly = DateTime.parse(toDate.toString().substring(0, 10));
//
// final isAfterOrSameFrom = parsedDate.isAfter(fromDate) || parsedDate.isAtSameMomentAs(fromDate);
//
// final isBeforeOrSameTo = parsedDate.isBefore(toDateOnly) || parsedDate.isAtSameMomentAs(toDateOnly);
//
// return isAfterOrSameFrom && isBeforeOrSameTo;
// } catch (e) {
// return false;
// }
// }
//
// @override
// _IncomeListState createState() => _IncomeListState();
// }
//
// class _IncomeListState extends State<IncomeList> {
// final dateController = TextEditingController();
// TextEditingController fromDateTextEditingController = TextEditingController(text: DateFormat.yMMMd().format(DateTime(2021)));
// TextEditingController toDateTextEditingController = TextEditingController(text: DateFormat.yMMMd().format(DateTime.now()));
// DateTime fromDate = DateTime(2021);
// DateTime toDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);
// num totalExpense = 0;
//
// @override
// void dispose() {
// dateController.dispose();
// super.dispose();
// }
//
// bool _isRefreshing = false;
//
// Future<void> refreshData(WidgetRef ref) async {
// if (_isRefreshing) return;
// _isRefreshing = true;
//
// ref.refresh(incomeDurationProvider);
// ref.refresh(incomeCategoryProvider);
//
// await Future.delayed(const Duration(seconds: 1));
// _isRefreshing = false;
// }
//
// @override
// Widget build(BuildContext context) {
// totalExpense = 0;
// return Consumer(builder: (context, ref, __) {
// final incomeData = ref.watch(incomeProvider);
// final businessInfoData = ref.watch(businessInfoProvider);
// final permissionService = PermissionService(ref);
// return GlobalPopup(
// child: Scaffold(
// backgroundColor: kWhite,
// appBar: AppBar(
// title: Text(
// lang.S.of(context).incomeReport,
// ),
// iconTheme: const IconThemeData(color: Colors.black),
// centerTitle: true,
// backgroundColor: Colors.white,
// elevation: 0.0,
// ),
// body: RefreshIndicator(
// onRefresh: () => refreshData(ref),
// child: SingleChildScrollView(
// physics: const AlwaysScrollableScrollPhysics(),
// child: Padding(
// padding: const EdgeInsets.all(10.0),
// child: Column(
// children: [
// if (permissionService.hasPermission(Permit.incomesRead.value)) ...{
// Padding(
// padding: const EdgeInsets.only(right: 10.0, left: 10.0, top: 10, bottom: 10),
// child: Row(
// children: [
// Expanded(
// child: AppTextField(
// textFieldType: TextFieldType.NAME,
// readOnly: true,
// controller: fromDateTextEditingController,
// decoration: InputDecoration(
// floatingLabelBehavior: FloatingLabelBehavior.always,
// labelText: lang.S.of(context).fromDate,
// border: const OutlineInputBorder(),
// suffixIcon: IconButton(
// onPressed: () async {
// final DateTime? picked = await showDatePicker(
// initialDate: DateTime.now(),
// firstDate: DateTime(2015, 8),
// lastDate: DateTime(2101),
// context: context,
// );
// setState(() {
// fromDateTextEditingController.text = DateFormat.yMMMd().format(picked ?? DateTime.now());
// fromDate = picked!;
// totalExpense = 0;
// });
// },
// icon: const Icon(FeatherIcons.calendar),
// ),
// ),
// ),
// ),
// const SizedBox(width: 10),
// Expanded(
// child: AppTextField(
// textFieldType: TextFieldType.NAME,
// readOnly: true,
// controller: toDateTextEditingController,
// decoration: InputDecoration(
// floatingLabelBehavior: FloatingLabelBehavior.always,
// labelText: lang.S.of(context).toDate,
// border: const OutlineInputBorder(),
// suffixIcon: IconButton(
// onPressed: () async {
// final DateTime? picked = await showDatePicker(
// initialDate: toDate,
// firstDate: DateTime(2015, 8),
// lastDate: DateTime(2101),
// context: context,
// );
//
// setState(() {
// toDateTextEditingController.text = DateFormat.yMMMd().format(picked ?? DateTime.now());
// picked!.isToday ? toDate = DateTime.now() : toDate = picked;
// totalExpense = 0;
// });
// },
// icon: const Icon(FeatherIcons.calendar),
// ),
// ),
// ),
// ),
// ],
// ),
// ),
//
// ///__________expense_data_table____________________________________________
// Container(
// width: context.width(),
// height: 50,
// padding: const EdgeInsets.all(10),
// decoration: const BoxDecoration(color: kDarkWhite),
// child: Row(
// crossAxisAlignment: CrossAxisAlignment.center,
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// SizedBox(
// width: 130,
// child: Text(
// lang.S.of(context).incomeFor,
// ),
// ),
// SizedBox(
// width: 100,
// child: Text(lang.S.of(context).date),
// ),
// Container(
// alignment: Alignment.centerRight,
// width: 70,
// child: Text(lang.S.of(context).amount),
// )
// ],
// ),
// ),
//
// incomeData.when(data: (mainData) {
// if (mainData.isNotEmpty) {
// totalExpense = 0;
// for (var income in mainData) {
// final result = IncomeList.isDateInRange(
// incomeDate: income.incomeDate,
// fromDate: fromDate,
// toDate: toDate,
// );
// if (result) {
// totalExpense += income.amount ?? 0;
// }
// }
//
// return SizedBox(
// width: context.width(),
// child: ListView.builder(
// shrinkWrap: true,
// itemCount: mainData.length,
// physics: const NeverScrollableScrollPhysics(),
// itemBuilder: (BuildContext context, int index) {
// return Visibility(
// visible: IncomeList.isDateInRange(
// incomeDate: mainData[index].incomeDate ?? (mainData[index].createdAt ?? ''),
// fromDate: fromDate,
// toDate: toDate,
// ),
// child: Column(
// children: [
// Padding(
// padding: const EdgeInsets.all(10.0),
// child: Row(
// crossAxisAlignment: CrossAxisAlignment.center,
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// SizedBox(
// width: 130,
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// mainAxisAlignment: MainAxisAlignment.center,
// children: [
// Text(
// mainData[index].incomeFor ?? '',
// maxLines: 2,
// overflow: TextOverflow.ellipsis,
// ),
// const SizedBox(height: 5),
// Text(
// mainData[index].category?.categoryName ?? '',
// maxLines: 2,
// overflow: TextOverflow.ellipsis,
// style: const TextStyle(color: Colors.grey, fontSize: 11),
// ),
// ],
// ),
// ),
// SizedBox(
// width: 100,
// child: Text(
// DateTime.tryParse(mainData[index].incomeDate ?? '') == null
// ? ""
// : DateFormat.yMMMd().format(DateTime.parse(mainData[index].incomeDate ?? '')),
// ),
// ),
// Container(
// alignment: Alignment.centerRight,
// width: 70,
// child: Text("$currency${mainData[index].amount.toString()}"),
// )
// ],
// ),
// ),
// Container(
// height: 1,
// color: Colors.black12,
// )
// ],
// ),
// );
// },
// ),
// );
// } else {
// return Padding(
// padding: const EdgeInsets.all(20),
// child: Center(
// child: Text(lang.S.of(context).noData),
// ),
// );
// }
// }, error: (Object error, StackTrace? stackTrace) {
// return Text(error.toString());
// }, loading: () {
// return const Center(child: CircularProgressIndicator());
// }),
// } else
// Center(child: PermitDenyWidget()),
// ],
// ),
// ),
// ),
// ),
// bottomNavigationBar: Padding(
// padding: const EdgeInsets.all(10.0),
// child: Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// ///_________total______________________________________________
// if (permissionService.hasPermission(Permit.incomesRead.value))
// Container(
// height: 50,
// padding: const EdgeInsets.all(10),
// decoration: const BoxDecoration(color: kDarkWhite),
// child: Row(
// crossAxisAlignment: CrossAxisAlignment.center,
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Text(
// lang.S.of(context).totalIncome,
// ),
// Text('$currency$totalExpense')
// ],
// ),
// ),
// const SizedBox(height: 10),
//
// ///________button________________________________________________
// businessInfoData.when(data: (details) {
// return ElevatedButton(
// onPressed: () async {
// bool result = await checkActionWhenNoBranch(ref: ref, context: context);
// if (!result) {
// return;
// }
// const AddIncome().launch(context);
// },
// child: Text(lang.S.of(context).addIncome),
// );
// }, error: (e, stack) {
// return Text(e.toString());
// }, loading: () {
// return const Center(
// child: CircularProgressIndicator(),
// );
// })
// ],
// ),
// ),
// ),
// );
// });
// }
// }