Skip to content

Commit

Permalink
Merge pull request #400 from hngprojects/dev
Browse files Browse the repository at this point in the history
chore: merging dev into staging
  • Loading branch information
Dev-Tonia authored Aug 7, 2024
2 parents 36e16e4 + 592cce9 commit 6b26846
Show file tree
Hide file tree
Showing 96 changed files with 49,510 additions and 3,187 deletions.
6,337 changes: 5,832 additions & 505 deletions .scribe/endpoints.cache/00.yaml

Large diffs are not rendered by default.

6,335 changes: 5,831 additions & 504 deletions .scribe/endpoints/00.yaml

Large diffs are not rendered by default.

Empty file added [
Empty file.
58 changes: 41 additions & 17 deletions app/Http/Controllers/Api/V1/Auth/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\User;
use App\Models\Organisation;
use App\Models\OrganisationUser;
use Illuminate\Support\Facades\Log;
use App\Models\Validators\AuthValidator;
use Illuminate\Support\Facades\Validator;
Expand Down Expand Up @@ -47,6 +49,7 @@ public function store(Request $request)
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email:rfc|max:255|unique:users',
'admin_secret' => 'nullable|string|max:255',
'password' => ['required', 'string', Password::min(8)
->letters()
->mixedCase()
Expand All @@ -63,45 +66,66 @@ public function store(Request $request)
try {
DB::beginTransaction();

$role = $request->admin_secret ? 'admin' : 'user';

// Creating the user
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => $role
]);

$profile = $user->profile()->create([
'first_name' => $request->first_name,
'last_name' => $request->last_name
]);

$organization = $user->owned_organisations()->create([
'name' => $request->first_name."'s Organisation",
]);

$organization_user = OrganisationUser::create([
'user_id' => $user->id,
'org_id' => $organization->org_id
]);

$roles = $user->roles()->create([
'name' => $role,
'org_id' => $organization->org_id
]);
DB::table('users_roles')->insert([
'user_id' => $user->id,
'role_id' => $roles->id
]);

// Generate JWT token
$token = JWTAuth::fromUser($user);

DB::commit();
$data = [
'user' => [
'id' => $user->id,
'first_name' => $profile->first_name,
'last_name' => $profile->last_name,
'email' => $user->email,
'avatar_url' => $profile->avatar_url,
'role' => $user->role

return response()->json([
'status' => 201,
"message" => "User Created Successfully",
'access_token' => $token,
'data' => [
'user' => [
'id' => $user->id,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'avatar_url' => $user->profile->avatar_url,
'email' => $user->email,
'role' => $user->role
]
],
];

return $this->apiResponse(
message: 'User Created Successfully',
status_code: Response::HTTP_CREATED,
data: $data,
token: $token
);
], 201);
// return $this->apiResponse('Registration successful', Response::HTTP_CREATED, $data);
} catch (\Exception $e) {
DB::rollBack();
Log::error('Registration error: ' . $e->getMessage());

return $this->apiResponse('Registration unsuccessful', Response::HTTP_BAD_REQUEST);
}

}

