sayliR #18
167
app/Http/Controllers/APIS/CustomerApi/CustomerController.php
Normal file
167
app/Http/Controllers/APIS/CustomerApi/CustomerController.php
Normal file
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\APIS\CustomerApi;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\CreateCustomerRequest;
|
||||
use App\Models\Customer;
|
||||
use Illuminate\Support\Str;
|
||||
use App\Services\AdminService;
|
||||
use Illuminate\Http\Request;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
|
||||
class CustomerController extends Controller
|
||||
|
||||
{
|
||||
protected $adminService;
|
||||
|
||||
public function __construct(AdminService $adminService)
|
||||
{
|
||||
$this->adminService = $adminService;
|
||||
}
|
||||
|
||||
|
||||
public function createOrUpdateCustomer(CreateCustomerRequest $request)
|
||||
{
|
||||
try {
|
||||
$userData = [
|
||||
'title' => $request->title,
|
||||
'email' => $request->email,
|
||||
'country' => $request->country,
|
||||
'state' => $request->state,
|
||||
'city' => $request->city,
|
||||
'zip' => $request->zip,
|
||||
'name' => $request->name,
|
||||
'phone' => $request->phone,
|
||||
'address' => $request->address,
|
||||
'address2' => $request->address2,
|
||||
'description' => $request->description,
|
||||
'version' => $request->version,
|
||||
'additionalInfo' => $request->additionalInfo,
|
||||
|
||||
];
|
||||
|
||||
if (!empty($request->id) && is_array($request->id) && isset($request->id['id'])) {
|
||||
$userData['id'] = [
|
||||
'id' => $request->id['id'],
|
||||
'entityType' => 'CUSTOMER',
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($request->tenantId) && is_array($request->tenantId) && isset($request->tenantId['id'])) {
|
||||
$userData['tenantId'] = [
|
||||
'id' => $request->tenantId['id'],
|
||||
'entityType' => 'TENANT',
|
||||
];
|
||||
}
|
||||
|
||||
// Call API to create/update customer
|
||||
$response = $this->adminService->createOrUpdateCustomer($userData);
|
||||
Log::info("API Response: ", $response);
|
||||
|
||||
if (is_array($response)) {
|
||||
$apiData = $response; // If it's an array, use it directly
|
||||
} elseif (method_exists($response, 'json')) {
|
||||
$apiData = $response->json();
|
||||
} else {
|
||||
Log::error("Unexpected API response format.", ['response' => $response]);
|
||||
return jsonResponseWithErrorMessage('Unexpected API response format', 500);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// $tenantId = $apiResponse['tenantId']['id'] ?? null;
|
||||
$externalId = $apiData['externalId'] ?? null;
|
||||
$tenantId = is_array($apiData['tenantId']) ? ($apiData['tenantId']['id'] ?? null) : $apiData['tenantId'];
|
||||
|
||||
|
||||
|
||||
// Store customer in database
|
||||
$customer = Customer::updateOrCreate(
|
||||
['id' => $apiData['id']['id'] ?? Str::uuid()->toString()],
|
||||
[
|
||||
'entity_type' => $apiData['id']['entityType'] ?? 'CUSTOMER',
|
||||
'created_time' => $apiData['createdTime'] ?? now()->timestamp,
|
||||
'country' => $apiData['country'] ?? null,
|
||||
'state' => $apiData['state'] ?? null,
|
||||
'city' => $apiData['city'] ?? null,
|
||||
'address' => $apiData['address'] ?? null,
|
||||
'address2' => $apiData['address2'] ?? null,
|
||||
'zip' => $apiData['zip'] ?? null,
|
||||
'phone' => $apiData['phone'] ?? null,
|
||||
'email' => $apiData['email'] ?? null,
|
||||
'title' => $apiData['title'] ?? null,
|
||||
'external_id' => $externalId,
|
||||
'version' => $apiData['version'] ?? 1,
|
||||
'name' => $apiData['name'] ?? null,
|
||||
'tenant_id' => $tenantId,
|
||||
'additional_info' => json_encode($apiData['additionalInfo'] ?? [])
|
||||
]
|
||||
);
|
||||
|
||||
return jsonResponseWithSuccessMessage(
|
||||
$request->customerId ? 'Customer updated successfully' : 'Customer created successfully',
|
||||
[
|
||||
'customer' => $customer,
|
||||
'api_response' => $apiData
|
||||
]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error("An error occurred: " . $e->getMessage());
|
||||
|
||||
$errorResponse = json_decode($e->getMessage(), true);
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
return jsonResponseWithErrorMessage($errorResponse['message'] ?? 'Something went wrong', 400, $errorResponse);
|
||||
}
|
||||
|
||||
return jsonResponseWithErrorMessage($e->getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function listCustomers(Request $request)
|
||||
{
|
||||
try {
|
||||
$customers = Customer::all();
|
||||
|
||||
return jsonResponseWithSuccessMessage('Customers fetched successfully', [
|
||||
'customers' => $customers
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error("An error occurred: " . $e->getMessage());
|
||||
return jsonResponseWithErrorMessage($e->getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function deleteCustomers($customerId)
|
||||
{
|
||||
|
||||
try {
|
||||
if (!$customerId) {
|
||||
return jsonResponseWithErrorMessage('Customer ID is required', 400);
|
||||
}
|
||||
|
||||
$response = $this->adminService->deleteCustomer(['customerId' => $customerId]);
|
||||
|
||||
|
||||
// Delete customer from local database if API deletion was successful
|
||||
$customer = Customer::where('id', $customerId)->first();
|
||||
if ($customer) {
|
||||
$customer->delete();
|
||||
}
|
||||
|
||||
return jsonResponseWithSuccessMessage('Customer deleted successfully', ['api_response' => $response]);
|
||||
} catch (Exception $e) {
|
||||
Log::error("An error occurred: " . $e->getMessage());
|
||||
$errorResponse = json_decode($e->getMessage(), true);
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
return jsonResponseWithErrorMessage($errorResponse['message'] ?? 'Something went wrong', 400, $errorResponse);
|
||||
}
|
||||
|
||||
return jsonResponseWithErrorMessage($e->getMessage(), 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
65
app/Http/Requests/CreateCustomerRequest.php
Normal file
65
app/Http/Requests/CreateCustomerRequest.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\Validator;
|
||||
use Illuminate\Http\Exceptions\HttpResponseException;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CreateCustomerRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
Log::info("CreateCustomerRequest: " . json_encode($this->all()));
|
||||
return [
|
||||
// 'id' => 'required|array',
|
||||
// 'id.id' => 'required|uuid',
|
||||
// 'id.entityType' => 'required|string|in:CUSTOMER',
|
||||
|
||||
'country' => 'required|string',
|
||||
'state' => 'required|string|max:255',
|
||||
'city' => 'required|string|max:255',
|
||||
'address' => 'required|string|max:255',
|
||||
'address2' => 'nullable|string|max:255',
|
||||
'zip' => 'required|string|max:20',
|
||||
'phone' => 'nullable|string|max:20',
|
||||
'email' => 'required|email|max:255',
|
||||
|
||||
'title' => 'required|string|max:255',
|
||||
|
||||
// 'tenantId' => 'required',
|
||||
// 'tenantId.id' => 'required|uuid',
|
||||
// 'tenantId.entityType' => 'required|string|in:TENANT',
|
||||
|
||||
// 'version' => 'required|integer|min:1',
|
||||
|
||||
// 'additionalInfo' => 'nullable|array',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handle a failed validation attempt.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Validation\Validator $validator
|
||||
* @throws \Illuminate\Http\Exceptions\HttpResponseException
|
||||
*/
|
||||
protected function failedValidation(Validator $validator)
|
||||
{
|
||||
throw new HttpResponseException(jsonResponseWithErrorMessage(implode(', ', $validator->errors()->all()), 422));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Cache;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
|
||||
class AdminService
|
||||
{
|
||||
private $baseUrl;
|
||||
@@ -30,19 +31,82 @@ class AdminService
|
||||
'accept' => 'application/json',
|
||||
'Content-Type' => 'application/json',
|
||||
])
|
||||
->post("{$this->baseUrl}/api/auth/login", [
|
||||
'username' => $this->username,
|
||||
'password' => $this->password,
|
||||
]);
|
||||
->post("{$this->baseUrl}/api/auth/login", [
|
||||
'username' => $this->username,
|
||||
'password' => $this->password,
|
||||
]);
|
||||
|
||||
|
||||
if ($response->successful()) {
|
||||
$token = $response->json('token');
|
||||
Cache::put('thingsboard_token', $token, now()->addMinutes(15));
|
||||
return $token;
|
||||
} else {
|
||||
Log::error("ThingsBoard Authentication Failed: " . $response->body());
|
||||
throw new Exception('Unable to authenticate with ThingsBoard: ' . $response->body());
|
||||
}
|
||||
}
|
||||
public function createOrUpdateCustomer(array $data)
|
||||
{
|
||||
$token = $this->getToken();
|
||||
Log::info('Getting data before payload', ['data' => json_encode($data, JSON_PRETTY_PRINT)]);
|
||||
|
||||
$payload = [
|
||||
'title' => $data['title'] ?? 'Default Title',
|
||||
'email' => $data['email'] ?? 'default@example.com',
|
||||
'country' => $data['country'] ?? 'India',
|
||||
'state' => $data['state'] ?? 'Karnataka',
|
||||
'city' => $data['city'] ?? 'Bangalore',
|
||||
'zip' => $data['zip'] ?? '560001',
|
||||
'name' => $data['name'] ?? 'John Doe',
|
||||
'address' => $data['address'] ?? '123, 4th Cross, 5th Main',
|
||||
'address2' => $data['address2'] ?? 'Near Park',
|
||||
'phone' => $data['phone'] ?? '1234567890',
|
||||
'version' => $data['version'] ?? '794665488',
|
||||
'additionalInfo' => [
|
||||
'description' => $data['description'] ?? 'User description'
|
||||
],
|
||||
|
||||
];
|
||||
|
||||
|
||||
|
||||
if (!empty($data['id']) && is_array($data['id']) && isset($data['id']['id'])) {
|
||||
$payload['id'] = [
|
||||
'id' => $data['id']['id'],
|
||||
'entityType' => 'CUSTOMER'
|
||||
];
|
||||
}
|
||||
|
||||
// Check if `tenantId` exists and assign correctly
|
||||
if (!empty($data['tenantId']) && is_array($data['tenantId']) && isset($data['tenantId']['id'])) {
|
||||
$payload['tenantId'] = [
|
||||
'id' => $data['tenantId']['id'],
|
||||
'entityType' => 'TENANT',
|
||||
];
|
||||
}
|
||||
|
||||
Log::info('Final Payload:', ['payload' => json_encode($payload, JSON_PRETTY_PRINT)]);
|
||||
|
||||
|
||||
|
||||
$url = "{$this->baseUrl}/api/customer";
|
||||
$method = 'post';
|
||||
// Send request
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'Accept' => 'application/json',
|
||||
'Content-Type' => 'application/json',
|
||||
])->$method($url, $payload);
|
||||
if ($response->successful()) {
|
||||
return $response->json();
|
||||
} else {
|
||||
throw new Exception('Failed to process customer: ' . $response->body());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public function createUser(array $data)
|
||||
{
|
||||
@@ -72,55 +136,80 @@ class AdminService
|
||||
'accept' => 'application/json',
|
||||
'Content-Type' => 'application/json',
|
||||
])->withBody(json_encode($payload), 'application/json')
|
||||
->post("{$this->baseUrl}/api/user");
|
||||
->post("{$this->baseUrl}/api/user");
|
||||
|
||||
if ($response->successful()) {
|
||||
return $response->json();
|
||||
} else {
|
||||
throw new Exception('Failed to create user: ' . $response->body());
|
||||
throw new Exception('Failed to process customer: ' . $response->body());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function deleteCustomer(array $data)
|
||||
{
|
||||
$token = $this->getToken();
|
||||
|
||||
|
||||
$url = "{$this->baseUrl}/api/customer/{$data['customerId']}";
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'Accept' => 'application/json',
|
||||
])->delete($url);
|
||||
|
||||
|
||||
|
||||
// If response body is empty, assume success
|
||||
if ($response->status() === 200 && empty($response->body())) {
|
||||
return ['message' => 'Customer deleted successfully'];
|
||||
}
|
||||
|
||||
if ($response->successful()) {
|
||||
return $response->json();
|
||||
} else {
|
||||
throw new Exception('Failed to create customer: ' . $response->body());
|
||||
}
|
||||
|
||||
throw new Exception('Failed to create user: ' . $response->body());
|
||||
}
|
||||
|
||||
|
||||
public function listUsers()
|
||||
{
|
||||
$token = $this->getToken();
|
||||
{
|
||||
$token = $this->getToken();
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'accept' => 'application/json',
|
||||
])->get("{$this->baseUrl}/api/users?pageSize=100&page=0");
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'accept' => 'application/json',
|
||||
])->get("{$this->baseUrl}/api/users?pageSize=100&page=0");
|
||||
|
||||
if ($response->successful()) {
|
||||
return $response->json();
|
||||
} else {
|
||||
throw new Exception('Failed to fetch users: ' . $response->body());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function deleteUser($userId)
|
||||
{
|
||||
$token = $this->getToken();
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'accept' => 'application/json',
|
||||
'Content-Type' => 'application/json',
|
||||
])->delete("{$this->baseUrl}/api/user/{$userId}");
|
||||
|
||||
// Handle ThingsBoard API errors
|
||||
if ($response->failed()) {
|
||||
Log::error('Failed to delete user: ' . $response->body());
|
||||
|
||||
// Return the ThingsBoard error message
|
||||
return $response->json();
|
||||
if ($response->successful()) {
|
||||
return $response->json();
|
||||
} else {
|
||||
throw new Exception('Failed to fetch users: ' . $response->body());
|
||||
}
|
||||
}
|
||||
|
||||
return $response->json();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public function deleteUser($userId)
|
||||
{
|
||||
$token = $this->getToken();
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token",
|
||||
'accept' => 'application/json',
|
||||
'Content-Type' => 'application/json',
|
||||
])->delete("{$this->baseUrl}/api/user/{$userId}");
|
||||
|
||||
// Handle ThingsBoard API errors
|
||||
if ($response->failed()) {
|
||||
Log::error('Failed to delete user: ' . $response->body());
|
||||
|
||||
// Return the ThingsBoard error message
|
||||
return $response->json();
|
||||
}
|
||||
|
||||
return $response->json();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\APIS\CustomerApi\CustomerController;
|
||||
use App\Http\Controllers\APIS\AdminApi\UsersController;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
@@ -9,6 +10,18 @@ Route::get('/adminapi', function () {
|
||||
return ('Welcome to admin api routes.');
|
||||
});
|
||||
|
||||
// Route::post('')
|
||||
|
||||
|
||||
//******************************************************* Customer API********************************************************
|
||||
|
||||
Route::post('/customer/create-or-update', [CustomerController::class, 'createOrUpdateCustomer'])->name('customer.create-or-update');
|
||||
Route::get('/customer/list', [CustomerController::class, 'listCustomers'])->name('customer.list');
|
||||
Route::delete('/customer/delete/{customerId}', [CustomerController::class, 'deleteCustomers'])->name('customer.delete');
|
||||
|
||||
|
||||
//******************************************************* User API********************************************************
|
||||
|
||||
Route::post('/users-store', [UsersController::class, 'store'])->name('user_create');
|
||||
Route::get('/users-list', [UsersController::class, 'list'])->name('user_list');
|
||||
Route::delete('/users-delete/{userId}', [UsersController::class, 'delete']);
|
||||
|
||||
Reference in New Issue
Block a user