pd-android-app/lib/screens/rd orders/rd_order_details_update.dart
saritabirare ff065bdc16 1) annaucement api integration done
2)Billto and shipTo api integration
2024-10-22 10:36:49 +05:30

768 lines
26 KiB
Dart

import 'package:cheminova/controller/rd_single_order_controller.dart';
import 'package:cheminova/models/rd_order_item_model.dart';
import 'package:cheminova/models/rd_placed_order_model.dart';
import 'package:cheminova/models/single_get_order_model.dart';
import 'package:cheminova/screens/rd%20orders/partial_processing_dialog_screen.dart';
import 'package:cheminova/screens/rd%20orders/rd_cancelled_screen.dart';
import 'package:cheminova/screens/rd%20orders/rd_processing_screen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../controller/cart_controller.dart';
import '../../controller/rd_get_order_controller.dart';
import '../../controller/rd_processing_order_controller.dart';
import '../../models/product_model1.dart';
import '../../utils/show_snackbar.dart';
class RdOrderDetailUpdateScreen extends StatefulWidget {
//final Product? productModel;
// PlacedOrderList and PlacedOrderModel are optional parameters passed to this screen
SingleGetOrderModel? placedOrderList;
final String orderId;
//final int orderIndex; // New parameter to receive the index
// PlacedOrderModel? placedOrderModel;
// Constructor for initializing the screen with placed order details
RdOrderDetailUpdateScreen({super.key,this.placedOrderList,required this.orderId});
@override
State<RdOrderDetailUpdateScreen> createState() =>
_RdOrderDetailUpdateScreenState();
}
class _RdOrderDetailUpdateScreenState
extends State<RdOrderDetailUpdateScreen> {
// Controllers for managing cart and placed orders
final RdSingleOrderController _getPlacedOrderController = Get.put(RdSingleOrderController());
final GetProductRDController _getProductRDController = Get.put(GetProductRDController());
final RDOrderPlacedController controller = Get.put(RDOrderPlacedController());
String? orderId;
final List<String> statusOptions = [
"new",
"pending",
"processing",
"dispatched",
"cancelled",
"delivered",
];
List<String> _statusList = ["new", "processing", "partial processing", "cancelled"]; // Default status list
// Define different status lists for different categories
final Map<String, List<String>> statusLists = {
"new": ["new", "processing", "partial processing", "cancelled"],
"pending": ["pending", "processing", "dispatched", "cancelled"],
"dispatched": ["dispatched", "delivered", "returned", "cancelled"],
"delivered": ["delivered", "returned", "cancelled"],
};
String selectedStatus = "new";
String _groupValue = "cheque";
// Function to format date from the API to a more readable format
// This function updates the dropdown list dynamically based on category selection
void updateStatusList(String category) {
setState(() {
_statusList = statusLists[category]!; // Update status list based on the selected category
selectedStatus = _statusList.first; // Set the default selection to the first item
});
}
String formatDate(String apiDate) {
// Parse the API date string into a DateTime object
DateTime parsedDate = DateTime.parse(apiDate).toLocal(); // Convert to local time
// Format the date and time according to your specified format
String formattedDate = DateFormat('EEE MMM dd yyyy').format(parsedDate);
return formattedDate; // Return the formatted date string
}
// Function to capitalize the first letter of a string
String capitalizeFirstLetter(String text) {
if (text.isEmpty) return text;
return text[0].toUpperCase() + text.substring(1).toLowerCase();
}
void _onPaymentModeChanged(String? value) {
setState(() {
_groupValue = value!;
});
_saveSelectedPaymentMode();
}
void _saveSelectedPaymentMode() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('selectedPaymentMode', _groupValue);
}
void _loadSelectedPaymentMode() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_groupValue = prefs.getString('selectedPaymentMode') ?? 'cheque';
});
}
// Function to collect unique order IDs and corresponding order details
Future<void> adduni()async {
final Set<String> uniqueOrderIds = {};
final List<SingleGetOrderModel> uniqueOrders = [];
// Loop through placed orders and add unique orders to the list
for (var order in _getPlacedOrderController.productRDOrderSingleList) {
if (uniqueOrderIds.add(order!.uniqueId.toString())) {
uniqueOrders.add(order);
}
}
final order = uniqueOrders[0];
// Combine product names, categories, and quantities into strings
final productNames = order.orderItem
?.map((item) => (item.name))
.join(', ');
final categotyName = order.orderItem
?.map((item) => (item.categoryName))
.join(', ');
final quantity = order.orderItem
?.map((item) => (item.quantity))
.join(', ');
}
@override
void initState() {
// TODO: implement initState
super.initState();
//getOrder1();
selectedStatus= widget.placedOrderList!.status ?? 'new';
// controller.fetchOrderItems(widget.placedOrderList!.id);
// if (widget.orderId.isNotEmpty) {
// _getPlacedOrderController.fetchAllOrdersAndSingleOrder().then((_) {
// if (_getPlacedOrderController.productRDOrderSingleList.isNotEmpty) {
// // Update the UI with the fetched order data
// setState(() {
// var order = _getPlacedOrderController.productRDOrderSingleList.first;
// selectedStatus = order.status ?? 'new';
// widget.placedOrderList = order; // Update the placed order details
// });
// }
// });
// }
}
Future<void> getOrder1() async {
final order = await _getPlacedOrderController.fetchAllOrdersAndSingleOrder();
if (_getPlacedOrderController.productRDOrderSingleList.isEmpty) {
print("No orders found.");
} else {
print(" New Orders fetched successfully");
}
setState(() {
});
}
void _showConfirmationDialog() {
String dialogTitle;
String dialogContent;
TextEditingController reasonController = TextEditingController();
// Set dialog title and content based on selected status
switch (selectedStatus) {
case "processing":
dialogTitle = "Update Order Status";
dialogContent = "Are you sure you want to update the status to processing?";
break;
case "partial processing":
dialogTitle = "Update to Partial Processing";
dialogContent = "Are you sure you want to update the status to 'Partial Processing'?";
break;
case "cancelled":
dialogTitle = "Cancellation Reason";
dialogContent = "Please provide a reason for cancelling the order:";
break;
default:
dialogTitle = "Update Order Status";
dialogContent = "Are you sure you want to update the status to '$selectedStatus'?";
break;
}
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(dialogTitle),
content: selectedStatus == "cancelled"
? Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(dialogContent),
SizedBox(height: 10),
TextField(
controller: reasonController,
decoration: InputDecoration(
labelText: 'Cancellation Reason',
border: OutlineInputBorder(),
),
),
],
)
: Text(dialogContent),
actions: [
TextButton(
onPressed: () async {
if (selectedStatus == "cancelled") {
// Ensure the reason is provided for cancellation
if (reasonController.text.isEmpty) {
showSnackbar("Please provide a reason for cancelling the order.");
return; // Exit early if reason is empty
}
// Proceed with cancellation
await controller.CancleRDProduct(widget.placedOrderList!.id, reasonController.text);
// Notify user about successful cancellation
showSnackbar("Order cancelled successfully");
Get.to(RdCancelledScreen());
// Update the status in your UI or backend to reflect the cancelled state
setState(() {
// Update the status in the local model/UI
});
// Close the dialog after a short delay
Future.delayed(Duration(seconds: 1), () {
// Navigator.of(context).pop(); // Close the dialog
});
return; // Exit here to prevent further processing
}
if (selectedStatus == "partial processing") {
Get.to(() => PartialProcessingDialogScreen(placedOrderList: widget.placedOrderList));
return;
}
// Create a map to track products by their IDs and aggregate quantities
Map<String, RDOrderItem> orderItemMap = {};
// Populate the map with items and their quantities
for (var item in _getProductRDController.productRDList) {
var productId = item.orderItem[0].productId;
if (orderItemMap.containsKey(productId)) {
// If the product already exists, aggregate the quantity
var existingItem = orderItemMap[productId]!;
existingItem.quantity = (existingItem.quantity ?? 0) + (item.orderItem[0].quantity ?? 0);
existingItem.remainingQuantity = (existingItem.remainingQuantity ?? 0) + (item.orderItem[0].remainingQuantity ?? 0);
existingItem.processquantity = (existingItem.processquantity ?? 0) + (item.orderItem[0].processquantity ?? 0);
} else {
// If it's a new product, add it to the map
orderItemMap[productId] = RDOrderItem(
productId: productId,
sku: item.orderItem[0].sku,
name: item.orderItem[0].name,
categoryName: item.orderItem[0].categoryName,
brandName: item.orderItem[0].brandName,
price: item.orderItem[0].price,
gst: item.orderItem[0].gst.toInt(),
hsnCode: item.orderItem[0].hsnCode,
description: item.orderItem[0].description,
image: [], // Handle images appropriately
quantity: item.orderItem[0].quantity ?? 0,
remainingQuantity: item.orderItem[0].remainingQuantity ?? 0,
processquantity: item.orderItem[0].processquantity ?? 0,
);
}
}
// Convert the map to a list
List<RDOrderItem> orderItems = orderItemMap.values.toList();
// Ensure the placed order contains the correct orderId and items
controller.placedOrder1.value = PlacedOrdersProcessing(
orderId: widget.placedOrderList!.id,
invoiceItems: orderItems,
);
// Debugging: Print the JSON payload
print("Sending order payload: ${controller.placedOrder1.value.toJson()}");
// Place the order and catch any errors
await controller.placeRDOrder();
showSnackbar("Order processed and invoice created successfully");
Get.to(RdOrderProcessingScreen());
Navigator.of(context).pop();
// Close the dialog after a short delay
// Close the dialog
// Refresh the UI// Refresh the UI
},
child: Text("Confirm"),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(); // Close the dialog
},
child: Text("Cancel"),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: GestureDetector(
onTap: () {},
child: Padding(
padding: const EdgeInsets.all(16.0),
child: SvgPicture.asset(
'assets/svg/menu.svg',
),
),
),
actions: [
GestureDetector(
onTap: () => Get.back(),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: SvgPicture.asset(
'assets/svg/back_arrow.svg',
),
),
),
],
title: const Text("Order Detail"),
),
body: Stack(
fit: StackFit.expand,
children: [
Image.asset(
'assets/images/image_1.png',
fit: BoxFit.cover,
),
SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(height: Get.height * 0.02),
Card(
margin: const EdgeInsets.symmetric(horizontal: 18),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(19),
side: const BorderSide(color: Color(0xFFFDFDFD)),
),
color: const Color(0xFFB4D1E5).withOpacity(0.9),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_buildOrderSummary(),
const SizedBox(height: 8),
_buildOrderItems(),
const SizedBox(height: 8),
_buildCustomerDetails(),
const SizedBox(height: 8),
_buildBillingInfo(),
const SizedBox(height: 8),
_buildShippingInfo(),
const SizedBox(height: 8),
_buildPaymentInfo(),
const SizedBox(height: 8),
_buildOrderStatus(),
const SizedBox(height: 8),
_buildStatusDropdown(),
_buildUpdateStatusButton(),
],
),
),
),
SizedBox(height: Get.height * 0.04),
],
),
),
),
],
),
);
}
Widget _buildOrderSummary() {
return Card(
child: Column(
children: [
SizedBox(
width: Get.width,
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
child: Text(
"Order Summary",
style: GoogleFonts.roboto(
fontSize: Get.width * 0.05,
fontWeight: FontWeight.bold,
),
),
),
),
_buildRow("Order ID:", widget.placedOrderList!.uniqueId ?? "44564", Get.width * 0.04),
_buildRow("Order Date:", formatDate("${widget.placedOrderList!.createdAt}"), Get.width * 0.04),
_buildRow("Total Items:", "${widget.placedOrderList!.orderItem!.length}", Get.width * 0.04),
_buildRow("Sub Total:", "${widget.placedOrderList!.subtotal}", Get.width * 0.04),
_buildRow("GST:", "${widget.placedOrderList!.gstTotal}", Get.width * 0.04),
_buildRow("Total Amount:", "${widget.placedOrderList!.grandTotal}", Get.width * 0.04),
],
),
);
}
Widget _buildOrderItems() {
return Card(
child: SizedBox(
height: Get.height * 0.22,
child: Padding(
padding: EdgeInsets.all(Get.width * 0.02),
child: ListView.builder(
padding: EdgeInsets.zero,
itemCount: widget.placedOrderList!.orderItem!.length ?? 0,
itemBuilder: (context, index) {
final orderItem = widget.placedOrderList!.orderItem![index];
final subTotalProcesssItem = orderItem.price! * orderItem.quantity!.toInt();
final GstTotalAmounProcessItem = (orderItem.price! * orderItem.quantity!.toInt()) *(orderItem.gst!/100 );
final grandTotalProcessItem = subTotalProcesssItem + GstTotalAmounProcessItem;
return orderItem != null
? Card(
margin: const EdgeInsets.symmetric(vertical: 5.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Image.asset(
"assets/images/product.png",
height: 50,
width: 50,
fit: BoxFit.cover,
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
capitalizeFirstLetter(orderItem.name),
style: GoogleFonts.roboto(
fontSize: Get.width * 0.04,
fontWeight: FontWeight.bold,
),
),
Text(
"Quantity: ${orderItem.quantity}",
style: GoogleFonts.roboto(
fontSize: Get.width * 0.03,
),
),
Text("Price: ${orderItem.price}"),
Text("Subtotal : ${subTotalProcesssItem}"),
Text("GST : ${orderItem.gst}%"),
Text("GST Amount (₹) : ${GstTotalAmounProcessItem}"),
Text("Total Amount : ${grandTotalProcessItem}"),
],
),
),
],
),
),
)
: const SizedBox.shrink();
},
),
),
),
);
}
Widget _buildCustomerDetails() {
return Card(
child: Column(
children: [
_buildSectionTitle("Customer Details"),
_buildRow("Name:", widget.placedOrderList!.addedBy!.name, Get.width * 0.04),
_buildRow("Email:", widget.placedOrderList!.addedBy!.email, Get.width * 0.04),
_buildRow("Mobile Number:", widget.placedOrderList!.addedBy!.mobileNumber, Get.width * 0.04),
],
),
);
}
Widget _buildBillingInfo() {
return Card(
child: Column(
children: [
_buildSectionTitle("Billing Information"),
_buildInfoRow("Address", widget.placedOrderList!.billTo.toString(), Get.width * 0.04),
],
),
);
}
Widget _buildShippingInfo() {
return Card(
child: Column(
children: [
_buildSectionTitle("Shipping Information"),
_buildInfoRow("Address", widget.placedOrderList!.shipTo.toString(), Get.width * 0.04),
],
),
);
}
Widget _buildPaymentInfo() {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Text(
"Payment Mode: ",
style: GoogleFonts.roboto(
fontSize: Get.width * 0.04,
fontWeight: FontWeight.w500,
),
),
Text(capitalizeFirstLetter(widget.placedOrderList!.paymentMode.toString())),
],
),
),
);
}
Widget _buildOrderStatus() {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Text(
"Order Status: ",
style: GoogleFonts.roboto(
fontSize: Get.width * 0.04,
fontWeight: FontWeight.w500,
),
),
Text(capitalizeFirstLetter(selectedStatus)),
],
),
),
);
}
Widget _buildStatusDropdown() {
return SizedBox(
height: Get.height * 0.05,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
"Status: ",
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(width: 10),
Expanded(
child: DropdownButtonFormField<String>(
value: selectedStatus,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: Colors.grey, width: 1),
),
),
items: _statusList.map((String status) {
return DropdownMenuItem<String>(
value: status,
child: Text(capitalizeFirstLetter(status)),
);
}).toList(),
onChanged: (newValue) {
setState(() {
selectedStatus = newValue!;
});
},
),
),
],
),
);
}
Widget _buildUpdateStatusButton() {
if (selectedStatus == "processing" || selectedStatus == "partial processing" || selectedStatus == "cancelled") {
return SizedBox(
width: Get.width * 0.4,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: _showConfirmationDialog,
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: const Color(0xFF004791),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
child: Text(
"Update Status",
style: GoogleFonts.roboto(fontSize: 14, fontWeight: FontWeight.w400),
),
),
),
);
}
return const SizedBox.shrink();
}
Widget _buildSectionTitle(String title) {
return SizedBox(
width: Get.width,
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
child: Text(
title,
style: GoogleFonts.roboto(fontSize: Get.width * 0.05, fontWeight: FontWeight.bold),
),
),
);
}
Widget _buildRow(String label, String value, double fontSize) {
return Padding(
padding: const EdgeInsets.fromLTRB(8, 2, 8, 2),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
label,
style: GoogleFonts.roboto(fontSize: fontSize,fontWeight: FontWeight.bold),
),
Text(
value,
style: GoogleFonts.roboto(fontSize: fontSize),
),
],
),
);
}
Widget _buildInfoRow(String label, String value, double fontSize) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"$label: ",
style: GoogleFonts.roboto(fontSize: fontSize, fontWeight: FontWeight.w500),
),
Expanded(
child: Text(
value,
style: GoogleFonts.roboto(fontSize: fontSize),
),
),
],
),
);
}
}
Widget _buildRow(String label, String value, double fontSize) {
return SizedBox(
width: Get.width,
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
label,
style: GoogleFonts.roboto(
fontSize: fontSize,
fontWeight: FontWeight.bold,
),
),
Text(value),
],
),
),
);
}
Widget _buildInfoRow(String label, String value, double fontSize) {
return SizedBox(
width: Get.width,
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
child: Row(
children: [
Text(
"$label ",
style: GoogleFonts.roboto(
fontSize: fontSize,
fontWeight: FontWeight.bold,
),
),
Expanded(
child: Text(
value,
maxLines: 4,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
);
}