apskel-pos-flutter/lib/data/datasources/customer_remote_datasource.dart
2025-08-03 16:13:33 +07:00

102 lines
2.8 KiB
Dart

import 'dart:developer';
import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:enaklo_pos/core/network/dio_client.dart';
import 'package:enaklo_pos/data/models/response/customer_response_model.dart';
import '../../core/constants/variables.dart';
import 'auth_local_datasource.dart';
class CustomerRemoteDataSource {
final Dio dio = DioClient.instance;
Future<Either<String, CustomerResponseModel>> getCustomers({
int page = 1,
int limit = Variables.defaultLimit,
}) async {
try {
final authData = await AuthLocalDataSource().getAuthData();
final url = '${Variables.baseUrl}/api/v1/customers';
final response = await dio.get(
url,
queryParameters: {
'page': page,
'limit': limit,
'organization_id': authData.user?.organizationId,
},
options: Options(
headers: {
'Authorization': 'Bearer ${authData.token}',
'Accept': 'application/json',
},
),
);
if (response.statusCode == 200) {
return Right(CustomerResponseModel.fromMap(response.data));
} else {
return const Left('Failed to get customers');
}
} on DioException catch (e) {
log("Dio error: ${e.message}");
return Left(e.response?.data['message'] ?? 'Gagal mengambil customer');
} catch (e) {
log("Unexpected error: $e");
return const Left('Unexpected error occurred');
}
}
Future<Either<String, bool>> createCustomer({
required String name,
required String phone,
required String address,
required String email,
required bool isActive,
}) async {
try {
final authData = await AuthLocalDataSource().getAuthData();
final url = '${Variables.baseUrl}/api/v1/customers';
Map<String, dynamic> data = {
'name': name,
'is_active': isActive,
};
if (phone.isNotEmpty) {
data['phone'] = phone;
}
if (address.isNotEmpty) {
data['address'] = address;
}
if (email.isNotEmpty) {
data['email'] = email;
}
final response = await dio.post(
url,
data: data,
options: Options(
headers: {
'Authorization': 'Bearer ${authData.token}',
'Accept': 'application/json',
},
),
);
if (response.statusCode == 200 || response.statusCode == 201) {
return const Right(true);
} else {
return const Left('Failed to create customer ');
}
} on DioException catch (e) {
log("Dio error: ${e.message}");
return Left(e.response?.data['message'] ?? 'Gagal membuat pelanggan');
} catch (e) {
log("Unexpected error: $e");
return const Left('Unexpected error occurred');
}
}
}