feat: get table

This commit is contained in:
efrilm 2025-08-03 23:53:06 +07:00
parent 8431b07057
commit 6afd62b617
14 changed files with 769 additions and 478 deletions

View File

@ -358,19 +358,19 @@ class ProductLocalDatasource {
// generate table managent with count // generate table managent with count
Future<void> createTableManagement(String tableName, Offset position) async { Future<void> createTableManagement(String tableName, Offset position) async {
final db = await instance.database; // final db = await instance.database;
TableModel newTable = TableModel( // TableModel newTable = TableModel(
tableName: tableName, // tableName: tableName,
status: 'available', // status: 'available',
orderId: 0, // orderId: 0,
paymentAmount: 0, // paymentAmount: 0,
startTime: DateTime.now().toIso8601String(), // startTime: DateTime.now().toIso8601String(),
position: position, // position: position,
); // );
await db.insert( // await db.insert(
tableManagement, // tableManagement,
newTable.toMap(), // newTable.toMap(),
); // );
} }
// change position table // change position table

View File

@ -2,6 +2,7 @@ import 'dart:developer';
import 'package:dartz/dartz.dart'; import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:enaklo_pos/core/network/dio_client.dart'; import 'package:enaklo_pos/core/network/dio_client.dart';
import 'package:enaklo_pos/data/models/response/table_model.dart';
import '../../core/constants/variables.dart'; import '../../core/constants/variables.dart';
import 'auth_local_datasource.dart'; import 'auth_local_datasource.dart';
@ -50,4 +51,41 @@ class TableRemoteDataSource {
return const Left('Unexpected error occurred'); return const Left('Unexpected error occurred');
} }
} }
Future<Either<String, TableResponseModel>> getTable({
int page = 1,
int limit = 10,
}) async {
try {
final authData = await AuthLocalDataSource().getAuthData();
final url = '${Variables.baseUrl}/api/v1/tables';
final response = await dio.get(
url,
queryParameters: {
'page': page,
'limit': limit,
'outlet_id': authData.user?.outletId,
},
options: Options(
headers: {
'Authorization': 'Bearer ${authData.token}',
'Accept': 'application/json',
},
),
);
if (response.statusCode == 200) {
return Right(TableResponseModel.fromMap(response.data));
} else {
return const Left('Failed to get tables');
}
} on DioException catch (e) {
log("Dio error: ${e.message}");
return Left(e.response?.data['message'] ?? 'Gagal mengambil data meja');
} catch (e) {
log("Unexpected error: $e");
return const Left('Unexpected error occurred');
}
}
} }

View File

@ -1,74 +1,132 @@
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'dart:convert';
import 'dart:ui';
class TableResponseModel {
final bool? success;
final TableData? data;
final dynamic errors;
TableResponseModel({
this.success,
this.data,
this.errors,
});
factory TableResponseModel.fromJson(String str) =>
TableResponseModel.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory TableResponseModel.fromMap(Map<String, dynamic> json) =>
TableResponseModel(
success: json["success"],
data: json["data"] == null ? null : TableData.fromMap(json["data"]),
errors: json["errors"],
);
Map<String, dynamic> toMap() => {
"success": success,
"data": data?.toMap(),
"errors": errors,
};
}
class TableData {
final List<TableModel>? tables;
final int? totalCount;
final int? page;
final int? limit;
final int? totalPages;
TableData({
this.tables,
this.totalCount,
this.page,
this.limit,
this.totalPages,
});
factory TableData.fromMap(Map<String, dynamic> json) => TableData(
tables: json["tables"] == null
? []
: List<TableModel>.from(
json["tables"].map((x) => TableModel.fromMap(x))),
totalCount: json["total_count"],
page: json["page"],
limit: json["limit"],
totalPages: json["total_pages"],
);
Map<String, dynamic> toMap() => {
"tables": tables == null
? []
: List<dynamic>.from(tables!.map((x) => x.toMap())),
"total_count": totalCount,
"page": page,
"limit": limit,
"total_pages": totalPages,
};
}
class TableModel { class TableModel {
int? id; final String? id;
final String tableName; final String? organizationId;
final String startTime; final String? outletId;
final String status; final String? tableName;
final int orderId; final String? status;
final int paymentAmount; final int? paymentAmount;
final Offset position; final double? positionX;
final double? positionY;
final int? capacity;
final bool? isActive;
final DateTime? createdAt;
final DateTime? updatedAt;
TableModel({ TableModel({
this.id, this.id,
required this.tableName, this.organizationId,
required this.startTime, this.outletId,
required this.status, this.tableName,
required this.orderId, this.status,
required this.paymentAmount, this.paymentAmount,
required this.position, this.positionX,
this.positionY,
this.capacity,
this.isActive,
this.createdAt,
this.updatedAt,
}); });
@override factory TableModel.fromMap(Map<String, dynamic> json) => TableModel(
id: json["id"],
// from map organizationId: json["organization_id"],
factory TableModel.fromMap(Map<String, dynamic> map) { outletId: json["outlet_id"],
return TableModel( tableName: json["table_name"],
id: map['id'], status: json["status"],
tableName: map['table_name'], paymentAmount: json["payment_amount"],
startTime: map['start_time'], positionX: json["position_x"]?.toDouble(),
status: map['status'], positionY: json["position_y"]?.toDouble(),
orderId: map['order_id'], capacity: json["capacity"],
paymentAmount: map['payment_amount'], isActive: json["is_active"],
position: Offset(map['x_position'], map['y_position']), createdAt: json["created_at"] == null
? null
: DateTime.parse(json["created_at"]),
updatedAt: json["updated_at"] == null
? null
: DateTime.parse(json["updated_at"]),
); );
}
// to map Map<String, dynamic> toMap() => {
Map<String, dynamic> toMap() { "id": id,
return { "organization_id": organizationId,
'table_name': tableName, "outlet_id": outletId,
'status': status, "table_name": tableName,
'start_time': startTime, "status": status,
'order_id': orderId, "payment_amount": paymentAmount,
'payment_amount': paymentAmount, "position_x": positionX,
'x_position': position.dx, "position_y": positionY,
'y_position': position.dy, "capacity": capacity,
"is_active": isActive,
"created_at": createdAt?.toIso8601String(),
"updated_at": updatedAt?.toIso8601String(),
}; };
}
@override
bool operator ==(covariant TableModel other) {
if (identical(this, other)) return true;
return other.id == id &&
other.tableName == tableName &&
other.startTime == startTime &&
other.status == status &&
other.orderId == orderId &&
other.paymentAmount == paymentAmount &&
other.position == position;
}
@override
int get hashCode {
return id.hashCode ^
tableName.hashCode ^
startTime.hashCode ^
status.hashCode ^
orderId.hashCode ^
paymentAmount.hashCode ^
position.hashCode;
}
} }

