first commit

This commit is contained in:
Hamza-Ayed
2025-07-30 10:24:53 +03:00
parent 0945095398
commit 0b17f93aaa
244 changed files with 40043 additions and 0 deletions

View File

@@ -0,0 +1,187 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:sefer_admin1/constant/colors.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/views/widgets/my_scafold.dart';
import 'package:sefer_admin1/views/widgets/my_textField.dart';
import '../../constant/box_name.dart';
import '../../constant/info.dart';
import '../../controller/functions/encrypt_decrypt.dart';
import '../../main.dart';
class AddInvoicePage extends StatefulWidget {
const AddInvoicePage({super.key});
@override
State<AddInvoicePage> createState() => _AddInvoicePageState();
}
class _AddInvoicePageState extends State<AddInvoicePage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController _itemNameController = TextEditingController();
final TextEditingController _amountController = TextEditingController();
File? _imageFile;
bool _isLoading = false;
String generateInvoiceNumber() {
final now = DateTime.now();
return "INV-${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}-${now.microsecond}";
}
Future<void> uploadInvoice() async {
if (!_formKey.currentState!.validate()) return;
final driverID = '123'; // ← عدّله حسب نظامك
final invoiceNumber = generateInvoiceNumber();
final amount = _amountController.text.trim();
final date = DateTime.now().toIso8601String().split('T').first;
setState(() => _isLoading = true);
try {
final headers = {
'Authorization':
'Bearer ${r(box.read(BoxName.jwt)).split(AppInformation.addd)[0]}',
'X-HMAC-Auth': '${box.read(BoxName.hmac)}',
};
final uri = Uri.parse(AppLink.addInvoice);
final request = http.MultipartRequest('POST', uri)
..fields['driverID'] = driverID
..fields['invoiceNumber'] = invoiceNumber
..fields['amount'] = amount
..fields['date'] = date
..headers.addAll(headers);
if (_imageFile != null) {
final imageName = _imageFile!.path.split('/').last;
final imageStream = http.ByteStream(_imageFile!.openRead());
final imageLength = await _imageFile!.length();
request.files.add(http.MultipartFile(
'image',
imageStream,
imageLength,
filename: imageName,
));
} else {}
final response = await request.send();
final respStr = await response.stream.bytesToString();
final data = jsonDecode(respStr);
if (data['status'] == 'success') {
Get.snackbar('تم الحفظ', 'تم حفظ الفاتورة بنجاح',
backgroundColor: Colors.green.shade100);
_itemNameController.clear();
_amountController.clear();
setState(() => _imageFile = null);
Get.back(); // العودة للصفحة السابقة
} else {
Get.snackbar('خطأ', data['message'],
backgroundColor: Colors.red.shade100);
}
} catch (e, stacktrace) {
Get.snackbar('فشل الإرسال', e.toString(),
backgroundColor: Colors.red.shade100);
} finally {
setState(() => _isLoading = false);
}
}
Future<void> pickInvoiceImage() async {
final picker = ImagePicker();
final picked = await picker.pickImage(source: ImageSource.gallery);
if (picked != null) {
setState(() => _imageFile = File(picked.path));
}
}
@override
void dispose() {
_itemNameController.dispose();
_amountController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MyScafolld(
title: 'إضافة فاتورة جديدة',
body: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: ListView(
children: [
MyTextForm(
controller: _itemNameController,
label: 'اسم البضاعة',
hint: 'مثال: قطع غيار',
type: TextInputType.text,
// validator: (val) =>
// val!.isEmpty ? 'الرجاء إدخال اسم البضاعة' : null,
),
const SizedBox(height: 16),
MyTextForm(
controller: _amountController,
label: 'قيمة الفاتورة',
hint: 'مثال: 150.75',
type: TextInputType.numberWithOptions(decimal: true),
// validator: (val) =>
// val!.isEmpty ? 'الرجاء إدخال المبلغ' : null,
),
const SizedBox(height: 20),
Text('صورة الفاتورة (اختياري)',
style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 10),
Container(
height: 180,
decoration: BoxDecoration(
color: Colors.grey.shade200,
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(10),
),
child: _imageFile != null
? ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.file(_imageFile!, fit: BoxFit.cover),
)
: const Center(child: Text('لم يتم اختيار صورة')),
),
const SizedBox(height: 12),
ElevatedButton.icon(
onPressed: pickInvoiceImage,
icon: const Icon(Icons.image),
label: const Text('اختيار صورة'),
),
const SizedBox(height: 30),
ElevatedButton(
onPressed: _isLoading ? null : uploadInvoice,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: AppColor.primaryColor,
),
child: _isLoading
? const CircularProgressIndicator(color: Colors.white)
: const Text(
'حفظ الفاتورة',
style: TextStyle(color: Colors.white),
),
),
],
),
),
),
],
isleading: true,
);
}
}

View File

