first commit
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
import 'package:enaklo_pos/data/models/response/auth_response_model.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class AuthLocalDataSource {
|
||||
Future<void> saveAuthData(AuthResponseModel authResponseModel) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString('auth_data', authResponseModel.toJson());
|
||||
}
|
||||
|
||||
Future<void> removeAuthData() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove('auth_data');
|
||||
}
|
||||
|
||||
Future<AuthResponseModel> getAuthData() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final authData = prefs.getString('auth_data');
|
||||
|
||||
return AuthResponseModel.fromJson(authData!);
|
||||
}
|
||||
|
||||
Future<bool> isAuthDataExists() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.containsKey('auth_data');
|
||||
}
|
||||
|
||||
Future<void> saveMidtransServerKey(String serverKey) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString('server_key', serverKey);
|
||||
}
|
||||
|
||||
//get midtrans server key
|
||||
Future<String> getMitransServerKey() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final serverKey = prefs.getString('server_key');
|
||||
return serverKey ?? '';
|
||||
}
|
||||
|
||||
// save size receipt
|
||||
Future<void> saveSizeReceipt(String sizeReceipt) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString('size_receipt', sizeReceipt);
|
||||
}
|
||||
|
||||
// get size receipt
|
||||
Future<String> getSizeReceipt() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final sizeReceipt = prefs.getString('size_receipt');
|
||||
return sizeReceipt ?? '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||
import 'package:enaklo_pos/data/models/response/auth_response_model.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
class AuthRemoteDatasource {
|
||||
Future<Either<String, AuthResponseModel>> login(
|
||||
String email, String password) async {
|
||||
final url = Uri.parse('${Variables.baseUrl}/api/login');
|
||||
final response = await http.post(
|
||||
url,
|
||||
body: {
|
||||
'email': email,
|
||||
'password': password,
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return Right(AuthResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
return const Left('Failed to login');
|
||||
}
|
||||
}
|
||||
|
||||
//logout
|
||||
Future<Either<String, bool>> logout() async {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final url = Uri.parse('${Variables.baseUrl}/api/logout');
|
||||
final response = await http.post(
|
||||
url,
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return const Right(true);
|
||||
} else {
|
||||
return const Left('Failed to logout');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||
import 'package:enaklo_pos/data/models/response/category_response_model.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
class CategoryRemoteDatasource {
|
||||
Future<Either<String, CategroyResponseModel>> getCategories() async {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final Map<String, String> headers = {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
};
|
||||
final response = await http.get(
|
||||
Uri.parse('${Variables.baseUrl}/api/api-categories'),
|
||||
headers: headers);
|
||||
log(response.statusCode.toString());
|
||||
log(response.body);
|
||||
if (response.statusCode == 200) {
|
||||
return right(CategroyResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
return left(response.body);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||
import 'package:enaklo_pos/data/models/response/discount_response_model.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
class DiscountRemoteDatasource {
|
||||
Future<Either<String, DiscountResponseModel>> getDiscounts() async {
|
||||
final url = Uri.parse('${Variables.baseUrl}/api/api-discounts');
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.get(url, headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
});
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return Right(DiscountResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
return const Left('Failed to get discounts');
|
||||
}
|
||||
}
|
||||
|
||||
Future<Either<String, bool>> addDiscount(
|
||||
String name,
|
||||
String description,
|
||||
int value,
|
||||
) async {
|
||||
final url = Uri.parse('${Variables.baseUrl}/api/api-discounts');
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.post(url, headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
}, body: {
|
||||
'name': name,
|
||||
'description': description,
|
||||
'value': value.toString(),
|
||||
'type': 'percentage',
|
||||
});
|
||||
|
||||
if (response.statusCode == 201) {
|
||||
return const Right(true);
|
||||
} else {
|
||||
return const Left('Failed to add discount');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||
import 'package:enaklo_pos/data/models/response/qris_response_model.dart';
|
||||
import 'package:enaklo_pos/data/models/response/qris_status_response_model.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
class MidtransRemoteDatasource {
|
||||
String generateBasicAuthHeader(String serverKey) {
|
||||
final base64Credentials = base64Encode(utf8.encode('$serverKey:'));
|
||||
final authHeader = 'Basic $base64Credentials';
|
||||
|
||||
return authHeader;
|
||||
}
|
||||
|
||||
Future<QrisResponseModel> generateQRCode(
|
||||
String orderId, int grossAmount) async {
|
||||
final serverKey = await AuthLocalDataSource().getMitransServerKey();
|
||||
final headers = {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': generateBasicAuthHeader(serverKey),
|
||||
};
|
||||
|
||||
final body = jsonEncode({
|
||||
'payment_type': 'gopay',
|
||||
'transaction_details': {
|
||||
'gross_amount': grossAmount,
|
||||
'order_id': orderId,
|
||||
},
|
||||
});
|
||||
|
||||
final response = await http.post(
|
||||
Uri.parse('https://api.midtrans.com/v2/charge'),
|
||||
// Uri.parse('https://api.sandbox.midtrans.com/v2/charge'),
|
||||
|
||||
headers: headers,
|
||||
body: body,
|
||||
);
|
||||
|
||||
log("StatusCode: ${response.statusCode}");
|
||||
log("Body: ${response.body}");
|
||||
|
||||
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||
return QrisResponseModel.fromJson(response.body);
|
||||
} else {
|
||||
throw Exception('Failed to generate QR Code');
|
||||
}
|
||||
}
|
||||
|
||||
Future<QrisStatusResponseModel> checkPaymentStatus(String orderId) async {
|
||||
final serverKey = await AuthLocalDataSource().getMitransServerKey();
|
||||
final headers = {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': generateBasicAuthHeader(serverKey),
|
||||
};
|
||||
|
||||
final response = await http.get(
|
||||
Uri.parse('https://api.midtrans.com/v2/$orderId/status'),
|
||||
// Uri.parse('https://api.sandbox.midtrans.com/v2/$orderId/status'),
|
||||
headers: headers,
|
||||
);
|
||||
log("StatusCode: ${response.statusCode}");
|
||||
log("Body: ${response.body}");
|
||||
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||
return QrisStatusResponseModel.fromJson(response.body);
|
||||
} else {
|
||||
throw Exception('Failed to check payment status');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'dart:developer';
|
||||
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||
import 'package:enaklo_pos/data/models/response/item_sales_response_model.dart';
|
||||
import 'package:enaklo_pos/data/models/response/product_sales_response_model.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:dartz/dartz.dart';
|
||||
|
||||
class OrderItemRemoteDatasource {
|
||||
Future<Either<String, ItemSalesResponseModel>> getItemSalesByRangeDate(
|
||||
String stratDate,
|
||||
String endDate,
|
||||
) async {
|
||||
try {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.get(
|
||||
Uri.parse(
|
||||
'${Variables.baseUrl}/api/order-item?start_date=$stratDate&end_date=$endDate'),
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
log("Response: ${response.statusCode}");
|
||||
log("Response: ${response.body}");
|
||||
if (response.statusCode == 200) {
|
||||
return Right(ItemSalesResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
return const Left("Failed Load Data");
|
||||
}
|
||||
} catch (e) {
|
||||
log("Error: $e");
|
||||
return Left("Failed: $e");
|
||||
}
|
||||
}
|
||||
|
||||
Future<Either<String, ProductSalesResponseModel>> getProductSalesByRangeDate(
|
||||
String stratDate,
|
||||
String endDate,
|
||||
) async {
|
||||
try {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.get(
|
||||
Uri.parse(
|
||||
'${Variables.baseUrl}/api/order-sales?start_date=$stratDate&end_date=$endDate'),
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
log("Response: ${response.statusCode}");
|
||||
log("Response: ${response.body}");
|
||||
if (response.statusCode == 200) {
|
||||
return Right(ProductSalesResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
return const Left("Failed Load Data");
|
||||
}
|
||||
} catch (e) {
|
||||
log("Error: $e");
|
||||
return Left("Failed: $e");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||
import 'package:enaklo_pos/data/models/response/order_remote_datasource.dart';
|
||||
import 'package:enaklo_pos/data/models/response/payment_method_response_model.dart';
|
||||
import 'package:enaklo_pos/data/models/response/summary_response_model.dart';
|
||||
import 'package:enaklo_pos/presentation/home/models/order_model.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
class OrderRemoteDatasource {
|
||||
//save order to remote server
|
||||
Future<bool> saveOrder(OrderModel orderModel) async {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
print("🌐 API CALL: saveOrder");
|
||||
print("📡 URL: ${Variables.baseUrl}/api/save-order");
|
||||
print("🔑 Token: ${authData.token?.substring(0, 20)}...");
|
||||
try {
|
||||
final response = await http.post(
|
||||
Uri.parse('${Variables.baseUrl}/api/save-order'),
|
||||
body: orderModel.toJson(),
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
|
||||
print("📥 HTTP Status Code: ${response.statusCode}");
|
||||
print("📥 Response Body: ${response.body}");
|
||||
print("📥 Response Headers: ${response.headers}");
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
print("✅ API call successful - Order saved to server");
|
||||
return true;
|
||||
} else {
|
||||
print("❌ API call failed - Status: ${response.statusCode}");
|
||||
print("❌ Error Response: ${response.body}");
|
||||
return false;
|
||||
}
|
||||
} catch (e) {
|
||||
print("💥 API call error: $e");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<Either<String, OrderResponseModel>> getOrderByRangeDate(
|
||||
String stratDate,
|
||||
String endDate,
|
||||
) async {
|
||||
try {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.get(
|
||||
Uri.parse(
|
||||
'${Variables.baseUrl}/api/orders?start_date=$stratDate&end_date=$endDate'),
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
print("📥 HTTP Status Code: ${response.statusCode}");
|
||||
print("📥 Response Body: ${response.body}");
|
||||
print("📥 Response Headers: ${response.headers}");
|
||||
if (response.statusCode == 200) {
|
||||
print("✅ getOrderByRangeDate API call successful");
|
||||
return Right(OrderResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
print("❌ getOrderByRangeDate API call failed - Status: ${response.statusCode}");
|
||||
print("❌ Error Response: ${response.body}");
|
||||
return const Left("Failed Load Data");
|
||||
}
|
||||
} catch (e) {
|
||||
print("💥 getOrderByRangeDate API call error: $e");
|
||||
return Left("Failed: $e");
|
||||
}
|
||||
}
|
||||
|
||||
Future<Either<String, SummaryResponseModel>> getSummaryByRangeDate(
|
||||
String stratDate,
|
||||
String endDate,
|
||||
) async {
|
||||
try {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.get(
|
||||
Uri.parse(
|
||||
'${Variables.baseUrl}/api/summary?start_date=$stratDate&end_date=$endDate'),
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
print("📡 URL: ${response.request!.url}");
|
||||
print("📥 HTTP Status Code: ${response.statusCode}");
|
||||
print("📥 Response Body: ${response.body}");
|
||||
print("📥 Response Headers: ${response.headers}");
|
||||
if (response.statusCode == 200) {
|
||||
print("✅ getSummaryByRangeDate API call successful");
|
||||
return Right(SummaryResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
print("❌ getSummaryByRangeDate API call failed - Status: ${response.statusCode}");
|
||||
print("❌ Error Response: ${response.body}");
|
||||
return const Left("Failed Load Data");
|
||||
}
|
||||
} catch (e) {
|
||||
print("💥 getSummaryByRangeDate API call error: $e");
|
||||
return Left("Failed: $e");
|
||||
}
|
||||
}
|
||||
|
||||
Future<Either<String, PaymentMethodResponseModel>> getPaymentMethodByRangeDate(
|
||||
String startDate,
|
||||
String endDate,
|
||||
) async {
|
||||
try {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.get(
|
||||
Uri.parse(
|
||||
'${Variables.baseUrl}/api/order-paymentmethod?start_date=$startDate&end_date=$endDate'),
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
print("📥 Payment Method HTTP Status Code: ${response.statusCode}");
|
||||
print("📥 Payment Method Response Body: ${response.body}");
|
||||
print("📥 Payment Method Response Headers: ${response.headers}");
|
||||
if (response.statusCode == 200) {
|
||||
print("✅ getPaymentMethodByRangeDate API call successful");
|
||||
return Right(PaymentMethodResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
print("❌ getPaymentMethodByRangeDate API call failed - Status: ${response.statusCode}");
|
||||
print("❌ Error Response: ${response.body}");
|
||||
return const Left("Failed Load Payment Method Data");
|
||||
}
|
||||
} catch (e) {
|
||||
print("💥 getPaymentMethodByRangeDate API call error: $e");
|
||||
return Left("Failed: $e");
|
||||
}
|
||||
}
|
||||
|
||||
Future<Either<String, bool>> addOrderItems(
|
||||
int orderId,
|
||||
List<Map<String, dynamic>> orderItems,
|
||||
) async {
|
||||
try {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.post(
|
||||
Uri.parse('${Variables.baseUrl}/api/orders/add-items'),
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: jsonEncode({
|
||||
'order_id': orderId,
|
||||
'order_items': orderItems,
|
||||
}),
|
||||
);
|
||||
|
||||
print("📥 Add Order Items HTTP Status Code: ${response.statusCode}");
|
||||
print("📥 Add Order Items Response Body: ${response.body}");
|
||||
print("📥 Add Order Items Response Headers: ${response.headers}");
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
print("✅ addOrderItems API call successful");
|
||||
return const Right(true);
|
||||
} else {
|
||||
print("❌ addOrderItems API call failed - Status: ${response.statusCode}");
|
||||
print("❌ Error Response: ${response.body}");
|
||||
return Left("Failed to add order items: ${response.body}");
|
||||
}
|
||||
} catch (e) {
|
||||
print("💥 addOrderItems API call error: $e");
|
||||
return Left("Failed: $e");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||
import 'package:enaklo_pos/data/models/response/payment_methods_response_model.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
class PaymentMethodsRemoteDatasource {
|
||||
Future<Either<String, PaymentMethodsResponseModel>> getPaymentMethods() async {
|
||||
try {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.get(
|
||||
Uri.parse('${Variables.baseUrl}/api/payment-methods'),
|
||||
headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
);
|
||||
|
||||
log("Payment Methods Response Status: ${response.statusCode}");
|
||||
log("Payment Methods Response Body: ${response.body}");
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return Right(PaymentMethodsResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
return const Left('Failed to get payment methods');
|
||||
}
|
||||
} catch (e) {
|
||||
log("Error getting payment methods: $e");
|
||||
return Left('Error: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,613 @@
|
||||
import 'dart:developer';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:enaklo_pos/data/models/response/print_model.dart';
|
||||
import 'package:enaklo_pos/data/models/response/product_response_model.dart';
|
||||
import 'package:enaklo_pos/data/models/response/table_model.dart';
|
||||
import 'package:enaklo_pos/presentation/home/models/order_model.dart';
|
||||
import 'package:enaklo_pos/presentation/table/models/draft_order_item.dart';
|
||||
import 'package:enaklo_pos/presentation/table/models/draft_order_model.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
|
||||
import '../../presentation/home/models/product_quantity.dart';
|
||||
|
||||
class ProductLocalDatasource {
|
||||
ProductLocalDatasource._init();
|
||||
|
||||
static final ProductLocalDatasource instance = ProductLocalDatasource._init();
|
||||
|
||||
final String tableProduct = 'products';
|
||||
final String tableOrder = 'orders';
|
||||
final String tableOrderItem = 'order_items';
|
||||
final String tableManagement = 'table_management';
|
||||
final String tablePrint = 'prints';
|
||||
static Database? _database;
|
||||
|
||||
// "id": 1,
|
||||
// "category_id": 1,
|
||||
// "name": "Mie Ayam",
|
||||
// "description": "Ipsa dolorem impedit dolor. Libero nisi quidem expedita quod mollitia ad. Voluptas ut quia nemo nisi odit fuga. Fugit autem qui ratione laborum eum.",
|
||||
// "image": "https://via.placeholder.com/640x480.png/002200?text=nihil",
|
||||
// "price": "2000.44",
|
||||
// "stock": 94,
|
||||
// "status": 1,
|
||||
// "is_favorite": 1,
|
||||
// "created_at": "2024-02-08T14:30:22.000000Z",
|
||||
// "updated_at": "2024-02-08T15:14:22.000000Z"
|
||||
|
||||
Future<void> _createDb(Database db, int version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE $tableProduct (
|
||||
id INTEGER PRIMARY KEY,
|
||||
product_id INTEGER,
|
||||
name TEXT,
|
||||
printer_type TEXT,
|
||||
categoryId INTEGER,
|
||||
categoryName TEXT,
|
||||
description TEXT,
|
||||
image TEXT,
|
||||
price TEXT,
|
||||
stock INTEGER,
|
||||
status INTEGER,
|
||||
isFavorite INTEGER,
|
||||
createdAt TEXT,
|
||||
updatedAt TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE $tableOrder (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
payment_amount INTEGER,
|
||||
sub_total INTEGER,
|
||||
tax INTEGER,
|
||||
discount INTEGER,
|
||||
discount_amount INTEGER,
|
||||
service_charge INTEGER,
|
||||
total INTEGER,
|
||||
payment_method TEXT,
|
||||
total_item INTEGER,
|
||||
id_kasir INTEGER,
|
||||
nama_kasir TEXT,
|
||||
transaction_time TEXT,
|
||||
table_number INTEGER,
|
||||
customer_name TEXT,
|
||||
status TEXT,
|
||||
payment_status TEXT,
|
||||
order_type TEXT DEFAULT 'DINE IN',
|
||||
is_sync INTEGER DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE $tableOrderItem (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
id_order INTEGER,
|
||||
id_product INTEGER,
|
||||
quantity INTEGER,
|
||||
price INTEGER,
|
||||
notes TEXT DEFAULT ''
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE $tableManagement (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
table_name Text,
|
||||
start_time Text,
|
||||
order_id INTEGER,
|
||||
payment_amount INTEGER,
|
||||
x_position REAL NOT NULL,
|
||||
y_position REAL NOT NULL,
|
||||
status TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE draft_orders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
total_item INTEGER,
|
||||
subtotal INTEGER,
|
||||
tax INTEGER,
|
||||
discount INTEGER,
|
||||
discount_amount INTEGER,
|
||||
service_charge INTEGER,
|
||||
total INTEGER,
|
||||
transaction_time TEXT,
|
||||
table_number INTEGER,
|
||||
draft_name TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE draft_order_items (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
id_draft_order INTEGER,
|
||||
id_product INTEGER,
|
||||
quantity INTEGER,
|
||||
price INTEGER
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE $tablePrint (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code TEXT,
|
||||
name TEXT,
|
||||
address TEXT,
|
||||
paper TEXT,
|
||||
type TEXT
|
||||
)
|
||||
''');
|
||||
}
|
||||
|
||||
Future<Database> _initDB(String filePath) async {
|
||||
final dbPath = await getDatabasesPath();
|
||||
final path = dbPath + filePath;
|
||||
|
||||
// Force delete existing database to ensure new schema
|
||||
try {
|
||||
final dbExists = await databaseExists(path);
|
||||
if (dbExists) {
|
||||
log("Deleting existing database to ensure new schema with order_type column");
|
||||
await deleteDatabase(path);
|
||||
}
|
||||
} catch (e) {
|
||||
log("Error deleting database: $e");
|
||||
}
|
||||
|
||||
return await openDatabase(
|
||||
path,
|
||||
version: 2,
|
||||
onCreate: _createDb,
|
||||
onUpgrade: _onUpgrade,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
|
||||
if (oldVersion < 2) {
|
||||
// Add order_type column to orders table if it doesn't exist
|
||||
try {
|
||||
await db.execute('ALTER TABLE $tableOrder ADD COLUMN order_type TEXT DEFAULT "DINE IN"');
|
||||
log("Added order_type column to orders table");
|
||||
} catch (e) {
|
||||
log("order_type column might already exist: $e");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<Database> get database async {
|
||||
if (_database != null) return _database!;
|
||||
_database = await _initDB('dbresto36.db');
|
||||
return _database!;
|
||||
}
|
||||
|
||||
//save order
|
||||
Future<int> saveOrder(OrderModel order) async {
|
||||
final db = await instance.database;
|
||||
|
||||
// Since we're forcing database recreation, order_type column should exist
|
||||
final orderMap = order.toMap(includeOrderType: true);
|
||||
log("Final orderMap for insertion: $orderMap");
|
||||
|
||||
int id = await db.insert(tableOrder, orderMap,
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
|
||||
for (var item in order.orderItems) {
|
||||
log("Item: ${item.toLocalMap(id)}");
|
||||
await db.insert(tableOrderItem, item.toLocalMap(id),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
log("Success Order: ${order.toMap()}");
|
||||
return id;
|
||||
}
|
||||
|
||||
//get data order
|
||||
Future<List<OrderModel>> getOrderByIsNotSync() async {
|
||||
final db = await instance.database;
|
||||
final List<Map<String, dynamic>> maps =
|
||||
await db.query(tableOrder, where: 'is_sync = ?', whereArgs: [0]);
|
||||
return List.generate(maps.length, (i) {
|
||||
return OrderModel.fromMap(maps[i]);
|
||||
});
|
||||
}
|
||||
|
||||
Future<List<OrderModel>> getAllOrder(
|
||||
DateTime date,
|
||||
) async {
|
||||
final db = await instance.database;
|
||||
//date to iso8601
|
||||
final dateIso = date.toIso8601String();
|
||||
//get yyyy-MM-dd
|
||||
final dateYYYYMMDD = dateIso.substring(0, 10);
|
||||
// final formattedDate = DateFormat('yyyy-MM-dd').format(date);
|
||||
final List<Map<String, dynamic>> maps = await db.query(
|
||||
tableOrder,
|
||||
where: 'transaction_time like ?',
|
||||
whereArgs: ['$dateYYYYMMDD%'],
|
||||
// where: 'transaction_time BETWEEN ? AND ?',
|
||||
// whereArgs: [
|
||||
// DateFormat.yMd().format(start),
|
||||
// DateFormat.yMd().format(end)
|
||||
// ],
|
||||
);
|
||||
return List.generate(maps.length, (i) {
|
||||
log("Save save OrderModel: ${OrderModel.fromMap(maps[i])}");
|
||||
return OrderModel.fromMap(maps[i]);
|
||||
});
|
||||
}
|
||||
|
||||
//get order item by order id
|
||||
Future<List<ProductQuantity>> getOrderItemByOrderId(int orderId) async {
|
||||
final db = await instance.database;
|
||||
final List<Map<String, dynamic>> maps = await db
|
||||
.query(tableOrderItem, where: 'id_order = ?', whereArgs: [orderId]);
|
||||
return List.generate(maps.length, (i) {
|
||||
log("ProductQuantity: ${ProductQuantity.fromLocalMap(maps[i])}");
|
||||
return ProductQuantity.fromLocalMap(maps[i]);
|
||||
});
|
||||
}
|
||||
|
||||
//update payment status by order id
|
||||
Future<void> updatePaymentStatus(
|
||||
int orderId, String paymentStatus, String status) async {
|
||||
final db = await instance.database;
|
||||
await db.update(
|
||||
tableOrder, {'payment_status': paymentStatus, 'status': status},
|
||||
where: 'id = ?', whereArgs: [orderId]);
|
||||
log('update payment status success | order id: $orderId | payment status: $paymentStatus | status: $status');
|
||||
}
|
||||
|
||||
//update order is sync
|
||||
Future<void> updateOrderIsSync(int orderId) async {
|
||||
final db = await instance.database;
|
||||
await db.update(tableOrder, {'is_sync': 1},
|
||||
where: 'id = ?', whereArgs: [orderId]);
|
||||
}
|
||||
|
||||
//insert data product
|
||||
|
||||
Future<void> insertProduct(Product product) async {
|
||||
log("Product: ${product.toMap()}");
|
||||
final db = await instance.database;
|
||||
await db.insert(tableProduct, product.toMap(),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
|
||||
//update product
|
||||
Future<void> updateProduct(Product product) async {
|
||||
log("Update Product: ${product.toMap()}");
|
||||
final db = await instance.database;
|
||||
await db.update(
|
||||
tableProduct,
|
||||
product.toLocalMap(),
|
||||
where: 'product_id = ?',
|
||||
whereArgs: [product.productId],
|
||||
);
|
||||
}
|
||||
|
||||
//insert list of product
|
||||
Future<void> insertProducts(List<Product> products) async {
|
||||
final db = await instance.database;
|
||||
log("Save Products to Local");
|
||||
for (var product in products) {
|
||||
await db.insert(tableProduct, product.toLocalMap(),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
log('inserted success id: ${product.productId} | name: ${product.name} | price: ${product.price} | Printer Type ${product.printerType}');
|
||||
}
|
||||
}
|
||||
|
||||
//get all products
|
||||
Future<List<Product>> getProducts() async {
|
||||
final db = await instance.database;
|
||||
final List<Map<String, dynamic>> maps = await db.query(tableProduct);
|
||||
return List.generate(maps.length, (i) {
|
||||
return Product.fromLocalMap(maps[i]);
|
||||
});
|
||||
}
|
||||
|
||||
Future<Product?> getProductById(int id) async {
|
||||
final db = await instance.database;
|
||||
final result =
|
||||
await db.query(tableProduct, where: 'product_id = ?', whereArgs: [id]);
|
||||
|
||||
if (result.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Product.fromMap(result.first);
|
||||
}
|
||||
|
||||
// get Last Table Management
|
||||
|
||||
Future<TableModel?> getLastTableManagement() async {
|
||||
final db = await instance.database;
|
||||
final List<Map<String, dynamic>> maps =
|
||||
await db.query(tableManagement, orderBy: 'id DESC', limit: 1);
|
||||
if (maps.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return TableModel.fromMap(maps[0]);
|
||||
}
|
||||
|
||||
// generate table managent with count
|
||||
Future<void> createTableManagement(String tableName, Offset position) async {
|
||||
final db = await instance.database;
|
||||
TableModel newTable = TableModel(
|
||||
tableName: tableName,
|
||||
status: 'available',
|
||||
orderId: 0,
|
||||
paymentAmount: 0,
|
||||
startTime: DateTime.now().toIso8601String(),
|
||||
position: position,
|
||||
);
|
||||
await db.insert(
|
||||
tableManagement,
|
||||
newTable.toMap(),
|
||||
);
|
||||
}
|
||||
|
||||
// change position table
|
||||
Future<void> changePositionTable(int id, Offset position) async {
|
||||
final db = await instance.database;
|
||||
await db.update(
|
||||
tableManagement,
|
||||
{'x_position': position.dx, 'y_position': position.dy},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
// update table
|
||||
Future<void> updateTable(TableModel table) async {
|
||||
final db = await instance.database;
|
||||
await db.update(
|
||||
tableManagement,
|
||||
table.toMap(),
|
||||
where: 'id = ?',
|
||||
whereArgs: [table.id],
|
||||
);
|
||||
}
|
||||
|
||||
// get all table
|
||||
Future<List<TableModel>> getAllTable() async {
|
||||
final db = await instance.database;
|
||||
final List<Map<String, dynamic>> maps = await db.query(tableManagement);
|
||||
log("Table Management: $maps");
|
||||
return List.generate(maps.length, (i) {
|
||||
return TableModel.fromMap(maps[i]);
|
||||
});
|
||||
}
|
||||
|
||||
// get last order where table number
|
||||
Future<OrderModel?> getLastOrderTable(int tableNumber) async {
|
||||
final db = await instance.database;
|
||||
final List<Map<String, dynamic>> maps = await db.query(
|
||||
tableOrder,
|
||||
where: 'table_number = ?',
|
||||
whereArgs: [tableNumber],
|
||||
orderBy: 'id DESC', // Urutkan berdasarkan id dari yang terbesar (terbaru)
|
||||
limit: 1, // Ambil hanya satu data terakhir
|
||||
);
|
||||
|
||||
if (maps.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return OrderModel.fromMap(maps[0]);
|
||||
}
|
||||
|
||||
// get table by status
|
||||
Future<List<TableModel>> getTableByStatus(String status) async {
|
||||
final db = await instance.database;
|
||||
List<Map<String, dynamic>> maps;
|
||||
|
||||
if (status == 'all') {
|
||||
// Get all tables
|
||||
maps = await db.query(tableManagement);
|
||||
log("Getting all tables, found: ${maps.length}");
|
||||
|
||||
// If no tables exist, create some default tables
|
||||
if (maps.isEmpty) {
|
||||
log("No tables found, creating default tables...");
|
||||
await _createDefaultTables();
|
||||
maps = await db.query(tableManagement);
|
||||
log("After creating default tables, found: ${maps.length}");
|
||||
}
|
||||
} else {
|
||||
// Get tables by specific status
|
||||
maps = await db.query(
|
||||
tableManagement,
|
||||
where: 'status = ?',
|
||||
whereArgs: [status],
|
||||
);
|
||||
log("Getting tables with status '$status', found: ${maps.length}");
|
||||
}
|
||||
|
||||
final tables = List.generate(maps.length, (i) {
|
||||
return TableModel.fromMap(maps[i]);
|
||||
});
|
||||
|
||||
log("Returning ${tables.length} tables");
|
||||
tables.forEach((table) {
|
||||
log("Table: ${table.tableName} (ID: ${table.id}, Status: ${table.status})");
|
||||
});
|
||||
|
||||
return tables;
|
||||
}
|
||||
|
||||
// Create default tables if none exist
|
||||
Future<void> _createDefaultTables() async {
|
||||
final db = await instance.database;
|
||||
|
||||
// Create 5 default tables
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
await db.insert(tableManagement, {
|
||||
'table_name': 'Table $i',
|
||||
'start_time': DateTime.now().toIso8601String(),
|
||||
'order_id': 0,
|
||||
'payment_amount': 0,
|
||||
'x_position': 100.0 + (i * 50.0),
|
||||
'y_position': 100.0 + (i * 50.0),
|
||||
'status': 'available',
|
||||
});
|
||||
log("Created default table: Table $i");
|
||||
}
|
||||
}
|
||||
|
||||
// update status tabel
|
||||
Future<void> updateStatusTable(TableModel table) async {
|
||||
log("Updating table status: ${table.toMap()}");
|
||||
final db = await instance.database;
|
||||
await db.update(tableManagement, table.toMap(),
|
||||
where: 'id = ?', whereArgs: [table.id]);
|
||||
log("Success Update Status Table: ${table.toMap()}");
|
||||
|
||||
// Verify the update
|
||||
final updatedTable = await db.query(
|
||||
tableManagement,
|
||||
where: 'id = ?',
|
||||
whereArgs: [table.id],
|
||||
);
|
||||
if (updatedTable.isNotEmpty) {
|
||||
log("Verified table update: ${updatedTable.first}");
|
||||
}
|
||||
}
|
||||
|
||||
// Debug method to reset all tables to available status
|
||||
Future<void> resetAllTablesToAvailable() async {
|
||||
log("Resetting all tables to available status...");
|
||||
final db = await instance.database;
|
||||
await db.update(
|
||||
tableManagement,
|
||||
{
|
||||
'status': 'available',
|
||||
'order_id': 0,
|
||||
'payment_amount': 0,
|
||||
'start_time': DateTime.now().toIso8601String(),
|
||||
},
|
||||
);
|
||||
log("All tables reset to available status");
|
||||
}
|
||||
|
||||
//delete all products
|
||||
Future<void> deleteAllProducts() async {
|
||||
final db = await instance.database;
|
||||
await db.delete(tableProduct);
|
||||
}
|
||||
|
||||
Future<int> saveDraftOrder(DraftOrderModel order) async {
|
||||
log("save draft order: ${order.toMapForLocal()}");
|
||||
final db = await instance.database;
|
||||
int id = await db.insert('draft_orders', order.toMapForLocal());
|
||||
log("draft order id: $id | ${order.discountAmount}");
|
||||
for (var orderItem in order.orders) {
|
||||
await db.insert('draft_order_items', orderItem.toMapForLocal(id));
|
||||
log("draft order item ${orderItem.toMapForLocal(id)}");
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
//get all draft order
|
||||
Future<List<DraftOrderModel>> getAllDraftOrder() async {
|
||||
final db = await instance.database;
|
||||
final result = await db.query('draft_orders', orderBy: 'id ASC');
|
||||
|
||||
List<DraftOrderModel> results = await Future.wait(result.map((item) async {
|
||||
// Your asynchronous operation here
|
||||
final draftOrderItem =
|
||||
await getDraftOrderItemByOrderId(item['id'] as int);
|
||||
return DraftOrderModel.newFromLocalMap(item, draftOrderItem);
|
||||
}));
|
||||
return results;
|
||||
}
|
||||
|
||||
// get Darft Order by id
|
||||
Future<DraftOrderModel?> getDraftOrderById(int id) async {
|
||||
final db = await instance.database;
|
||||
final result =
|
||||
await db.query('draft_orders', where: 'id = ?', whereArgs: [id]);
|
||||
if (result.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final draftOrderItem =
|
||||
await getDraftOrderItemByOrderId(result.first['id'] as int);
|
||||
log("draft order item: $draftOrderItem | ${result.first.toString()}");
|
||||
return DraftOrderModel.newFromLocalMap(result.first, draftOrderItem);
|
||||
}
|
||||
|
||||
//get draft order item by id order
|
||||
Future<List<DraftOrderItem>> getDraftOrderItemByOrderId(int idOrder) async {
|
||||
final db = await instance.database;
|
||||
final result =
|
||||
await db.query('draft_order_items', where: 'id_draft_order = $idOrder');
|
||||
|
||||
List<DraftOrderItem> results = await Future.wait(result.map((item) async {
|
||||
// Your asynchronous operation here
|
||||
final product = await getProductById(item['id_product'] as int);
|
||||
return DraftOrderItem(
|
||||
product: product!, quantity: item['quantity'] as int);
|
||||
}));
|
||||
return results;
|
||||
}
|
||||
|
||||
//remove draft order by id
|
||||
Future<void> removeDraftOrderById(int id) async {
|
||||
final db = await instance.database;
|
||||
await db.delete('draft_orders', where: 'id = ?', whereArgs: [id]);
|
||||
await db.delete('draft_order_items',
|
||||
where: 'id_draft_order = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
//update draft order
|
||||
Future<void> updateDraftOrder(DraftOrderModel draftOrder) async {
|
||||
final db = await instance.database;
|
||||
|
||||
// Update the draft order
|
||||
await db.update(
|
||||
'draft_orders',
|
||||
draftOrder.toMapForLocal(),
|
||||
where: 'id = ?',
|
||||
whereArgs: [draftOrder.id],
|
||||
);
|
||||
|
||||
// Remove existing items and add new ones
|
||||
await db.delete('draft_order_items',
|
||||
where: 'id_draft_order = ?', whereArgs: [draftOrder.id]);
|
||||
|
||||
for (var orderItem in draftOrder.orders) {
|
||||
await db.insert('draft_order_items', orderItem.toMapForLocal(draftOrder.id!));
|
||||
}
|
||||
}
|
||||
|
||||
/// create printer
|
||||
Future<void> createPrinter(PrintModel print) async {
|
||||
final db = await instance.database;
|
||||
await db.insert(tablePrint, print.toMap());
|
||||
}
|
||||
|
||||
Future<void> updatePrinter(PrintModel print, int id) async {
|
||||
final db = await instance.database;
|
||||
log("Update Printer: ${print.toMap()} | id: $id");
|
||||
await db
|
||||
.update(tablePrint, print.toMap(), where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<void> deletePrinter(int id) async {
|
||||
final db = await instance.database;
|
||||
await db.delete(tablePrint, where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
// get printer by code
|
||||
Future<PrintModel?> getPrinterByCode(String code) async {
|
||||
final db = await instance.database;
|
||||
final result =
|
||||
await db.query(tablePrint, where: 'code = ?', whereArgs: [code]);
|
||||
if (result.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return PrintModel.fromMap(result.first);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:enaklo_pos/data/models/request/product_request_model.dart';
|
||||
import 'package:enaklo_pos/data/models/response/add_product_response_model.dart';
|
||||
import 'package:enaklo_pos/data/models/response/product_response_model.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../core/constants/variables.dart';
|
||||
import 'auth_local_datasource.dart';
|
||||
|
||||
class ProductRemoteDatasource {
|
||||
Future<Either<String, ProductResponseModel>> getProducts() async {
|
||||
final url = Uri.parse('${Variables.baseUrl}/api/products');
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final response = await http.get(url, headers: {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
'Accept': 'application/json',
|
||||
});
|
||||
log("Status Code: ${response.statusCode}");
|
||||
log("Body: ${response.body}");
|
||||
if (response.statusCode == 200) {
|
||||
return Right(ProductResponseModel.fromJson(response.body));
|
||||
} else {
|
||||
return const Left('Failed to get products');
|
||||
}
|
||||
}
|
||||
|
||||
Future<Either<String, AddProductResponseModel>> addProduct(
|
||||
ProductRequestModel productRequestModel) async {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final Map<String, String> headers = {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
};
|
||||
var request = http.MultipartRequest(
|
||||
'POST', Uri.parse('${Variables.baseUrl}/api/products'));
|
||||
request.fields.addAll(productRequestModel.toMap());
|
||||
request.files.add(await http.MultipartFile.fromPath(
|
||||
'image', productRequestModel.image!.path));
|
||||
request.headers.addAll(headers);
|
||||
|
||||
http.StreamedResponse response = await request.send();
|
||||
|
||||
final String body = await response.stream.bytesToString();
|
||||
log(response.stream.toString());
|
||||
log(response.statusCode.toString());
|
||||
if (response.statusCode == 201) {
|
||||
return right(AddProductResponseModel.fromJson(body));
|
||||
} else {
|
||||
return left(body);
|
||||
}
|
||||
}
|
||||
|
||||
Future<Either<String, AddProductResponseModel>> updateProduct(
|
||||
ProductRequestModel productRequestModel) async {
|
||||
final authData = await AuthLocalDataSource().getAuthData();
|
||||
final Map<String, String> headers = {
|
||||
'Authorization': 'Bearer ${authData.token}',
|
||||
};
|
||||
|
||||
log("Update Product Request Data: ${productRequestModel.toMap()}");
|
||||
log("Update Product ID: ${productRequestModel.id}");
|
||||
log("Update Product Name: ${productRequestModel.name}");
|
||||
log("Update Product Price: ${productRequestModel.price}");
|
||||
log("Update Product Stock: ${productRequestModel.stock}");
|
||||
log("Update Product Category ID: ${productRequestModel.categoryId}");
|
||||
log("Update Product Is Best Seller: ${productRequestModel.isBestSeller}");
|
||||
log("Update Product Printer Type: ${productRequestModel.printerType}");
|
||||
log("Update Product Has Image: ${productRequestModel.image != null}");
|
||||
|
||||
var request = http.MultipartRequest(
|
||||
'POST', Uri.parse('${Variables.baseUrl}/api/products/edit'));
|
||||
request.fields.addAll(productRequestModel.toMap());
|
||||
if (productRequestModel.image != null) {
|
||||
request.files.add(await http.MultipartFile.fromPath(
|
||||
'image', productRequestModel.image!.path));
|
||||
}
|
||||
request.headers.addAll(headers);
|
||||
|
||||
log("Update Product Request Fields: ${request.fields}");
|
||||
log("Update Product Request Files: ${request.files.length}");
|
||||
|
||||
http.StreamedResponse response = await request.send();
|
||||
|
||||
final String body = await response.stream.bytesToString();
|
||||
log("Update Product Status Code: ${response.statusCode}");
|
||||
log("Update Product Body: $body");
|
||||
if (response.statusCode == 200) {
|
||||
return right(AddProductResponseModel.fromJson(body));
|
||||
} else {
|
||||
return left(body);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../presentation/setting/models/tax_model.dart';
|
||||
|
||||
class SettingsLocalDatasource {
|
||||
// save tax to shared preferences
|
||||
Future<bool> saveTax(TaxModel taxModel) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.setString('tax', taxModel.toJson());
|
||||
}
|
||||
|
||||
// get tax from shared preferences
|
||||
Future<TaxModel> getTax() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final tax = prefs.getString('tax');
|
||||
if (tax != null) {
|
||||
return TaxModel.fromJson(tax);
|
||||
} else {
|
||||
return TaxModel(
|
||||
name: 'Tax',
|
||||
type: TaxType.pajak,
|
||||
value: 11,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// save service charge to shared preferences
|
||||
Future<bool> saveServiceCharge(int serviceCharge) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.setInt('serviceCharge', serviceCharge);
|
||||
}
|
||||
|
||||
// get service charge from shared preferences
|
||||
Future<int> getServiceCharge() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getInt('serviceCharge') ?? 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user