/**
Expand Down
53 changes: 47 additions & 6 deletions app/Http/Controllers/Api/V1/PaymentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Support\Facades\Validator;
use App\Models\Payment;
use App\Services\PaymentService;
use App\Models\Organisation;
use App\Models\SubscriptionPlan;
use App\Models\UserSubscription;
use Illuminate\Support\Str;
Expand All @@ -26,7 +27,7 @@ public function initiatePaymentForPayStack(Request $request)
{
// return response()->json(['h'=> 'ng']);
$validator = Validator::make($request->all(), [
// 'organisation_id' => 'required',
'organisation_id' => 'required',
'plan_id' =>'required',
'billing_option' => 'required|in:monthly,yearly',
'full_name' => 'required',
Expand All @@ -39,14 +40,31 @@ public function initiatePaymentForPayStack(Request $request)
'message' => 'Validation error: ' . $validator->errors()->first()
], 400);
}
$userIsAnAdminInOrganisation = Organisation::where('user_id', auth()->user()->id)
->where('org_id', $request->organisation_id)
->exists();
if (!$userIsAnAdminInOrganisation) {
return response()->json([
'status' => 403,
'message' => 'You do not have permission to initiate this payment'
], 403);
}

// $gateway_id = Gateway::where('code', 'paystack')->first()->id;
$subscriptionPlan = SubscriptionPlan::find($request->plan_id);
if(!$subscriptionPlan) {
return response()->json([
'status' => 404,
'message' => 'Subscription Plan not found'
], 404);
}
$data = $validator->validated();
$data['email'] = auth()->user()->email;
$data['reference'] = Str::uuid();
$data['plan_code'] = $subscriptionPlan->paystack_plan_code;
$data['plan_id'] = $subscriptionPlan->id;
$data['amount'] = $subscriptionPlan->price;
$data['organisation_id'] = $request->organisation_id;

try {

Expand All @@ -72,12 +90,13 @@ public function initiatePaymentForPayStack(Request $request)
} catch (\Exception $e) {
return response()->json([
'status' => 500,
'message' => 'Payment Initialization Failed: ' . $e->getMessage()
'message' => 'An unexpected error occurred. Please try again later.'
// 'message' => 'Payment Initialization Failed: ' . $e->getMessage()
], 500);
}
}

public function handlePaystackCallback($id, Request $request)
public function handlePaystackCallback($organisation_id, $id, Request $request)
{
$reference = $request->query('reference');

Expand All @@ -99,6 +118,7 @@ public function handlePaystackCallback($id, Request $request)
$userSubscription = new UserSubscription;
$userSubscription->user_id = auth()->user()->id;
$userSubscription->subscription_plan_id = $id;
$userSubscription->org_id = $organisation_id;
$userSubscription->save();


Expand All @@ -115,7 +135,7 @@ public function handlePaystackCallback($id, Request $request)
public function initiatePaymentForFlutterWave(Request $request)
{
$validator = Validator::make($request->all(), [
// 'organisation_id' => 'required',
'organisation_id' => 'required',
'plan_id' =>'required',
'billing_option' => 'required|in:monthly,yearly',
'full_name' => 'required',
Expand All @@ -128,8 +148,25 @@ public function initiatePaymentForFlutterWave(Request $request)
'message' => 'Validation error: ' . $validator->errors()->first()
], 400);
}

$userIsAnAdminInOrganisation = Organisation::where('user_id', auth()->user()->id)
->where('org_id', $request->organisation_id)
->exists();
// return response()->json(auth()->user()->id);
if (!$userIsAnAdminInOrganisation) {
return response()->json([
'status' => 403,
'message' => 'You do not have permission to initiate this payment'
], 403);
}
// $gateway_id = Gateway::where('code', 'flutterwave')->first()->id;
$subscriptionPlan = SubscriptionPlan::find($request->plan_id);
if(!$subscriptionPlan) {
return response()->json([
'status' => 404,
'message' => 'Subscription Plan not found'
], 404);
}

$data = $validator->validated();
$data['email'] = auth()->user()->email;
Expand All @@ -138,6 +175,8 @@ public function initiatePaymentForFlutterWave(Request $request)
$data['plan_id'] = $subscriptionPlan->id;
$data['amount'] = $subscriptionPlan->price;
$data['title'] = $subscriptionPlan->name;
$data['organisation_id'] = $request->organisation_id;
$data['title'] = $subscriptionPlan->name;

try {
// Retrieve the gateway name
Expand Down Expand Up @@ -166,12 +205,13 @@ public function initiatePaymentForFlutterWave(Request $request)
} catch (\Exception $e) {
return response()->json([
'status' => 500,
'message' => 'Payment Initialization Failed: ' . $e->getMessage()
'message' => 'An unexpected error occurred. Please try again later.'
// 'message' => 'Payment Initialization Failed: ' . $e->getMessage()
], 500);
}
}

public function handleFlutterwaveCallback($id, Request $request)
public function handleFlutterwaveCallback($organisation_id, $id, Request $request)
{
$transaction_id = $request->query('transaction_id');

Expand All @@ -192,6 +232,7 @@ public function handleFlutterwaveCallback($id, Request $request)
$userSubscription = new UserSubscription;
$userSubscription->user_id = auth()->user()->id;
$userSubscription->subscription_plan_id = $id;
$userSubscription->org_id = $organisation_id;
$userSubscription->save();

// Redirect to the specified URL with status
Expand Down
50 changes: 32 additions & 18 deletions app/Http/Controllers/Api/V1/ProductController.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,11 @@ public function search(Request $request)
});
}


$page = $request->input('page', 1);
$limit = $request->input('limit', 10);
$products = $query->with(['productsVariant', 'categories'])
->paginate($limit, ['*'], 'page', $page);
->paginate($limit, ['*'], 'page', $page);

$transformedProducts = $products->map(function ($product) {
return [
Expand All @@ -92,9 +92,9 @@ public function search(Request $request)
'description' => $product->description,
'product_id' => $product->product_id,
'quantity' => $product->quantity,
'category' => $product->categories->isNotEmpty() ? $product->categories->map->name : [],
'stock' => $product->productsVariant->isNotEmpty() ? $product->productsVariant->first()->stock : null,
'status' => $product->productsVariant->isNotEmpty() ? $product->productsVariant->first()->stock_status : null,
'category' => $product->categories->isNotEmpty() ? $product->categories->map->name : [],
'stock' => $product->productsVariant->isNotEmpty() ? $product->productsVariant->first()->stock : null,
'status' => $product->productsVariant->isNotEmpty() ? $product->productsVariant->first()->stock_status : null,
'date_added' => $product->created_at
];
});
Expand All @@ -107,7 +107,7 @@ public function search(Request $request)
'totalPages' => $products->lastPage(),
'currentPage' => $products->currentPage(),
'perPage' => $products->perPage(),
],
],
'status_code' => 200
], 200);
}
Expand Down Expand Up @@ -194,15 +194,15 @@ public function index(Request $request)
* Store a newly created resource in storage.
*/
public function store(CreateProductRequest $request, $org_id)
{
{
$isOwner = OrganisationUser::where('org_id', $org_id)->where('user_id', auth()->id())->exists();

if (!$isOwner) {
return response()->json(['message' => 'You are not authorized to create products for this organization.'], 403);
}

$imageUrl = null;
if($request->hasFile('image')) {
if ($request->hasFile('image')) {
$imagePath = $request->file('image')->store('product_images', 'public');
$imageUrl = Storage::url($imagePath);
}
Expand Down Expand Up @@ -239,7 +239,6 @@ public function store(CreateProductRequest $request, $org_id)
]);

return response()->json(['message' => 'Product created successfully', 'product' => $product], 201);

}