@@ -0,0 +1,280 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../../constant/links.dart';
import '../../controller/admin/get_all_invoice_controller.dart';
import '../../controller/functions/crud.dart';
import '../../print.dart';
import 'add_invoice_page.dart';
class InvoiceListPage extends StatefulWidget {
@override
_InvoiceListPageState createState() => _InvoiceListPageState();
}
class _InvoiceListPageState extends State<InvoiceListPage> {
List<InvoiceModel> invoices = [];
int totalCount = 0;
double totalAmount = 0.0;
bool isLoading = true;
@override
void initState() {
super.initState();
fetchInvoices();
}
Future<void> fetchInvoices() async {
// لإظهار مؤشر التحديث بشكل جيد
if (!isLoading) {
setState(() {});
}
final response = await CRUD().post(link: AppLink.getInvoices, payload: {});
final data = (response);
Log.print('data: $data');
if (mounted) {
if (data != 'failure' && data['status'] == 'success') {
setState(() {
invoices = List.from(data['data'])
.map((item) => InvoiceModel.fromJson(item))
.toList();
totalCount = data['summary']['count'];
totalAmount =
double.tryParse(data['summary']['total'].toString()) ?? 0.0;
isLoading = false;
});
} else {
setState(() {
isLoading = false;
});
Get.snackbar("خطأ", "فشل في تحميل الفواتير. حاول التحديث مرة أخرى.",
backgroundColor: Colors.red.withOpacity(0.8),
colorText: Colors.white);
}
}
}
// --- دالة لعرض الصورة في نافذة منبثقة ---
void _showImageDialog(BuildContext context, String imageUrl) {
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
child: GestureDetector(
// لإغلاق الصورة عند الضغط عليها
onTap: () => Navigator.of(context).pop(),
child: Container(
padding: EdgeInsets.all(12),
child: InteractiveViewer(
// لإتاحة التكبير والتصغير
panEnabled: true,
minScale: 0.5,
maxScale: 4,
child: Image.network(
imageUrl,
fit: BoxFit.contain,
// إظهار مؤشر تحميل أثناء جلب الصورة
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
);
},
// إظهار أيقونة خطأ في حال فشل تحميل الصورة
errorBuilder: (context, error, stackTrace) {
return Icon(Icons.broken_image,
size: 100, color: Colors.red);
},
),
),
),
),
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("قائمة الفواتير"),
centerTitle: true,
elevation: 2,
actions: [
IconButton(
icon: Icon(Icons.add_a_photo),
onPressed: () {
// يمكنك إضافة إجراء الطباعة هنا
Get.to(() => AddInvoicePage());
},
),
],
),
body: isLoading
? Center(child: CircularProgressIndicator())
: RefreshIndicator(
onRefresh: fetchInvoices, // خاصية السحب للتحديث
child: Column(
children: [
Expanded(
child: ListView.builder(
padding:
EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0),
itemCount: invoices.length,
itemBuilder: (context, index) {
final invoice = invoices[index];
return Card(
elevation: 4,
margin: EdgeInsets.symmetric(vertical: 8.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: InkWell(
borderRadius: BorderRadius.circular(15.0),
onTap: () {
// التحقق من وجود رابط للصورة قبل محاولة عرضه
if (invoice.imageLink != null &&
invoice.imageLink!.isNotEmpty) {
_showImageDialog(context, invoice.imageLink!);
} else {
Get.snackbar("لا توجد صورة",
"هذه الفاتورة لا تحتوي على صورة مرفقة.");
}
},
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
children: [
// أيقونة الفاتورة الرئيسية
Icon(Icons.receipt_long,
color: Theme.of(context).primaryColor,
size: 40),
SizedBox(width: 16),
// تفاصيل الفاتورة
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
"فاتورة رقم: ${invoice.invoiceNumber}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
SizedBox(height: 8),
Text(
"الاسم: ${invoice.name}",
style: TextStyle(
color: Colors.green.shade700,
fontWeight: FontWeight.w500,
),
),
SizedBox(height: 8),
Text(
"المبلغ: ${invoice.amount} د.أ",
style: TextStyle(
color: Colors.green.shade700,
fontWeight: FontWeight.w500,
),
),
SizedBox(height: 4),
Text(
"التاريخ: ${invoice.date}",
style: TextStyle(
color: Colors.grey.shade600,
fontSize: 12,
),
),
],
),
),
// أيقونة توضح وجود صورة
if (invoice.imageLink != null &&
invoice.imageLink!.isNotEmpty)
Icon(Icons.image_outlined,
color: Colors.blueAccent, size: 30),
],
),
),
),
);
},
),
),
_buildSummaryCard(), // بطاقة الملخص السفلية
],
),
),
);
}
Widget _buildSummaryCard() {
return Card(
margin: EdgeInsets.all(0),
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
child: Container(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"إجمالي الفواتير",
style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
),
Text(
"$totalCount",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
"المبلغ الإجمالي",
style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
),
Text(
"${totalAmount.toStringAsFixed(2)} د.أ",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.green.shade800,
),
),
],
),
],
),
),
);
}
}