first commit
This commit is contained in:
253
lib/Screens/product racks/add_edit_racks_screen.dart
Normal file
253
lib/Screens/product racks/add_edit_racks_screen.dart
Normal file
@@ -0,0 +1,253 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:mobile_pos/Screens/product%20racks/repo/product_racks_repo.dart';
|
||||
import 'package:mobile_pos/generated/l10n.dart' as lang;
|
||||
import '../../constant.dart';
|
||||
import '../shelfs/model/shelf_list_model.dart';
|
||||
import '../shelfs/provider/shelf_provider.dart';
|
||||
import 'model/product_racks_model.dart';
|
||||
|
||||
class AddEditRack extends ConsumerStatefulWidget {
|
||||
final bool isEdit;
|
||||
final RackData? rack;
|
||||
|
||||
const AddEditRack({super.key, this.isEdit = false, this.rack});
|
||||
|
||||
@override
|
||||
ConsumerState<AddEditRack> createState() => _AddEditRackState();
|
||||
}
|
||||
|
||||
class _AddEditRackState extends ConsumerState<AddEditRack> {
|
||||
final GlobalKey<FormState> _key = GlobalKey<FormState>();
|
||||
final TextEditingController nameController = TextEditingController();
|
||||
|
||||
List<ShelfData> _selectedShelves = []; // List of selected shelves (full data)
|
||||
String? _selectedStatus;
|
||||
|
||||
final List<String> _statusOptions = ['Active', 'Inactive'];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (widget.isEdit && widget.rack != null) {
|
||||
final data = widget.rack!;
|
||||
nameController.text = data.name ?? '';
|
||||
_selectedStatus = (data.status == 1 || data.status == 'Active') ? 'Active' : 'Inactive';
|
||||
|
||||
// NOTE: _selectedShelves will be populated in build after shelfListAsync loads.
|
||||
} else {
|
||||
_selectedStatus = 'Active';
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
nameController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// --- Submission Logic ---
|
||||
Future<void> _submit() async {
|
||||
if (!_key.currentState!.validate()) return;
|
||||
|
||||
final repo = RackRepo();
|
||||
final String apiStatus = _selectedStatus == 'Active' ? '1' : '0';
|
||||
|
||||
// Extract list of IDs from selected ShelfData objects
|
||||
final List<num> shelfIds = _selectedShelves.map((s) => s.id ?? 0).toList();
|
||||
|
||||
if (shelfIds.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Please select at least one Shelf.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (widget.isEdit) {
|
||||
await repo.updateRack(
|
||||
ref: ref,
|
||||
context: context,
|
||||
id: widget.rack!.id!.round(),
|
||||
name: nameController.text,
|
||||
shelfIds: shelfIds,
|
||||
status: apiStatus,
|
||||
);
|
||||
} else {
|
||||
await repo.createRack(
|
||||
ref: ref,
|
||||
context: context,
|
||||
name: nameController.text,
|
||||
shelfIds: shelfIds,
|
||||
status: apiStatus,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Reset Logic ---
|
||||
void _resetForm() {
|
||||
if (widget.isEdit) {
|
||||
Navigator.pop(context);
|
||||
} else {
|
||||
setState(() {
|
||||
_key.currentState?.reset();
|
||||
nameController.clear();
|
||||
_selectedStatus = 'Active';
|
||||
_selectedShelves = [];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Helper widget to display selected shelves as chips (matching screenshot)
|
||||
Widget _buildShelfChip(ShelfData shelf) {
|
||||
return Chip(
|
||||
label: Text(shelf.name ?? 'N/A'),
|
||||
backgroundColor: kMainColor.withOpacity(0.1),
|
||||
labelStyle: const TextStyle(color: kMainColor),
|
||||
deleteIcon: const Icon(Icons.close, size: 16),
|
||||
onDeleted: () {
|
||||
setState(() {
|
||||
_selectedShelves.removeWhere((s) => s.id == shelf.id);
|
||||
});
|
||||
_key.currentState?.validate(); // Re-validate after removal
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final shelfListAsync = ref.watch(shelfListProvider);
|
||||
final _lang = lang.S.of(context);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.white,
|
||||
appBar: AppBar(
|
||||
centerTitle: true,
|
||||
title: Text(widget.isEdit ? _lang.editRack : _lang.addNewRack),
|
||||
actions: [IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close))],
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Form(
|
||||
key: _key,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// 1. Rack Name Input
|
||||
TextFormField(
|
||||
controller: nameController,
|
||||
decoration: InputDecoration(labelText: _lang.rackName, hintText: _lang.enterName),
|
||||
validator: (value) => value!.isEmpty ? _lang.pleaseEnterRackName : null,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 2. Shelves Multi-Select Dropdown (Dynamic)
|
||||
shelfListAsync.when(
|
||||
loading: () => const LinearProgressIndicator(),
|
||||
error: (err, stack) => Text('Shelf List Error: $err'),
|
||||
data: (shelfModel) {
|
||||
final allShelves = shelfModel.data ?? [];
|
||||
|
||||
// FIX: Populate _selectedShelves on first load if editing
|
||||
if (widget.isEdit && widget.rack!.shelves != null && _selectedShelves.isEmpty) {
|
||||
final currentShelfIds = widget.rack!.shelves!.map((s) => s.id).toSet();
|
||||
// Map Shelf (nested model) back to ShelfData (provider model) for consistency
|
||||
_selectedShelves = allShelves.where((s) => currentShelfIds.contains(s.id)).toList();
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(_lang.shelves, style: Theme.of(context).textTheme.bodyLarge),
|
||||
const SizedBox(height: 8),
|
||||
// Display selected items as chips
|
||||
Wrap(
|
||||
spacing: 8.0,
|
||||
runSpacing: 4.0,
|
||||
children: _selectedShelves.map(_buildShelfChip).toList(),
|
||||
),
|
||||
|
||||
// Custom Dropdown Button for selection
|
||||
DropdownButtonFormField<ShelfData>(
|
||||
decoration: InputDecoration(
|
||||
hintText: _lang.pressToSelect,
|
||||
contentPadding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 12.0),
|
||||
),
|
||||
value: null,
|
||||
icon: const Icon(Icons.keyboard_arrow_down),
|
||||
validator: (_) => _selectedShelves.isEmpty ? _lang.selectAtLeastOneRack : null,
|
||||
items: allShelves.map((ShelfData shelf) {
|
||||
final isSelected = _selectedShelves.any((s) => s.id == shelf.id);
|
||||
return DropdownMenuItem<ShelfData>(
|
||||
value: shelf,
|
||||
enabled: !isSelected,
|
||||
child: Text(shelf.name ?? 'N/A',
|
||||
style: TextStyle(color: isSelected ? Colors.grey : Colors.black)),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (ShelfData? newShelf) {
|
||||
if (newShelf != null && !_selectedShelves.any((s) => s.id == newShelf.id)) {
|
||||
setState(() {
|
||||
_selectedShelves.add(newShelf);
|
||||
});
|
||||
}
|
||||
_key.currentState?.validate();
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 3. Status Dropdown
|
||||
DropdownButtonFormField<String>(
|
||||
value: _selectedStatus,
|
||||
icon: const Icon(Icons.keyboard_arrow_down, color: kNeutral800),
|
||||
decoration: InputDecoration(labelText: _lang.status, hintText: _lang.selectOne),
|
||||
items: [
|
||||
DropdownMenuItem(value: 'Active', child: Text(_lang.active)),
|
||||
DropdownMenuItem(value: 'Inactive', child: Text(_lang.inactive)),
|
||||
],
|
||||
// items:
|
||||
// _statusOptions.map((String value) => DropdownMenuItem(value: value, child: Text(value))).toList(),
|
||||
onChanged: (String? newValue) {
|
||||
setState(() => _selectedStatus = newValue);
|
||||
},
|
||||
validator: (value) => value == null ? _lang.pleaseSelectAStatus : null,
|
||||
),
|
||||
const SizedBox(height: 30),
|
||||
|
||||
// 4. Action Buttons (Reset/Save)
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: _resetForm,
|
||||
style: OutlinedButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 50),
|
||||
side: const BorderSide(color: Colors.red),
|
||||
foregroundColor: Colors.red,
|
||||
),
|
||||
child: Text(_lang.resets),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: ElevatedButton(
|
||||
onPressed: _submit,
|
||||
style: ElevatedButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 50),
|
||||
backgroundColor: const Color(0xFFB71C1C),
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
child: Text(widget.isEdit ? _lang.update : _lang.save),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
57
lib/Screens/product racks/model/product_racks_model.dart
Normal file
57
lib/Screens/product racks/model/product_racks_model.dart
Normal file
@@ -0,0 +1,57 @@
|
||||
// File: product_rack_model.dart (Updated with actual API structure)
|
||||
|
||||
class RackListModel {
|
||||
RackListModel({
|
||||
this.message,
|
||||
this.data,
|
||||
});
|
||||
|
||||
RackListModel.fromJson(dynamic json) {
|
||||
message = json['message'];
|
||||
if (json['data'] != null) {
|
||||
data = [];
|
||||
json['data'].forEach((v) {
|
||||
data?.add(RackData.fromJson(v));
|
||||
});
|
||||
}
|
||||
}
|
||||
String? message;
|
||||
List<RackData>? data;
|
||||
}
|
||||
|
||||
class RackData {
|
||||
RackData({
|
||||
this.id,
|
||||
this.name,
|
||||
this.status,
|
||||
this.shelves, // List of Shelf objects (for reading/display)
|
||||
});
|
||||
|
||||
RackData.fromJson(dynamic json) {
|
||||
id = json['id'];
|
||||
name = json['name'];
|
||||
status = json['status'];
|
||||
|
||||
// Process the nested 'shelves' list
|
||||
if (json['shelves'] is List) {
|
||||
shelves = (json['shelves'] as List).map((e) => Shelf.fromJson(e)).toList();
|
||||
}
|
||||
}
|
||||
num? id;
|
||||
String? name;
|
||||
dynamic status;
|
||||
List<Shelf>? shelves; // For UI display
|
||||
}
|
||||
|
||||
// Model for the nested Shelf objects returned inside a Rack
|
||||
class Shelf {
|
||||
Shelf({this.id, this.name});
|
||||
|
||||
// NOTE: We ignore the 'pivot' field in the model as it's not needed for UI/submission
|
||||
Shelf.fromJson(dynamic json) {
|
||||
id = json['id'];
|
||||
name = json['name'];
|
||||
}
|
||||
num? id;
|
||||
String? name;
|
||||
}
|
||||
259
lib/Screens/product racks/product_racks_list.dart
Normal file
259
lib/Screens/product racks/product_racks_list.dart
Normal file
@@ -0,0 +1,259 @@
|
||||
// File: product_rack_list_screen.dart (Rack List)
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_easyloading/flutter_easyloading.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:hugeicons/hugeicons.dart';
|
||||
import 'package:mobile_pos/Screens/product%20racks/provider/product_recks_provider.dart';
|
||||
import 'package:mobile_pos/Screens/product%20racks/repo/product_racks_repo.dart';
|
||||
import 'package:nb_utils/nb_utils.dart'; // For .launch()
|
||||
|
||||
// --- Local Imports ---
|
||||
import 'package:mobile_pos/constant.dart';
|
||||
import 'package:mobile_pos/generated/l10n.dart' as lang;
|
||||
import '../../GlobalComponents/glonal_popup.dart';
|
||||
import '../../service/check_user_role_permission_provider.dart';
|
||||
import '../../widgets/empty_widget/_empty_widget.dart';
|
||||
import '../hrm/widgets/deleteing_alart_dialog.dart';
|
||||
import '../hrm/widgets/global_search_appbar.dart';
|
||||
import '../product_category/product_category_list_screen.dart';
|
||||
import 'add_edit_racks_screen.dart';
|
||||
import 'model/product_racks_model.dart'; // Assuming GlobalSearchAppBar exists
|
||||
|
||||
class ProductRackList extends ConsumerStatefulWidget {
|
||||
const ProductRackList({super.key, required this.isFromProductList});
|
||||
|
||||
final bool isFromProductList;
|
||||
|
||||
@override
|
||||
ConsumerState<ProductRackList> createState() => _ProductRackListState();
|
||||
}
|
||||
|
||||
class _ProductRackListState extends ConsumerState<ProductRackList> {
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
List<RackData> _filteredList = [];
|
||||
bool _isSearch = false;
|
||||
String search = ''; // Used for searching the list
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_searchController.addListener(_onSearchChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchController.removeListener(_onSearchChanged);
|
||||
_searchController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onSearchChanged() {
|
||||
setState(() {
|
||||
search = _searchController.text;
|
||||
});
|
||||
}
|
||||
|
||||
void _filterRacks(List<RackData> allRacks) {
|
||||
final query = search.toLowerCase().trim();
|
||||
if (query.isEmpty) {
|
||||
_filteredList = allRacks;
|
||||
} else {
|
||||
_filteredList = allRacks.where((rack) {
|
||||
final nameMatch = (rack.name ?? '').toLowerCase().contains(query);
|
||||
final shelfNames = (rack.shelves ?? []).map((s) => s.name).join(', ').toLowerCase();
|
||||
|
||||
return nameMatch || shelfNames.contains(query);
|
||||
}).toList();
|
||||
}
|
||||
}
|
||||
|
||||
String _getStatusText(dynamic status) {
|
||||
if (status == 1 || status == '1' || status?.toLowerCase() == 'active') return 'Active';
|
||||
return 'Inactive';
|
||||
}
|
||||
|
||||
Color _getStatusColor(dynamic status) {
|
||||
if (status == 1 || status == '1' || status?.toLowerCase() == 'active') return kSuccessColor;
|
||||
return Colors.red;
|
||||
}
|
||||
|
||||
Future<void> _refreshData() async {
|
||||
ref.invalidate(rackListProvider);
|
||||
return ref.watch(rackListProvider.future);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// NOTE: Using GlobalSearchAppBar from your Holiday/Department List structure
|
||||
// If you prefer the old BrandList structure (TextField inside the body),
|
||||
// you'll need to adapt the GlobalSearchAppBar part below.
|
||||
final _lang = lang.S.of(context);
|
||||
|
||||
return GlobalPopup(
|
||||
child: Scaffold(
|
||||
backgroundColor: kWhite,
|
||||
appBar: AppBar(
|
||||
title: Text(_lang.productRacks),
|
||||
iconTheme: const IconThemeData(color: Colors.black),
|
||||
centerTitle: true,
|
||||
backgroundColor: Colors.white,
|
||||
elevation: 0.0,
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
child: Consumer(builder: (context, ref, __) {
|
||||
final rackDataAsync = ref.watch(rackListProvider);
|
||||
// Assuming businessInfoProvider and Permit enum are accessible
|
||||
final permissionService = PermissionService(ref);
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: AppTextField(
|
||||
// Assuming AppTextField is similar to TextFormField
|
||||
textFieldType: TextFieldType.NAME,
|
||||
decoration: InputDecoration(
|
||||
border: const OutlineInputBorder(),
|
||||
hintText: lang.S.of(context).search,
|
||||
prefixIcon: Icon(
|
||||
Icons.search,
|
||||
color: kGreyTextColor.withOpacity(0.5),
|
||||
),
|
||||
),
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
search = value;
|
||||
_onSearchChanged(); // Manually trigger search update
|
||||
});
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10.0),
|
||||
// Add Button
|
||||
Expanded(
|
||||
flex: 1,
|
||||
child: GestureDetector(
|
||||
onTap: () async {
|
||||
// NOTE: Replace 'rack_create_permit' with your actual Permit.value
|
||||
if (!permissionService.hasPermission('rack_create_permit')) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
backgroundColor: Colors.red,
|
||||
content: Text(_lang.youDoNtHavePermissionToCreateRacks)));
|
||||
return;
|
||||
}
|
||||
const AddEditRack().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: kGreyTextColor),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.add,
|
||||
color: kGreyTextColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// Rack Data List Loading and Display
|
||||
rackDataAsync.when(
|
||||
data: (model) {
|
||||
final allRacks = model.data ?? [];
|
||||
// Apply Search Filtering
|
||||
_filterRacks(allRacks);
|
||||
|
||||
// NOTE: Replace 'rack_read_permit' with your actual Permit.value
|
||||
if (!permissionService.hasPermission('rack_read_permit')) {
|
||||
return const Center(child: PermitDenyWidget());
|
||||
}
|
||||
|
||||
return _filteredList.isNotEmpty
|
||||
? ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: _filteredList.length,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemBuilder: (context, i) {
|
||||
final rack = _filteredList[i];
|
||||
return ListCardWidget(
|
||||
// OnSelect action depends on context (e.g., selecting for product creation)
|
||||
onSelect: widget.isFromProductList ? () => Navigator.pop(context, rack) : () {},
|
||||
title: rack.name ?? 'N/A Rack',
|
||||
// subtitle: 'Shelves: ${(rack.shelves ?? []).map((s) => s.name).join(', ')}',
|
||||
|
||||
// Delete Action
|
||||
onDelete: () async {
|
||||
// NOTE: Replace 'rack_delete_permit' with your actual Permit.value
|
||||
if (!permissionService.hasPermission('rack_delete_permit')) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
backgroundColor: Colors.red,
|
||||
content: Text(_lang.youDoNtHavePermissionToDeleteRacks)));
|
||||
return;
|
||||
}
|
||||
|
||||
bool confirmDelete =
|
||||
await showDeleteConfirmationDialog(context: context, itemName: 'rack');
|
||||
if (confirmDelete) {
|
||||
EasyLoading.show();
|
||||
if (await RackRepo().deleteRack(context: context, id: rack.id ?? 0, ref: ref)) {
|
||||
ref.refresh(rackListProvider);
|
||||
}
|
||||
EasyLoading.dismiss();
|
||||
}
|
||||
},
|
||||
|
||||
// Edit Action
|
||||
onEdit: () async {
|
||||
// NOTE: Replace 'rack_update_permit' with your actual Permit.value
|
||||
if (!permissionService.hasPermission('rack_update_permit')) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
backgroundColor: Colors.red,
|
||||
content: Text(_lang.youDoNtHavePermissionToUpdateRacks)));
|
||||
return;
|
||||
}
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => AddEditRack(
|
||||
isEdit: true,
|
||||
rack: rack,
|
||||
),
|
||||
));
|
||||
},
|
||||
);
|
||||
})
|
||||
: Padding(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: Text(
|
||||
search.isEmpty ? lang.S.of(context).noDataFound : _lang.notMatchingResultFound,
|
||||
),
|
||||
);
|
||||
},
|
||||
error: (e, __) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: Text('Error loading data: ${e.toString()}'),
|
||||
);
|
||||
},
|
||||
loading: () {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../model/product_racks_model.dart';
|
||||
import '../repo/product_racks_repo.dart';
|
||||
|
||||
final repo = RackRepo();
|
||||
final rackListProvider = FutureProvider<RackListModel>((ref) => repo.fetchAllRacks());
|
||||
208
lib/Screens/product racks/repo/product_racks_repo.dart
Normal file
208
lib/Screens/product racks/repo/product_racks_repo.dart
Normal file
@@ -0,0 +1,208 @@
|
||||
// File: rack_repo.dart
|
||||
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_easyloading/flutter_easyloading.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
// --- Local Imports ---
|
||||
import '../../../../Const/api_config.dart';
|
||||
import '../../../../http_client/custome_http_client.dart'; // YOUR CUSTOM HTTP CLIENT
|
||||
import '../../../../http_client/customer_http_client_get.dart';
|
||||
import '../model/product_racks_model.dart';
|
||||
import '../provider/product_recks_provider.dart';
|
||||
|
||||
class RackRepo {
|
||||
static const String _endpoint = '/racks';
|
||||
|
||||
///---------------- FETCH ALL RACKS (GET) ----------------///
|
||||
Future<RackListModel> fetchAllRacks() async {
|
||||
// This remains unchanged, using CustomHttpClientGet
|
||||
CustomHttpClientGet clientGet = CustomHttpClientGet(client: http.Client());
|
||||
final uri = Uri.parse('${APIConfig.url}$_endpoint');
|
||||
|
||||
final response = await clientGet.get(url: uri);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final parsedData = jsonDecode(response.body);
|
||||
return RackListModel.fromJson(parsedData);
|
||||
} else {
|
||||
throw Exception('Failed to fetch rack list. Status: ${response.statusCode}');
|
||||
}
|
||||
}
|
||||
|
||||
///---------------- CREATE RACK (POST - USING UPLOAD FILE FOR FORM-DATA) ----------------///
|
||||
Future<void> createRack({
|
||||
required WidgetRef ref,
|
||||
required BuildContext context,
|
||||
required String name,
|
||||
required List<num> shelfIds,
|
||||
required String status,
|
||||
}) async {
|
||||
final uri = Uri.parse('${APIConfig.url}$_endpoint');
|
||||
|
||||
// Prepare fields for MultipartRequest
|
||||
final Map<String, String> fields = {
|
||||
'name': name,
|
||||
'status': status,
|
||||
};
|
||||
|
||||
// Add shelf_id[] as multiple fields (Multipart Request handles array fields easily)
|
||||
for (int i = 0; i < shelfIds.length; i++) {
|
||||
fields['shelf_id[$i]'] = shelfIds[i].toString();
|
||||
// NOTE: Using 'shelf_id[i]' indexing is a common way to ensure PHP/Laravel
|
||||
// recognizes the array input in form-data.
|
||||
}
|
||||
|
||||
// Initialize CustomHttpClient
|
||||
CustomHttpClient customHttpClient = CustomHttpClient(client: http.Client(), context: context, ref: ref);
|
||||
|
||||
try {
|
||||
EasyLoading.show(status: 'Creating Rack...');
|
||||
|
||||
// Use uploadFile method for form-data submission (even without a file)
|
||||
var streamedResponse = await customHttpClient.uploadFile(
|
||||
url: uri,
|
||||
fields: fields,
|
||||
// NOTE: Replace 'rack_create_permit' with your actual Permit.value
|
||||
permission: 'rack_create_permit',
|
||||
);
|
||||
|
||||
// Convert StreamedResponse to standard Response for easy parsing
|
||||
var response = await http.Response.fromStream(streamedResponse);
|
||||
|
||||
final parsedData = jsonDecode(response.body);
|
||||
EasyLoading.dismiss();
|
||||
|
||||
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||
ref.invalidate(rackListProvider);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(parsedData['message'] ?? 'Rack created successfully')),
|
||||
);
|
||||
Navigator.pop(context);
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Creation failed: ${parsedData['message'] ?? 'Unknown error'}')),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
EasyLoading.dismiss();
|
||||
// Catching the "Permission denied" exception thrown by CustomHttpClient
|
||||
if (error.toString().contains("Permission denied")) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Permission denied to create rack.'), backgroundColor: Colors.red));
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('An error occurred: $error')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///---------------- UPDATE RACK (POST with _method=put - USING UPLOAD FILE) ----------------///
|
||||
Future<void> updateRack({
|
||||
required WidgetRef ref,
|
||||
required BuildContext context,
|
||||
required num id,
|
||||
required String name,
|
||||
required List<num> shelfIds,
|
||||
required String status,
|
||||
}) async {
|
||||
final uri = Uri.parse('${APIConfig.url}$_endpoint/$id');
|
||||
|
||||
final Map<String, String> fields = {
|
||||
'_method': 'put', // Simulate PUT
|
||||
'name': name,
|
||||
'status': status,
|
||||
};
|
||||
|
||||
// Add shelf_id[]
|
||||
for (int i = 0; i < shelfIds.length; i++) {
|
||||
fields['shelf_id[$i]'] = shelfIds[i].toString();
|
||||
}
|
||||
|
||||
CustomHttpClient customHttpClient = CustomHttpClient(client: http.Client(), context: context, ref: ref);
|
||||
|
||||
try {
|
||||
EasyLoading.show(status: 'Updating Rack...');
|
||||
|
||||
var streamedResponse = await customHttpClient.uploadFile(
|
||||
url: uri,
|
||||
fields: fields,
|
||||
// NOTE: Replace 'rack_update_permit' with your actual Permit.value
|
||||
permission: 'rack_update_permit',
|
||||
);
|
||||
|
||||
var response = await http.Response.fromStream(streamedResponse);
|
||||
final parsedData = jsonDecode(response.body);
|
||||
EasyLoading.dismiss();
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
ref.invalidate(rackListProvider);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(parsedData['message'] ?? 'Rack updated successfully')),
|
||||
);
|
||||
Navigator.pop(context);
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Update failed: ${parsedData['message'] ?? 'Unknown error'}')),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
EasyLoading.dismiss();
|
||||
if (error.toString().contains("Permission denied")) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Permission denied to update rack.'), backgroundColor: Colors.red));
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('An error occurred: $error')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///---------------- DELETE RACK (DELETE - USING CustomHttpClient) ----------------///
|
||||
Future<bool> deleteRack({
|
||||
required num id,
|
||||
required BuildContext context,
|
||||
required WidgetRef ref,
|
||||
}) async {
|
||||
final url = Uri.parse('${APIConfig.url}$_endpoint/$id');
|
||||
CustomHttpClient customHttpClient = CustomHttpClient(ref: ref, context: context, client: http.Client());
|
||||
|
||||
try {
|
||||
EasyLoading.show(status: 'Deleting...');
|
||||
|
||||
// Use the standard delete method
|
||||
final response = await customHttpClient.delete(
|
||||
url: url,
|
||||
// NOTE: Replace 'rack_delete_permit' with your actual Permit.value
|
||||
permission: 'rack_delete_permit',
|
||||
);
|
||||
|
||||
EasyLoading.dismiss();
|
||||
if (response.statusCode == 200) {
|
||||
ref.invalidate(rackListProvider);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Rack deleted successfully')),
|
||||
);
|
||||
return true;
|
||||
} else {
|
||||
final parsedData = jsonDecode(response.body);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Deletion failed: ${parsedData['message'] ?? 'Unknown error'}')),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
EasyLoading.dismiss();
|
||||
if (error.toString().contains("Permission denied")) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Permission denied to delete rack.'), backgroundColor: Colors.red));
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('An error occurred during deletion: $error')),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user