View File

@ -154,7 +154,7 @@ class _MyAppState extends State<MyApp> {
create: (context) => ChangePositionTableBloc(), create: (context) => ChangePositionTableBloc(),
), ),
BlocProvider( BlocProvider(
create: (context) => GetTableBloc(), create: (context) => GetTableBloc(TableRemoteDataSource()),
), ),
BlocProvider( BlocProvider(
create: (context) => UpdateTableBloc(), create: (context) => UpdateTableBloc(),

View File

@ -117,7 +117,7 @@ class _PaymentSaveDialogState extends State<PaymentSaveDialog> {
(TableModel value) => (TableModel value) =>
DropdownMenuItem<TableModel>( DropdownMenuItem<TableModel>(
value: value, value: value,
child: Text(value.tableName), child: Text(value.tableName ?? ""),
), ),
) )
.toList(), .toList(),

View File

@ -829,7 +829,8 @@ class _ConfirmPaymentPageState extends State<ConfirmPaymentPage> {
DropdownMenuItem< DropdownMenuItem<
TableModel>( TableModel>(
value: value, value: value,
child: Text(value.tableName), child: Text(
value.tableName ?? ""),
), ),
) )
.toList(), .toList(),
@ -1192,28 +1193,28 @@ class _ConfirmPaymentPageState extends State<ConfirmPaymentPage> {
savedDraftOrder: (orderDraftId) { savedDraftOrder: (orderDraftId) {
log("PRICEVALUE: ${priceValue}"); log("PRICEVALUE: ${priceValue}");
final newTabel = TableModel( // final newTabel = TableModel(
id: widget.isTable // id: widget.isTable
? widget.table!.id // ? widget.table!.id
: selectTable?.id, // : selectTable?.id,
tableName: widget.isTable // tableName: widget.isTable
? widget.table!.tableName // ? widget.table!.tableName
: selectTable?.tableName ?? // : selectTable?.tableName ??
'0', // '0',
status: 'occupied', // status: 'occupied',
paymentAmount: priceValue, // paymentAmount: priceValue,
orderId: orderDraftId, // orderId: orderDraftId,
startTime: DateTime.now() // startTime: DateTime.now()
.toIso8601String(), // .toIso8601String(),
position: widget.isTable // position: widget.isTable
? widget.table!.position // ? widget.table!.position
: selectTable!.position); // : selectTable!.position);
log('new tabel: ${newTabel.toMap()}'); // log('new tabel: ${newTabel.toMap()}');
context // context
.read<StatusTableBloc>() // .read<StatusTableBloc>()
.add(StatusTableEvent.statusTabel( // .add(StatusTableEvent.statusTabel(
newTabel, // newTabel,
)); // ));
}); });
}, },
child: child:
@ -1357,16 +1358,16 @@ class _ConfirmPaymentPageState extends State<ConfirmPaymentPage> {
if (widget.isTable) { if (widget.isTable) {
log("discountAmountValue: $totalDiscount"); log("discountAmountValue: $totalDiscount");
context.read<CheckoutBloc>().add( // context.read<CheckoutBloc>().add(
CheckoutEvent // CheckoutEvent
.saveDraftOrder( // .saveDraftOrder(
widget.isTable == true // widget.isTable == true
? widget.table!.id! // ? widget.table!.id!
: selectTable!.id!, // : selectTable!.id!,
customerController.text, // customerController.text,
totalDiscount.toInt(), // totalDiscount.toInt(),
), // ),
); // );
await showDialog( await showDialog(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
@ -1515,120 +1516,120 @@ class _ConfirmPaymentPageState extends State<ConfirmPaymentPage> {
// Tambahkan ke pesanan meja yang sudah ada // Tambahkan ke pesanan meja yang sudah ada
if (selectTable != null) { if (selectTable != null) {
// Ambil draft order yang sudah ada // Ambil draft order yang sudah ada
final existingDraftOrder = // final existingDraftOrder =
await ProductLocalDatasource // await ProductLocalDatasource
.instance // .instance
.getDraftOrderById( // .getDraftOrderById(
selectTable // selectTable
?.orderId ?? // ?.orderId ??
0); // 0);
if (existingDraftOrder != // if (existingDraftOrder !=
null) { // null) {
// Convert items ke DraftOrderItem // // Convert items ke DraftOrderItem
final newDraftItems = items // final newDraftItems = items
.map((item) => // .map((item) =>
DraftOrderItem( // DraftOrderItem(
product: // product:
item.product, // item.product,
quantity: // quantity:
item.quantity, // item.quantity,
)) // ))
.toList(); // .toList();
// Gabungkan dengan pesanan yang sudah ada // // Gabungkan dengan pesanan yang sudah ada
final updatedItems = [ // final updatedItems = [
...existingDraftOrder // ...existingDraftOrder
.orders, // .orders,
...newDraftItems // ...newDraftItems
]; // ];
final updatedDraftOrder = // final updatedDraftOrder =
existingDraftOrder // existingDraftOrder
.copyWith( // .copyWith(
orders: updatedItems, // orders: updatedItems,
totalQuantity: // totalQuantity:
updatedItems.fold<int>( // updatedItems.fold<int>(
0, // 0,
(sum, item) => // (sum, item) =>
sum + // sum +
item.quantity), // item.quantity),
subTotal: updatedItems.fold< // subTotal: updatedItems.fold<
int>( // int>(
0, // 0,
(sum, item) => // (sum, item) =>
sum + // sum +
(item.product // (item.product
.price ?? // .price ??
0) * // 0) *
item.quantity), // item.quantity),
); // );
// Update draft order // // Update draft order
await ProductLocalDatasource // await ProductLocalDatasource
.instance // .instance
.updateDraftOrder( // .updateDraftOrder(
updatedDraftOrder); // updatedDraftOrder);
// Tampilkan dialog sukses // // Tampilkan dialog sukses
await showDialog( // await showDialog(
context: context, // context: context,
barrierDismissible: false, // barrierDismissible: false,
builder: (context) => // builder: (context) =>
SaveOrderDialog( // SaveOrderDialog(
data: items, // data: items,
totalQty: totalQty, // totalQty: totalQty,
totalPrice: // totalPrice:
totalPriceFinal, // totalPriceFinal,
totalTax: // totalTax:
finalTax.toInt(), // finalTax.toInt(),
totalDiscount: // totalDiscount:
totalDiscount.toInt(), // totalDiscount.toInt(),
subTotal: // subTotal:
subTotal.toInt(), // subTotal.toInt(),
normalPrice: price, // normalPrice: price,
table: selectTable!, // table: selectTable!,
draftName: // draftName:
customerController // customerController
.text, // .text,
), // ),
); // );
} else { // } else {
// Jika tidak ada draft order, buat baru // // Jika tidak ada draft order, buat baru
context // context
.read<CheckoutBloc>() // .read<CheckoutBloc>()
.add( // .add(
CheckoutEvent // CheckoutEvent
.saveDraftOrder( // .saveDraftOrder(
selectTable!.id!, // selectTable!.id!,
customerController // customerController
.text, // .text,
totalDiscount.toInt(), // totalDiscount.toInt(),
), // ),
); // );
await showDialog( // await showDialog(
context: context, // context: context,
barrierDismissible: false, // barrierDismissible: false,
builder: (context) => // builder: (context) =>
SaveOrderDialog( // SaveOrderDialog(
data: items, // data: items,
totalQty: totalQty, // totalQty: totalQty,
totalPrice: // totalPrice:
totalPriceFinal, // totalPriceFinal,
totalTax: // totalTax:
finalTax.toInt(), // finalTax.toInt(),
totalDiscount: // totalDiscount:
totalDiscount.toInt(), // totalDiscount.toInt(),
subTotal: // subTotal:
subTotal.toInt(), // subTotal.toInt(),
normalPrice: price, // normalPrice: price,
table: selectTable!, // table: selectTable!,
draftName: // draftName:
customerController // customerController
.text, // .text,
), // ),
); // );
} // }
} else { } else {
ScaffoldMessenger.of(context) ScaffoldMessenger.of(context)
.showSnackBar( .showSnackBar(
@ -1640,16 +1641,16 @@ class _ConfirmPaymentPageState extends State<ConfirmPaymentPage> {
); );
} }
} else { } else {
context.read<CheckoutBloc>().add( // context.read<CheckoutBloc>().add(
CheckoutEvent // CheckoutEvent
.saveDraftOrder( // .saveDraftOrder(
widget.isTable == true // widget.isTable == true
? widget.table!.id! // ? widget.table!.id!
: selectTable!.id!, // : selectTable!.id!,
customerController.text, // customerController.text,
totalDiscount.toInt(), // totalDiscount.toInt(),
), // ),
); // );
await showDialog( await showDialog(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,

View File

@ -97,7 +97,17 @@ class _SaveOrderDialogState extends State<SaveOrderDialog> {
builder: (context, state) { builder: (context, state) {
final orderType = state.maybeWhen( final orderType = state.maybeWhen(
orElse: () => OrderType.dineIn, orElse: () => OrderType.dineIn,
loaded: (items, discountModel, discount, discountAmount, tax, serviceCharge, totalQuantity, totalPrice, draftName, orderType) => orderType, loaded: (items,
discountModel,
discount,
discountAmount,
tax,
serviceCharge,
totalQuantity,
totalPrice,
draftName,
orderType) =>
orderType,
); );
return Button.filled( return Button.filled(
@ -108,7 +118,8 @@ class _SaveOrderDialogState extends State<SaveOrderDialog> {
final kitchenPrinter = await ProductLocalDatasource final kitchenPrinter = await ProductLocalDatasource
.instance .instance
.getPrinterByCode('kitchen'); .getPrinterByCode('kitchen');
final barPrinter = await ProductLocalDatasource.instance final barPrinter = await ProductLocalDatasource
.instance
.getPrinterByCode('bar'); .getPrinterByCode('bar');
log("Checker printer: ${checkerPrinter?.toMap()}"); log("Checker printer: ${checkerPrinter?.toMap()}");
@ -121,21 +132,20 @@ class _SaveOrderDialogState extends State<SaveOrderDialog> {
final printValue = await PrintDataoutputs.instance final printValue = await PrintDataoutputs.instance
.printChecker( .printChecker(
widget.data, widget.data,
widget.table.tableName, widget.table.tableName!,
widget.draftName, widget.draftName,
'kasir', 'kasir',
checkerPrinter.paper.toIntegerFromText, checkerPrinter.paper.toIntegerFromText,
orderType.value); orderType.value);
await PrinterService().printWithPrinter( await PrinterService().printWithPrinter(
checkerPrinter, checkerPrinter, printValue, context);
printValue,
context
);
} catch (e) { } catch (e) {
log("Error printing checker: $e"); log("Error printing checker: $e");
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error printing checker: $e')), SnackBar(
content:
Text('Error printing checker: $e')),
); );
} }
} }
@ -143,9 +153,10 @@ class _SaveOrderDialogState extends State<SaveOrderDialog> {
// Kitchen printer // Kitchen printer
if (kitchenPrinter != null) { if (kitchenPrinter != null) {
try { try {
final printValue = await PrintDataoutputs.instance.printKitchen( final printValue =
await PrintDataoutputs.instance.printKitchen(
widget.data, widget.data,
widget.table.tableName, widget.table.tableName!,
widget.draftName, widget.draftName,
'kasir', 'kasir',
kitchenPrinter.paper.toIntegerFromText, kitchenPrinter.paper.toIntegerFromText,
@ -153,14 +164,13 @@ class _SaveOrderDialogState extends State<SaveOrderDialog> {
); );
await PrinterService().printWithPrinter( await PrinterService().printWithPrinter(
kitchenPrinter, kitchenPrinter, printValue, context);
printValue,
context
);
} catch (e) { } catch (e) {
log("Error printing kitchen order: $e"); log("Error printing kitchen order: $e");
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error printing kitchen order: $e')), SnackBar(
content: Text(
'Error printing kitchen order: $e')),
); );
} }
} }
@ -168,9 +178,10 @@ class _SaveOrderDialogState extends State<SaveOrderDialog> {
// Bar printer // Bar printer
if (barPrinter != null) { if (barPrinter != null) {
try { try {
final printValue = await PrintDataoutputs.instance.printBar( final printValue =
await PrintDataoutputs.instance.printBar(
widget.data, widget.data,
widget.table.tableName, widget.table.tableName!,
widget.draftName, widget.draftName,
'kasir', 'kasir',
barPrinter.paper.toIntegerFromText, barPrinter.paper.toIntegerFromText,
@ -178,14 +189,13 @@ class _SaveOrderDialogState extends State<SaveOrderDialog> {
); );
await PrinterService().printWithPrinter( await PrinterService().printWithPrinter(
barPrinter, barPrinter, printValue, context);
printValue,
context
);
} catch (e) { } catch (e) {
log("Error printing bar order: $e"); log("Error printing bar order: $e");
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error printing bar order: $e')), SnackBar(
content:
Text('Error printing bar order: $e')),
); );
} }
} }

View File

@ -1,3 +1,4 @@
import 'package:enaklo_pos/data/datasources/table_remote_datasource.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; import 'package:enaklo_pos/data/datasources/product_local_datasource.dart';
import 'package:enaklo_pos/data/models/response/table_model.dart'; import 'package:enaklo_pos/data/models/response/table_model.dart';
@ -8,11 +9,17 @@ part 'get_table_state.dart';
part 'get_table_bloc.freezed.dart'; part 'get_table_bloc.freezed.dart';
class GetTableBloc extends Bloc<GetTableEvent, GetTableState> { class GetTableBloc extends Bloc<GetTableEvent, GetTableState> {
GetTableBloc() : super(_Initial()) { final TableRemoteDataSource _tableRemoteDataSource;
GetTableBloc(this._tableRemoteDataSource) : super(GetTableState.initial()) {
on<_GetTables>((event, emit) async { on<_GetTables>((event, emit) async {
emit(_Loading()); emit(_Loading());
final tables = await ProductLocalDatasource.instance.getAllTable(); final tables = await _tableRemoteDataSource.getTable();
emit(_Success(tables)); tables.fold(
(l) => emit(_Error(l)),
(r) => emit(
_Success(r.data!.tables!),
),
);
}); });
} }
} }

View File

@ -294,6 +294,7 @@ mixin _$GetTableState {
required TResult Function() initial, required TResult Function() initial,
required TResult Function() loading, required TResult Function() loading,
required TResult Function(List<TableModel> tables) success, required TResult Function(List<TableModel> tables) success,
required TResult Function(String message) error,
}) => }) =>
throw _privateConstructorUsedError; throw _privateConstructorUsedError;
@optionalTypeArgs @optionalTypeArgs
@ -301,6 +302,7 @@ mixin _$GetTableState {
TResult? Function()? initial, TResult? Function()? initial,
TResult? Function()? loading, TResult? Function()? loading,
TResult? Function(List<TableModel> tables)? success, TResult? Function(List<TableModel> tables)? success,
TResult? Function(String message)? error,
}) => }) =>
throw _privateConstructorUsedError; throw _privateConstructorUsedError;
@optionalTypeArgs @optionalTypeArgs
@ -308,6 +310,7 @@ mixin _$GetTableState {
TResult Function()? initial, TResult Function()? initial,
TResult Function()? loading, TResult Function()? loading,
TResult Function(List<TableModel> tables)? success, TResult Function(List<TableModel> tables)? success,
TResult Function(String message)? error,
required TResult orElse(), required TResult orElse(),
}) => }) =>
throw _privateConstructorUsedError; throw _privateConstructorUsedError;
@ -316,6 +319,7 @@ mixin _$GetTableState {
required TResult Function(_Initial value) initial, required TResult Function(_Initial value) initial,
required TResult Function(_Loading value) loading, required TResult Function(_Loading value) loading,
required TResult Function(_Success value) success, required TResult Function(_Success value) success,
required TResult Function(_Error value) error,
}) => }) =>
throw _privateConstructorUsedError; throw _privateConstructorUsedError;
@optionalTypeArgs @optionalTypeArgs
@ -323,6 +327,7 @@ mixin _$GetTableState {
TResult? Function(_Initial value)? initial, TResult? Function(_Initial value)? initial,
TResult? Function(_Loading value)? loading, TResult? Function(_Loading value)? loading,
TResult? Function(_Success value)? success, TResult? Function(_Success value)? success,
TResult? Function(_Error value)? error,
}) => }) =>
throw _privateConstructorUsedError; throw _privateConstructorUsedError;
@optionalTypeArgs @optionalTypeArgs
@ -330,6 +335,7 @@ mixin _$GetTableState {
TResult Function(_Initial value)? initial, TResult Function(_Initial value)? initial,
TResult Function(_Loading value)? loading, TResult Function(_Loading value)? loading,
TResult Function(_Success value)? success, TResult Function(_Success value)? success,
TResult Function(_Error value)? error,
required TResult orElse(), required TResult orElse(),
}) => }) =>
throw _privateConstructorUsedError; throw _privateConstructorUsedError;
@ -400,6 +406,7 @@ class _$InitialImpl implements _Initial {
required TResult Function() initial, required TResult Function() initial,
required TResult Function() loading, required TResult Function() loading,
required TResult Function(List<TableModel> tables) success, required TResult Function(List<TableModel> tables) success,
required TResult Function(String message) error,
}) { }) {
return initial(); return initial();
} }
@ -410,6 +417,7 @@ class _$InitialImpl implements _Initial {
TResult? Function()? initial, TResult? Function()? initial,
TResult? Function()? loading, TResult? Function()? loading,
TResult? Function(List<TableModel> tables)? success, TResult? Function(List<TableModel> tables)? success,
TResult? Function(String message)? error,
}) { }) {
return initial?.call(); return initial?.call();
} }
@ -420,6 +428,7 @@ class _$InitialImpl implements _Initial {
TResult Function()? initial, TResult Function()? initial,
TResult Function()? loading, TResult Function()? loading,
TResult Function(List<TableModel> tables)? success, TResult Function(List<TableModel> tables)? success,
TResult Function(String message)? error,
required TResult orElse(), required TResult orElse(),
}) { }) {
if (initial != null) { if (initial != null) {
@ -434,6 +443,7 @@ class _$InitialImpl implements _Initial {
required TResult Function(_Initial value) initial, required TResult Function(_Initial value) initial,
required TResult Function(_Loading value) loading, required TResult Function(_Loading value) loading,
required TResult Function(_Success value) success, required TResult Function(_Success value) success,
required TResult Function(_Error value) error,
}) { }) {
return initial(this); return initial(this);
} }
@ -444,6 +454,7 @@ class _$InitialImpl implements _Initial {
TResult? Function(_Initial value)? initial, TResult? Function(_Initial value)? initial,
TResult? Function(_Loading value)? loading, TResult? Function(_Loading value)? loading,
TResult? Function(_Success value)? success, TResult? Function(_Success value)? success,
TResult? Function(_Error value)? error,
}) { }) {
return initial?.call(this); return initial?.call(this);
} }
@ -454,6 +465,7 @@ class _$InitialImpl implements _Initial {
TResult Function(_Initial value)? initial, TResult Function(_Initial value)? initial,
TResult Function(_Loading value)? loading, TResult Function(_Loading value)? loading,
TResult Function(_Success value)? success, TResult Function(_Success value)? success,
TResult Function(_Error value)? error,
required TResult orElse(), required TResult orElse(),
}) { }) {
if (initial != null) { if (initial != null) {
@ -511,6 +523,7 @@ class _$LoadingImpl implements _Loading {
required TResult Function() initial, required TResult Function() initial,
required TResult Function() loading, required TResult Function() loading,
required TResult Function(List<TableModel> tables) success, required TResult Function(List<TableModel> tables) success,
required TResult Function(String message) error,
}) { }) {
return loading(); return loading();
} }
@ -521,6 +534,7 @@ class _$LoadingImpl implements _Loading {
TResult? Function()? initial, TResult? Function()? initial,
TResult? Function()? loading, TResult? Function()? loading,
TResult? Function(List<TableModel> tables)? success, TResult? Function(List<TableModel> tables)? success,
TResult? Function(String message)? error,
}) { }) {
return loading?.call(); return loading?.call();
} }
@ -531,6 +545,7 @@ class _$LoadingImpl implements _Loading {
TResult Function()? initial, TResult Function()? initial,
TResult Function()? loading, TResult Function()? loading,
TResult Function(List<TableModel> tables)? success, TResult Function(List<TableModel> tables)? success,
TResult Function(String message)? error,
required TResult orElse(), required TResult orElse(),
}) { }) {
if (loading != null) { if (loading != null) {
@ -545,6 +560,7 @@ class _$LoadingImpl implements _Loading {
required TResult Function(_Initial value) initial, required TResult Function(_Initial value) initial,
required TResult Function(_Loading value) loading, required TResult Function(_Loading value) loading,
required TResult Function(_Success value) success, required TResult Function(_Success value) success,
required TResult Function(_Error value) error,
}) { }) {
return loading(this); return loading(this);
} }
@ -555,6 +571,7 @@ class _$LoadingImpl implements _Loading {
TResult? Function(_Initial value)? initial, TResult? Function(_Initial value)? initial,
TResult? Function(_Loading value)? loading, TResult? Function(_Loading value)? loading,
TResult? Function(_Success value)? success, TResult? Function(_Success value)? success,
TResult? Function(_Error value)? error,
}) { }) {
return loading?.call(this); return loading?.call(this);
} }
@ -565,6 +582,7 @@ class _$LoadingImpl implements _Loading {
TResult Function(_Initial value)? initial, TResult Function(_Initial value)? initial,
TResult Function(_Loading value)? loading, TResult Function(_Loading value)? loading,
TResult Function(_Success value)? success, TResult Function(_Success value)? success,
TResult Function(_Error value)? error,
required TResult orElse(), required TResult orElse(),
}) { }) {
if (loading != null) { if (loading != null) {
@ -655,6 +673,7 @@ class _$SuccessImpl implements _Success {
required TResult Function() initial, required TResult Function() initial,
required TResult Function() loading, required TResult Function() loading,
required TResult Function(List<TableModel> tables) success, required TResult Function(List<TableModel> tables) success,
required TResult Function(String message) error,
}) { }) {
return success(tables); return success(tables);
} }
@ -665,6 +684,7 @@ class _$SuccessImpl implements _Success {
TResult? Function()? initial, TResult? Function()? initial,
TResult? Function()? loading, TResult? Function()? loading,
TResult? Function(List<TableModel> tables)? success, TResult? Function(List<TableModel> tables)? success,
TResult? Function(String message)? error,
}) { }) {
return success?.call(tables); return success?.call(tables);
} }
@ -675,6 +695,7 @@ class _$SuccessImpl implements _Success {
TResult Function()? initial, TResult Function()? initial,
TResult Function()? loading, TResult Function()? loading,
TResult Function(List<TableModel> tables)? success, TResult Function(List<TableModel> tables)? success,
TResult Function(String message)? error,
required TResult orElse(), required TResult orElse(),
}) { }) {
if (success != null) { if (success != null) {
@ -689,6 +710,7 @@ class _$SuccessImpl implements _Success {
required TResult Function(_Initial value) initial, required TResult Function(_Initial value) initial,
required TResult Function(_Loading value) loading, required TResult Function(_Loading value) loading,
required TResult Function(_Success value) success, required TResult Function(_Success value) success,
required TResult Function(_Error value) error,
}) { }) {
return success(this); return success(this);
} }
@ -699,6 +721,7 @@ class _$SuccessImpl implements _Success {
TResult? Function(_Initial value)? initial, TResult? Function(_Initial value)? initial,
TResult? Function(_Loading value)? loading, TResult? Function(_Loading value)? loading,
TResult? Function(_Success value)? success, TResult? Function(_Success value)? success,
TResult? Function(_Error value)? error,
}) { }) {
return success?.call(this); return success?.call(this);
} }
@ -709,6 +732,7 @@ class _$SuccessImpl implements _Success {
TResult Function(_Initial value)? initial, TResult Function(_Initial value)? initial,
TResult Function(_Loading value)? loading, TResult Function(_Loading value)? loading,
TResult Function(_Success value)? success, TResult Function(_Success value)? success,
TResult Function(_Error value)? error,
required TResult orElse(), required TResult orElse(),
}) { }) {
if (success != null) { if (success != null) {
@ -729,3 +753,155 @@ abstract class _Success implements GetTableState {
_$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith =>
throw _privateConstructorUsedError; throw _privateConstructorUsedError;
} }
/// @nodoc
abstract class _$$ErrorImplCopyWith<$Res> {
factory _$$ErrorImplCopyWith(
_$ErrorImpl value, $Res Function(_$ErrorImpl) then) =
__$$ErrorImplCopyWithImpl<$Res>;
@useResult
$Res call({String message});
}
/// @nodoc
class __$$ErrorImplCopyWithImpl<$Res>
extends _$GetTableStateCopyWithImpl<$Res, _$ErrorImpl>
implements _$$ErrorImplCopyWith<$Res> {
__$$ErrorImplCopyWithImpl(
_$ErrorImpl _value, $Res Function(_$ErrorImpl) _then)
: super(_value, _then);
/// Create a copy of GetTableState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? message = null,
}) {
return _then(_$ErrorImpl(
null == message
? _value.message
: message // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
class _$ErrorImpl implements _Error {
const _$ErrorImpl(this.message);
@override
final String message;
@override
String toString() {
return 'GetTableState.error(message: $message)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$ErrorImpl &&
(identical(other.message, message) || other.message == message));
}
@override
int get hashCode => Object.hash(runtimeType, message);
/// Create a copy of GetTableState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$ErrorImplCopyWith<_$ErrorImpl> get copyWith =>
__$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity);
@override
@optionalTypeArgs
TResult when<TResult extends Object?>({
required TResult Function() initial,
required TResult Function() loading,
required TResult Function(List<TableModel> tables) success,
required TResult Function(String message) error,
}) {
return error(message);
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
TResult? Function()? initial,
TResult? Function()? loading,
TResult? Function(List<TableModel> tables)? success,
TResult? Function(String message)? error,
}) {
return error?.call(message);
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>({
TResult Function()? initial,
TResult Function()? loading,
TResult Function(List<TableModel> tables)? success,
TResult Function(String message)? error,
required TResult orElse(),
}) {
if (error != null) {
return error(message);
}
return orElse();
}
@override
@optionalTypeArgs
TResult map<TResult extends Object?>({
required TResult Function(_Initial value) initial,
required TResult Function(_Loading value) loading,
required TResult Function(_Success value) success,
required TResult Function(_Error value) error,
}) {
return error(this);
}
@override
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
TResult? Function(_Initial value)? initial,
TResult? Function(_Loading value)? loading,
TResult? Function(_Success value)? success,
TResult? Function(_Error value)? error,
}) {
return error?.call(this);
}
@override
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>({
TResult Function(_Initial value)? initial,
TResult Function(_Loading value)? loading,
TResult Function(_Success value)? success,
TResult Function(_Error value)? error,
required TResult orElse(),
}) {
if (error != null) {
return error(this);
}
return orElse();
}
}
abstract class _Error implements GetTableState {
const factory _Error(final String message) = _$ErrorImpl;
String get message;
/// Create a copy of GetTableState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
_$$ErrorImplCopyWith<_$ErrorImpl> get copyWith =>
throw _privateConstructorUsedError;
}

