2021-03-14 10:45:42 +01:00
|
|
|
<?php
|
|
|
|
|
|
2021-07-28 14:18:47 +02:00
|
|
|
namespace App\Http\Controllers\Api\V2;
|
2021-03-14 10:45:42 +01:00
|
|
|
|
|
|
|
|
use App\Enums\ApiError;
|
2021-07-28 14:18:47 +02:00
|
|
|
use App\Exceptions\Api\V2\ApiErrorException;
|
2021-12-19 15:57:24 +01:00
|
|
|
use App\Exceptions\Api\V2\CrmException;
|
2021-03-14 10:45:42 +01:00
|
|
|
use App\Http\Controllers\Controller;
|
2021-07-28 14:18:47 +02:00
|
|
|
use App\Http\Requests\Api\V2\SingleOptinRequest;
|
2021-03-14 10:45:42 +01:00
|
|
|
use App\Models\CustomerInfo;
|
|
|
|
|
use App\Models\Service;
|
2023-06-23 17:18:59 +02:00
|
|
|
use Illuminate\Http\JsonResponse;
|
2021-03-14 10:45:42 +01:00
|
|
|
use App\Models\SingleOptin;
|
|
|
|
|
|
|
|
|
|
class OptinController extends Controller
|
|
|
|
|
{
|
|
|
|
|
/**
|
2021-12-19 15:57:24 +01:00
|
|
|
* Creates a new Single optin or destroys it if exists
|
2021-03-14 10:45:42 +01:00
|
|
|
*
|
2023-06-23 17:18:59 +02:00
|
|
|
* @param \App\Http\Requests\Api\V2\SingleOptinRequest $request
|
|
|
|
|
* @param \App\Models\Service $service
|
|
|
|
|
* @return \Illuminate\Http\JsonResponse
|
|
|
|
|
* @throws \App\Exceptions\Api\V2\ApiErrorException With ApiError::singleOptinCustomerExists
|
2023-06-22 17:25:52 +02:00
|
|
|
* if this email already has a full account.
|
2023-06-23 17:18:59 +02:00
|
|
|
* @throws \App\Exceptions\Api\V2\CrmException If the single optin could not be added or removed.
|
2021-03-14 10:45:42 +01:00
|
|
|
*/
|
2023-06-23 17:18:59 +02:00
|
|
|
public function optin(SingleOptinRequest $request, Service $service): JsonResponse
|
2021-03-14 10:45:42 +01:00
|
|
|
{
|
2021-08-06 15:57:48 +02:00
|
|
|
if (CustomerInfo::getFromEmail($service->brand, $request->email)->exists()) {
|
|
|
|
|
throw new ApiErrorException(ApiError::singleOptinCustomerExists());
|
|
|
|
|
}
|
|
|
|
|
|
2021-03-14 10:45:42 +01:00
|
|
|
/** @var \App\Models\SingleOptin */
|
2021-12-19 15:57:24 +01:00
|
|
|
$singleOptin = SingleOptin::where('email', $request->email)
|
2023-06-22 17:25:52 +02:00
|
|
|
->whereHas('brand', function ($q) use ($service) {
|
|
|
|
|
$q->whereId($service->brand->id);
|
|
|
|
|
})->firstOrNew();
|
2021-03-14 10:45:42 +01:00
|
|
|
|
2021-08-05 16:18:09 +02:00
|
|
|
if ($request->opt_in) {
|
2021-03-14 10:45:42 +01:00
|
|
|
$singleOptin->fill($request->validated());
|
|
|
|
|
$singleOptin->brand()->associate($service->brand);
|
2021-12-19 15:57:24 +01:00
|
|
|
$success = $singleOptin->save();
|
2021-03-14 10:45:42 +01:00
|
|
|
} else {
|
2021-12-19 15:57:24 +01:00
|
|
|
$success = $singleOptin->delete() !== false;
|
2021-03-14 10:45:42 +01:00
|
|
|
}
|
2021-12-19 15:57:24 +01:00
|
|
|
|
|
|
|
|
if (!$success) {
|
|
|
|
|
// @codeCoverageIgnoreStart
|
|
|
|
|
throw new CrmException('Api failed to update single optin.');
|
|
|
|
|
// @codeCoverageIgnoreEnd
|
|
|
|
|
}
|
|
|
|
|
|
2021-03-14 10:45:42 +01:00
|
|
|
return response()->json();
|
|
|
|
|
}
|
|
|
|
|
}
|