/**
Expand Down Expand Up @@ -320,28 +319,43 @@ public function update(UpdateProductRequest $request, string $org_id, string $pr
/**
* Remove the specified resource from storage.
*/
public function destroy($productId)
public function destroy($org_id, $product_id)
{
if (!Auth::check()) {
return response()->json([
'error' => 'Unauthorized',
'message' => 'You must be authenticated to delete a product.'
], 401);

$isOwner = OrganisationUser::where('org_id', $org_id)->where('user_id', auth()->id())->exists();
// Check if the user's organization matches the org_id in the request
if (!$isOwner) {
return response()->json(
[
'status' => 'Forbidden',
'message' => 'You do not have permission to delete a product from this organization.',
'status_code' => 403
],
403
);
}

$product = Product::find($productId);
$product = Product::find($product_id);

if (!$product) {
return response()->json([
'error' => 'Product not found',
'message' => "The product with ID $productId does not exist."
'message' => "The product with ID $product_id does not exist."
], 404);
}

// Check if the product belongs to the organization
if ($product->org_id !== $org_id) {
return response()->json([
'error' => 'Forbidden',
'message' => 'You do not have permission to delete this product.'
], 403);
}

$product->delete();

return response()->json([
'message' => 'Product deleted successfully.'
], 200);
], 204);
}
}
Loading

0 comments on commit 6b26846

Please sign in to comment.