feat: Implement SMS sending functionality with KavehNegar and Rangineh providers

- Add SendSmsMessage class for encapsulating SMS message data.
- Create KavehNegarProvider and RanginehProvider classes implementing SmsProviderInterface for sending SMS.
- Implement SmsLogRepository and SmsTemplateRepository for managing SMS logs and templates.
- Develop SendSmsHandler for handling SMS sending messages.
- Create SmsService to manage SMS dispatching and logging.
- Add UserProfileController for managing user profiles with CRUD operations.
- Implement UserProfile entity and repository for user profile data management.
- Update symfony.lock and bootstrap.php for project dependencies and environment setup.
This commit is contained in:
hamed
2026-06-09 22:00:34 +03:30
commit de1a78a235
222 changed files with 36388 additions and 0 deletions
+202
View File
@@ -0,0 +1,202 @@
<?php
namespace App\Sms\Controller;
use App\Auth\Entity\User;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Sms\Entity\SmsTemplate;
use App\Sms\Repository\SmsTemplateRepository;
use App\Sms\Service\SmsService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class SmsController extends BaseController
{
public function __construct(
private readonly SmsTemplateRepository $templateRepo,
private readonly SmsService $smsService,
) {}
// ── Send SMS directly ─────────────────────────────────────────────────────
#[IsGranted('ROLE_ADMIN')]
#[Route('/api/v1/sms/send', methods: ['POST'])]
public function send(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true) ?? [];
$mobile = trim($data['mobile'] ?? '');
$message = trim($data['message'] ?? '');
$provider = $data['provider'] ?? 'kavenegar';
if (empty($mobile) || empty($message)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'mobile و message الزامی است', 422);
}
$this->smsService->dispatchAsync($mobile, $message, $provider);
return $this->success(['message' => 'پیامک در صف ارسال قرار گرفت']);
}
// ── Templates ─────────────────────────────────────────────────────────────
#[IsGranted('ROLE_ADMIN')]
#[Route('/api/v1/sms/template', methods: ['POST'])]
public function createTemplate(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true) ?? [];
$name = trim($data['name'] ?? '');
$body = trim($data['body'] ?? '');
$variables = $data['variables'] ?? [];
if (empty($name) || empty($body)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'name و body الزامی است', 422);
}
$template = new SmsTemplate($name, $body, $variables);
$this->templateRepo->save($template);
return $this->success(['data' => $template->toArray()], 201);
}
#[Route('/api/v1/sms/template/{uuid}', methods: ['GET'])]
public function getTemplate(string $uuid): JsonResponse
{
$template = $this->templateRepo->findByUuid($uuid);
if ($template === null) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'تمپلیت یافت نشد', 404);
}
return $this->success(['data' => $template->toArray()]);
}
#[IsGranted('ROLE_ADMIN')]
#[Route('/api/v1/sms/template/{uuid}', methods: ['PATCH'])]
public function updateTemplate(string $uuid, Request $request): JsonResponse
{
$template = $this->templateRepo->findByUuid($uuid);
if ($template === null) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'تمپلیت یافت نشد', 404);
}
if ($template->getStatus() === SmsTemplate::STATUS_APPROVED) {
return $this->error(ErrorCodes::ERR_SMS_003, ErrorCodes::message(ErrorCodes::ERR_SMS_003), 422);
}
$data = json_decode($request->getContent(), true) ?? [];
if (array_key_exists('name', $data)) $template->setName($data['name']);
if (array_key_exists('body', $data)) $template->setBody($data['body']);
if (array_key_exists('variables', $data)) $template->setVariables($data['variables']);
$this->templateRepo->save($template);
return $this->success(['data' => $template->toArray()]);
}
#[IsGranted('ROLE_ADMIN')]
#[Route('/api/v1/sms/template/{uuid}/submit', methods: ['POST'])]
public function submitTemplate(string $uuid): JsonResponse
{
$template = $this->templateRepo->findByUuid($uuid);
if ($template === null) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'تمپلیت یافت نشد', 404);
}
$template->submitForReview();
$this->templateRepo->save($template);
return $this->success(['data' => $template->toArray()]);
}
#[IsGranted('ROLE_ADMIN')]
#[Route('/api/v1/sms/template/{uuid}', methods: ['DELETE'])]
public function deleteTemplate(string $uuid): JsonResponse
{
$template = $this->templateRepo->findByUuid($uuid);
if ($template === null) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'تمپلیت یافت نشد', 404);
}
$this->templateRepo->remove($template);
return $this->success(['message' => 'تمپلیت حذف شد']);
}
// ── Admin moderation ──────────────────────────────────────────────────────
#[IsGranted('ROLE_ADMIN')]
#[Route('/api/v1/admin/sms/templates', methods: ['GET'])]
public function listTemplates(): JsonResponse
{
$templates = array_map(fn(SmsTemplate $t) => $t->toArray(), $this->templateRepo->findAll());
return $this->success(['data' => $templates]);
}
#[IsGranted('ROLE_ADMIN')]
#[Route('/api/v1/admin/sms/template/{uuid}/approve', methods: ['POST'])]
public function approveTemplate(string $uuid, Request $request): JsonResponse
{
$template = $this->templateRepo->findByUuid($uuid);
if ($template === null) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'تمپلیت یافت نشد', 404);
}
$data = json_decode($request->getContent(), true) ?? [];
$template->approve($data['note'] ?? null);
if (!empty($data['provider_code'])) $template->setProviderCode($data['provider_code']);
$this->templateRepo->save($template);
return $this->success(['data' => $template->toArray()]);
}
#[IsGranted('ROLE_ADMIN')]
#[Route('/api/v1/admin/sms/template/{uuid}/reject', methods: ['POST'])]
public function rejectTemplate(string $uuid, Request $request): JsonResponse
{
$template = $this->templateRepo->findByUuid($uuid);
if ($template === null) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'تمپلیت یافت نشد', 404);
}
$data = json_decode($request->getContent(), true) ?? [];
$note = trim($data['note'] ?? '');
if (empty($note)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'دلیل رد الزامی است', 422);
}
$template->reject($note);
$this->templateRepo->save($template);
return $this->success(['data' => $template->toArray()]);
}
// ── Send via template ─────────────────────────────────────────────────────
#[IsGranted('ROLE_ADMIN')]
#[Route('/api/v1/sms/send-template', methods: ['POST'])]
public function sendViaTemplate(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true) ?? [];
$mobile = trim($data['mobile'] ?? '');
$templateUuid = trim($data['template_uuid'] ?? '');
$vars = $data['vars'] ?? [];
$provider = $data['provider'] ?? 'kavenegar';
$template = $this->templateRepo->findByUuid($templateUuid);
if ($template === null) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'تمپلیت یافت نشد', 404);
}
if ($template->getStatus() !== SmsTemplate::STATUS_APPROVED) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'تمپلیت هنوز تأیید نشده است', 422);
}
$message = $template->renderBody($vars);
$this->smsService->dispatchAsync(
$mobile, $message, $provider, $template->getUuid(),
$vars, $template->getProviderCode()
);
return $this->success(['message' => 'پیامک در صف ارسال قرار گرفت']);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Sms\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
#[ORM\Entity]
#[ORM\Table(name: 'sms_logs')]
#[ORM\Index(columns: ['mobile', 'created_at'], name: 'idx_sms_logs_mobile')]
class SmsLog
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 36, unique: true)]
private string $uuid;
#[ORM\Column(type: 'string', length: 20)]
private string $mobile;
#[ORM\Column(type: 'text')]
private string $message;
#[ORM\Column(type: 'string', length: 20)]
private string $provider;
#[ORM\Column(type: 'boolean')]
private bool $success;
#[ORM\Column(name: 'template_uuid', type: 'string', length: 36, nullable: true)]
private ?string $templateUuid = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
public function __construct(string $mobile, string $message, string $provider, bool $success)
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->mobile = $mobile;
$this->message = $message;
$this->provider = $provider;
$this->success = $success;
$this->createdAt = time();
}
public function setTemplateUuid(?string $v): self { $this->templateUuid = $v; return $this; }
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'mobile' => $this->mobile,
'message' => $this->message,
'provider' => $this->provider,
'success' => $this->success,
'template_uuid' => $this->templateUuid,
'created_at' => $this->createdAt,
];
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
namespace App\Sms\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
#[ORM\Entity]
#[ORM\Table(name: 'sms_templates')]
class SmsTemplate
{
public const STATUS_DRAFT = 'draft';
public const STATUS_PENDING = 'pending';
public const STATUS_APPROVED = 'approved';
public const STATUS_REJECTED = 'rejected';
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 36, unique: true)]
private string $uuid;
#[ORM\Column(type: 'string', length: 100)]
private string $name;
#[ORM\Column(type: 'text')]
private string $body;
#[ORM\Column(name: 'provider_code', type: 'string', length: 100, nullable: true)]
private ?string $providerCode = null;
#[ORM\Column(type: 'string', length: 20)]
private string $status = self::STATUS_DRAFT;
#[ORM\Column(name: 'variables', type: 'json')]
private array $variables = [];
#[ORM\Column(name: 'admin_note', type: 'string', length: 500, nullable: true)]
private ?string $adminNote = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
#[ORM\Column(name: 'updated_at', type: 'integer')]
private int $updatedAt;
public function __construct(string $name, string $body, array $variables = [])
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->name = $name;
$this->body = $body;
$this->variables = $variables;
$this->createdAt = time();
$this->updatedAt = time();
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getName(): string { return $this->name; }
public function getBody(): string { return $this->body; }
public function getProviderCode(): ?string { return $this->providerCode; }
public function getStatus(): string { return $this->status; }
public function getVariables(): array { return $this->variables; }
public function getAdminNote(): ?string { return $this->adminNote; }
public function setName(string $v): self { $this->name = $v; $this->touch(); return $this; }
public function setBody(string $v): self { $this->body = $v; $this->touch(); return $this; }
public function setProviderCode(?string $v): self { $this->providerCode = $v; $this->touch(); return $this; }
public function setVariables(array $v): self { $this->variables = $v; $this->touch(); return $this; }
public function submitForReview(): self { $this->status = self::STATUS_PENDING; $this->touch(); return $this; }
public function approve(?string $note = null): self
{
$this->status = self::STATUS_APPROVED;
$this->adminNote = $note;
$this->touch();
return $this;
}
public function reject(string $note): self
{
$this->status = self::STATUS_REJECTED;
$this->adminNote = $note;
$this->touch();
return $this;
}
private function touch(): void { $this->updatedAt = time(); }
public function renderBody(array $vars): string
{
$body = $this->body;
foreach ($vars as $key => $value) {
$body = str_replace('{{' . $key . '}}', $value, $body);
}
return $body;
}
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'name' => $this->name,
'body' => $this->body,
'provider_code' => $this->providerCode,
'variables' => $this->variables,
'status' => $this->status,
'admin_note' => $this->adminNote,
'created_at' => $this->createdAt,
];
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace App\Sms\Message;
final class SendSmsMessage
{
public function __construct(
public readonly string $mobile,
public readonly string $message,
public readonly string $provider = 'kavenegar',
public readonly ?string $templateUuid = null,
public readonly array $templateVars = [],
public readonly ?string $templateCode = null,
) {}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Sms\Provider;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class KavehNegarProvider implements SmsProviderInterface
{
private const BASE = 'https://api.kavenegar.com/v1';
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly string $apiKey,
private readonly string $sender,
) {}
public function getName(): string { return 'kavenegar'; }
public function send(string $mobile, string $message): bool
{
try {
$resp = $this->httpClient->request('POST',
self::BASE . '/' . $this->apiKey . '/sms/send.json', [
'body' => http_build_query([
'receptor' => $mobile,
'message' => $message,
'sender' => $this->sender,
]),
'timeout' => 10,
]
);
$data = $resp->toArray();
return ($data['return']['status'] ?? 0) === 200;
} catch (\Throwable) {
return false;
}
}
public function sendTemplate(string $mobile, string $templateCode, array $vars): bool
{
try {
$params = ['receptor' => $mobile, 'template' => $templateCode];
foreach (array_values($vars) as $i => $v) {
$params['token' . ($i > 0 ? $i + 1 : '')] = $v;
}
$resp = $this->httpClient->request('POST',
self::BASE . '/' . $this->apiKey . '/verify/lookup.json', [
'body' => http_build_query($params),
'timeout' => 10,
]
);
$data = $resp->toArray();
return ($data['return']['status'] ?? 0) === 200;
} catch (\Throwable) {
return false;
}
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Sms\Provider;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class RanginehProvider implements SmsProviderInterface
{
private const BASE = 'https://rest.payamresan.com/api/v1';
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly string $apiKey,
private readonly string $sender,
) {}
public function getName(): string { return 'rangineh'; }
public function send(string $mobile, string $message): bool
{
try {
$resp = $this->httpClient->request('POST', self::BASE . '/send', [
'json' => ['from' => $this->sender, 'to' => [$mobile], 'text' => $message],
'headers' => ['ApiKey' => $this->apiKey],
'timeout' => 10,
]);
return $resp->getStatusCode() === 200;
} catch (\Throwable) {
return false;
}
}
public function sendTemplate(string $mobile, string $templateCode, array $vars): bool
{
try {
$resp = $this->httpClient->request('POST', self::BASE . '/send/verify', [
'json' => [
'mobile' => $mobile,
'template' => $templateCode,
'params' => $vars,
],
'headers' => ['ApiKey' => $this->apiKey],
'timeout' => 10,
]);
return $resp->getStatusCode() === 200;
} catch (\Throwable) {
return false;
}
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace App\Sms\Provider;
interface SmsProviderInterface
{
public function getName(): string;
/** @return bool true on success */
public function send(string $mobile, string $message): bool;
/** Send via approved template (pattern send) */
public function sendTemplate(string $mobile, string $templateCode, array $vars): bool;
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Sms\Repository;
use App\Sms\Entity\SmsLog;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class SmsLogRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry) { parent::__construct($registry, SmsLog::class); }
public function save(SmsLog $e, bool $flush = true): void { $this->getEntityManager()->persist($e); if ($flush) $this->getEntityManager()->flush(); }
}
@@ -0,0 +1,15 @@
<?php
namespace App\Sms\Repository;
use App\Sms\Entity\SmsTemplate;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class SmsTemplateRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry) { parent::__construct($registry, SmsTemplate::class); }
public function findByUuid(string $uuid): ?SmsTemplate { return $this->findOneBy(['uuid' => $uuid]); }
public function save(SmsTemplate $e, bool $flush = true): void { $this->getEntityManager()->persist($e); if ($flush) $this->getEntityManager()->flush(); }
public function remove(SmsTemplate $e, bool $flush = true): void { $this->getEntityManager()->remove($e); if ($flush) $this->getEntityManager()->flush(); }
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Sms\Service;
use App\Sms\Message\SendSmsMessage;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
class SendSmsHandler
{
public function __construct(private readonly SmsService $smsService) {}
public function __invoke(SendSmsMessage $message): void
{
$this->smsService->sendNow($message);
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
namespace App\Sms\Service;
use App\Sms\Entity\SmsLog;
use App\Sms\Message\SendSmsMessage;
use App\Sms\Provider\KavehNegarProvider;
use App\Sms\Provider\RanginehProvider;
use App\Sms\Provider\SmsProviderInterface;
use App\Sms\Repository\SmsLogRepository;
use Symfony\Component\Messenger\MessageBusInterface;
class SmsService
{
private array $providers;
public function __construct(
private readonly KavehNegarProvider $kavenegar,
private readonly RanginehProvider $rangineh,
private readonly SmsLogRepository $logRepo,
private readonly MessageBusInterface $bus,
) {
$this->providers = [
'kavenegar' => $kavenegar,
'rangineh' => $rangineh,
];
}
public function dispatchAsync(
string $mobile,
string $message,
string $provider = 'kavenegar',
?string $templateUuid = null,
array $templateVars = [],
?string $templateCode = null,
): void {
$this->bus->dispatch(new SendSmsMessage(
$mobile, $message, $provider, $templateUuid, $templateVars, $templateCode
));
}
public function sendNow(SendSmsMessage $msg): bool
{
$provider = $this->resolveProvider($msg->provider);
$success = ($msg->templateCode !== null)
? $provider->sendTemplate($msg->mobile, $msg->templateCode, $msg->templateVars)
: $provider->send($msg->mobile, $msg->message);
$log = new SmsLog($msg->mobile, $msg->message, $provider->getName(), $success);
if ($msg->templateUuid) $log->setTemplateUuid($msg->templateUuid);
$this->logRepo->save($log);
return $success;
}
private function resolveProvider(string $name): SmsProviderInterface
{
return $this->providers[$name] ?? $this->kavenegar;
}
}