View File

@ -5,4 +5,5 @@ class GetTableState with _$GetTableState {
const factory GetTableState.initial() = _Initial; const factory GetTableState.initial() = _Initial;
const factory GetTableState.loading() = _Loading; const factory GetTableState.loading() = _Loading;
const factory GetTableState.success(List<TableModel> tables) = _Success; const factory GetTableState.success(List<TableModel> tables) = _Success;
const factory GetTableState.error(String message) = _Error;
} }

View File

@ -3,7 +3,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:enaklo_pos/core/components/components.dart'; import 'package:enaklo_pos/core/components/components.dart';
import 'package:enaklo_pos/core/constants/colors.dart'; import 'package:enaklo_pos/core/constants/colors.dart';
import 'package:enaklo_pos/core/extensions/build_context_ext.dart';
import 'package:enaklo_pos/presentation/table/blocs/change_position_table/change_position_table_bloc.dart'; import 'package:enaklo_pos/presentation/table/blocs/change_position_table/change_position_table_bloc.dart';
import 'package:enaklo_pos/presentation/table/blocs/create_table/create_table_bloc.dart'; import 'package:enaklo_pos/presentation/table/blocs/create_table/create_table_bloc.dart';
import 'package:enaklo_pos/presentation/table/blocs/get_table/get_table_bloc.dart'; import 'package:enaklo_pos/presentation/table/blocs/get_table/get_table_bloc.dart';
@ -94,8 +93,8 @@ class _TableManagementScreenState extends State<TableManagementScreen> {
return Stack( return Stack(
children: tables.map((table) { children: tables.map((table) {
return Positioned( return Positioned(
left: table.position.dx - 116, left: (table.positionX ?? 0) - 116,
top: table.position.dy - 80, top: (table.positionY ?? 0) - 80,
child: BlocListener<ChangePositionTableBloc, child: BlocListener<ChangePositionTableBloc,
ChangePositionTableState>( ChangePositionTableState>(
listener: (context, state) { listener: (context, state) {
@ -111,12 +110,12 @@ class _TableManagementScreenState extends State<TableManagementScreen> {
feedback: TableWidget(table: table), feedback: TableWidget(table: table),
childWhenDragging: SizedBox.shrink(), childWhenDragging: SizedBox.shrink(),
onDragEnd: (details) { onDragEnd: (details) {
context // context
.read<ChangePositionTableBloc>() // .read<ChangePositionTableBloc>()
.add(ChangePositionTableEvent.changePositionTable( // .add(ChangePositionTableEvent.changePositionTable(
tableId: table.id!, // tableId: table.id,
position: details.offset, // position: details.offset,
)); // ));
}, },
child: TableWidget(table: table), child: TableWidget(table: table),
), ),

View File

@ -51,18 +51,18 @@ class _PaymentTablePageState extends State<PaymentTablePage> {
Future<void> _handlePostPaymentCleanup() async { Future<void> _handlePostPaymentCleanup() async {
if (widget.table != null && widget.draftOrder?.id != null) { if (widget.table != null && widget.draftOrder?.id != null) {
// Update table status to available // Update table status to available
final newTable = TableModel( // final newTable = TableModel(
id: widget.table!.id, // id: widget.table!.id,
tableName: widget.table!.tableName, // tableName: widget.table!.tableName,
status: 'available', // status: 'available',
orderId: 0, // orderId: 0,
paymentAmount: 0, // paymentAmount: 0,
startTime: DateTime.now().toIso8601String(), // startTime: DateTime.now().toIso8601String(),
position: widget.table!.position, // position: widget.table!.position,
); // );
// Update table status // Update table status
await ProductLocalDatasource.instance.updateStatusTable(newTable); // await ProductLocalDatasource.instance.updateStatusTable(newTable);
// Remove draft order // Remove draft order
await ProductLocalDatasource.instance await ProductLocalDatasource.instance
@ -965,25 +965,25 @@ class _PaymentTablePageState extends State<PaymentTablePage> {
onPressed: () { onPressed: () {
// Void the order // Void the order
if (widget.table != null) { if (widget.table != null) {
final newTable = TableModel( // final newTable = TableModel(
id: widget.table!.id, // id: widget.table!.id,
tableName: widget // tableName: widget
.table!.tableName, // .table!.tableName,
status: 'available', // status: 'available',
orderId: 0, // orderId: 0,
paymentAmount: 0, // paymentAmount: 0,
startTime: DateTime.now() // startTime: DateTime.now()
.toIso8601String(), // .toIso8601String(),
position: widget // position: widget
.table!.position, // .table!.position,
); // );
context // context
.read<StatusTableBloc>() // .read<StatusTableBloc>()
.add( // .add(
StatusTableEvent // StatusTableEvent
.statusTabel( // .statusTabel(
newTable), // newTable),
); // );
} }
// Remove draft order from local storage // Remove draft order from local storage
if (widget.draftOrder?.id != if (widget.draftOrder?.id !=
@ -1013,21 +1013,21 @@ class _PaymentTablePageState extends State<PaymentTablePage> {
const SpaceWidth(8.0), const SpaceWidth(8.0),
BlocListener<OrderBloc, OrderState>( BlocListener<OrderBloc, OrderState>(
listener: (context, state) { listener: (context, state) {
final newTable = TableModel( // final newTable = TableModel(
id: widget.table!.id, // id: widget.table!.id,
tableName: widget.table!.tableName, // tableName: widget.table!.tableName,
status: 'available', // status: 'available',
orderId: 0, // orderId: 0,
paymentAmount: 0, // paymentAmount: 0,
startTime: // startTime:
DateTime.now().toIso8601String(), // DateTime.now().toIso8601String(),
position: widget.table!.position, // position: widget.table!.position,
); // );
context.read<StatusTableBloc>().add( // context.read<StatusTableBloc>().add(
StatusTableEvent.statusTabel( // StatusTableEvent.statusTabel(
newTable, // newTable,
), // ),
); // );
ProductLocalDatasource.instance ProductLocalDatasource.instance
.removeDraftOrderById( .removeDraftOrderById(
widget.draftOrder!.id!); widget.draftOrder!.id!);
@ -1160,24 +1160,24 @@ class _PaymentTablePageState extends State<PaymentTablePage> {
'uang tunai' || 'uang tunai' ||
paymentMethodName == paymentMethodName ==
'cash payment') { 'cash payment') {
context.read<OrderBloc>().add( // context.read<OrderBloc>().add(
OrderEvent.order( // OrderEvent.order(
items, // items,
discount, // discount,
discountAmountFinal, // discountAmountFinal,
finalTax.toInt(), // finalTax.toInt(),
0, // 0,
totalPriceController.text // totalPriceController.text
.toIntegerFromText, // .toIntegerFromText,
customerController.text, // customerController.text,
widget.table?.id ?? 0, // widget.table?.id ?? 0,
'completed', // 'completed',
'paid', // 'paid',
selectedPaymentMethod // selectedPaymentMethod
?.name ?? // ?.name ??
'Cash', // 'Cash',
totalPriceFinal, // totalPriceFinal,
orderType)); // orderType));
await showDialog( await showDialog(
context: context, context: context,
@ -1202,24 +1202,24 @@ class _PaymentTablePageState extends State<PaymentTablePage> {
await _handlePostPaymentCleanup(); await _handlePostPaymentCleanup();
} else { } else {
log("Processing non-cash payment: ${selectedPaymentMethod?.name}"); log("Processing non-cash payment: ${selectedPaymentMethod?.name}");
context.read<OrderBloc>().add( // context.read<OrderBloc>().add(
OrderEvent.order( // OrderEvent.order(
items, // items,
discount, // discount,
discountAmountFinal, // discountAmountFinal,
finalTax.toInt(), // finalTax.toInt(),
0, // 0,
totalPriceController.text // totalPriceController.text
.toIntegerFromText, // .toIntegerFromText,
customerController.text, // customerController.text,
widget.table?.id ?? 0, // widget.table?.id ?? 0,
'completed', // 'completed',
'paid', // 'paid',
selectedPaymentMethod // selectedPaymentMethod
?.name ?? // ?.name ??
'Unknown Payment Method', // 'Unknown Payment Method',
totalPriceFinal, // totalPriceFinal,
orderType)); // orderType));
await showDialog( await showDialog(
context: context, context: context,

View File

@ -39,8 +39,8 @@ class _CardTableWidgetState extends State<CardTableWidget> {
loadData() async { loadData() async {
if (widget.table.status != 'available') { if (widget.table.status != 'available') {
data = await ProductLocalDatasource.instance // data = await ProductLocalDatasource.instance
.getDraftOrderById(widget.table.orderId); // .getDraftOrderById(widget.table.orderId);
} }
} }
@ -70,9 +70,10 @@ class _CardTableWidgetState extends State<CardTableWidget> {
), ),
), ),
Text( Text(
widget.table.status == 'available' // widget.table.status == 'available'
? widget.table.status // ? widget.table.status
: "${widget.table.status} - ${DateTime.parse(widget.table.startTime).toFormattedTime()}", // : "${widget.table.status} - ${DateTime.parse(widget.table.startTime).toFormattedTime()}",
"",
style: TextStyle( style: TextStyle(
color: AppColors.black, color: AppColors.black,
fontSize: 24, fontSize: 24,

View File

@ -51,8 +51,8 @@ class _TableWidgetState extends State<TableWidget> {
loadData() async { loadData() async {
if (widget.table.status != 'available') { if (widget.table.status != 'available') {
data = await ProductLocalDatasource.instance // data = await ProductLocalDatasource.instance
.getDraftOrderById(widget.table.orderId); // .getDraftOrderById(widget.table.orderId);
} }
} }
@ -136,33 +136,33 @@ class _TableWidgetState extends State<TableWidget> {
Expanded( Expanded(
child: Button.filled( child: Button.filled(
onPressed: () { onPressed: () {
final newData = // final newData =
TableModel( // TableModel(
id: widget.table.id, // id: widget.table.id,
tableName: // tableName:
tableNameController! // tableNameController!
.text, // .text,
status: // status:
widget.table.status, // widget.table.status,
startTime: widget // startTime: widget
.table.startTime, // .table.startTime,
orderId: widget // orderId: widget
.table.orderId, // .table.orderId,
paymentAmount: widget // paymentAmount: widget
.table // .table
.paymentAmount, // .paymentAmount,
position: widget // position: widget
.table.position, // .table.position,
); // );
context // context
.read< // .read<
UpdateTableBloc>() // UpdateTableBloc>()
.add( // .add(
UpdateTableEvent // UpdateTableEvent
.updateTable( // .updateTable(
newData, // newData,
), // ),
); // );
context context
.pop(); // close dialog after adding .pop(); // close dialog after adding
}, },
@ -194,16 +194,16 @@ class _TableWidgetState extends State<TableWidget> {
color: widget.table.status == 'available' color: widget.table.status == 'available'
? Colors.green ? Colors.green
: Colors.red), : Colors.red),
widget.table.status == 'available' // widget.table.status == 'available'
? SizedBox.shrink() // ? SizedBox.shrink()
: _buildInfoRow( // : _buildInfoRow(
'Start Time:', // 'Start Time:',
DateFormatter.formatDateTime2( // DateFormatter.formatDateTime2(
widget.table.startTime)), // widget.table.startTime)),
widget.table.status == 'available' // widget.table.status == 'available'
? SizedBox.shrink() // ? SizedBox.shrink()
: _buildInfoRow( // : _buildInfoRow(
'Order ID:', widget.table.orderId.toString()), // 'Order ID:', widget.table.orderId.toString()),
widget.table.status == 'available' widget.table.status == 'available'
? SizedBox.shrink() ? SizedBox.shrink()
: SpaceHeight(16), : SpaceHeight(16),
@ -267,29 +267,29 @@ class _TableWidgetState extends State<TableWidget> {
backgroundColor: AppColors.red, backgroundColor: AppColors.red,
), ),
onPressed: () { onPressed: () {
// Void the order // // Void the order
final newTable = TableModel( // final newTable = TableModel(
id: widget.table.id, // id: widget.table.id,
tableName: // tableName:
widget.table.tableName, // widget.table.tableName,
status: 'available', // status: 'available',
orderId: 0, // orderId: 0,
paymentAmount: 0, // paymentAmount: 0,
startTime: DateTime.now() // startTime: DateTime.now()
.toIso8601String(), // .toIso8601String(),
position: widget.table.position, // position: widget.table.position,
); // );
context // context
.read<StatusTableBloc>() // .read<StatusTableBloc>()
.add( // .add(
StatusTableEvent // StatusTableEvent
.statusTabel(newTable), // .statusTabel(newTable),
); // );
// Remove draft order from local storage // // Remove draft order from local storage
ProductLocalDatasource.instance // ProductLocalDatasource.instance
.removeDraftOrderById( // .removeDraftOrderById(
widget.table.orderId); // widget.table.orderId);
log("Voided order for table: ${widget.table.tableName}"); // log("Voided order for table: ${widget.table.tableName}");
}, },
child: const Text( child: const Text(
"Ya, Batalkan", "Ya, Batalkan",