<?php
namespace EADPlataforma\Controller\Api\v1;
use OpenApi\Annotations as OA;
use Nelmio\ApiDocBundle\Annotation\Model;
use Nelmio\ApiDocBundle\Annotation\Security;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use EADPlataforma\Controller\Api\AbstractApiController;
use EADPlataforma\Entity\User;
use EADPlataforma\Entity\UserSubscription;
use EADPlataforma\Entity\Product;
use EADPlataforma\Entity\ProductOffer;
use EADPlataforma\Entity\ProductCoupon;
use EADPlataforma\Entity\Transaction;
use EADPlataforma\Entity\TransactionItem;
use EADPlataforma\Entity\UserCheckoutInfo;
use EADPlataforma\Entity\City;
use EADPlataforma\Entity\State;
use EADPlataforma\Enum\TransactionItemEnum;
use EADPlataforma\Enum\UserLogEnum;
use EADPlataforma\Enum\ErrorEnum;
use EADPlataforma\Enum\UserPermissionEnum;
use EADPlataforma\Enum\TrashEnum;
class TransactionItemApiController extends AbstractApiController {
public function getEntityClass(){
return TransactionItem::class;
}
/**
* Listagem dos pagamentos das assinaturas do EAD.
*
*
* @Route("/api/1/payment", methods={"GET"})
* @OA\Response(
* response=200,
* description="Retorna os pagamentos dos planos cadastrados no EAD.",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="assinatura_id", type="integer", example=1, description="Id da assinatura cadastrada no EAD."),
* @OA\Property(property="transacao_id", type="string", example="", description="Id da transação cadastrada no EAD."),
* @OA\Property(property="status", type="integer", example="", description="Status da transação."),
* @OA\Property(property="data_compra", type="datetime", example="", description="Data e hora do pedido."),
* @OA\Property(property="data_conclusao", type="datetime", example="", description="Data e hora da conclusão do processamento do pedido."),
* @OA\Property(property="plano_id", type="integer", example=1, description="Id do plano cadastrado no EAD."),
* @OA\Property(property="valor_pago", type="float", example=1, description="Valor pago pelo aluno."),
* @OA\Property(property="aluno_id", type="integer", example=1, description="Id do aluno cadastrado no EAD."),
* @OA\Property(property="nome", type="string", example="", description="Nome do aluno cadastrado no EAD."),
* @OA\Property(property="email", type="integer", example="", description="E-mail do aluno cadastrado no EAD.")
* )
* )
*
* @OA\Response(
* response=204,
* description="No content"
* )
*
* @OA\Response(
* response=401,
* description="Token not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=401, description="Token not found"),
* @OA\Property(property="message", type="string", example="Token not found")
* )
* )
*
* @OA\Response(
* response=429,
* description="Too many requests",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=429, description="Too many requests"),
* @OA\Property(property="message", type="string", example="Too many requests")
* )
* )
*
* @OA\Response(
* response=500,
* description="Internal Server Error",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=500, description="Internal Server Error"),
* @OA\Property(property="message", type="string", example="Internal Server Error")
* )
* )
*
* @OA\Parameter(
* name="id",
* in="query",
* description="Assinatura Id",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="usuario_id",
* in="query",
* description="Usuário Id",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="plano_id",
* in="query",
* description="Plano Id",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="data_inicio",
* in="query",
* description="Data inicial última compra (yyyy-mm-dd)",
* @OA\Schema(type="string")
* )
*
* @OA\Parameter(
* name="data_fim",
* in="query",
* description="Data final última compra (yyyy-mm-dd)",
* @OA\Schema(type="string")
* )
*
* @OA\Parameter(
* name="paginate",
* in="query",
* description="Informaçoes para paginação",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="limit",
* in="query",
* description="Número máximo de dados retornados por página, valor padrão 1000",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="offset",
* in="query",
* description="Indica o início da leitura, caso não informado valor padrão será 0",
* @OA\Schema(type="integer")
* )
*
* @OA\Tag(name="Assinaturas")
* @Security(name="Bearer")
*
*/
public function getUserPayment(Request $request)
{
$this->requestUtil->setRequest($request)->setData();
$columns = [
"us.id AS assinatura_id",
"t.hash AS transacao_id",
"t.status",
"DATE_FORMAT(t.dateRegister, '%Y-%m-%d %H:%i:%s') AS data_compra",
"DATE_FORMAT(t.dateApprove, '%Y-%m-%d %H:%i:%s') AS data_conclusao",
"p.id AS plano_id",
"t.amount AS valor_pago",
"u.id AS aluno_id",
"u.name AS nome",
"u.email"
];
$transactionClass = Transaction::class;
$productClass = Product::class;
$userClass = User::class;
$userSubscription = UserSubscription::class;
$joins = [
"{$productClass} AS p" => "p.id = ti.product AND p.type = 2",
"{$transactionClass} AS t" => "t.id = ti.transaction AND t.deleted = 0",
"{$userClass} AS u" => "u.id = t.user",
"{$userSubscription} AS us" => "us.user = t.user AND us.product = ti.product"
];
$id = $request->get('id');
$userId = $request->get('usuario_id');
$productId = $request->get('plano_id');
$dateStart = $request->get('data_inicio');
$dateEnd = $request->get('data_fim');
$paginate = $request->get('paginate');
$limit = (int)$request->get('limit');
$offset = (int)$request->get('offset');
$filter = [
"ti.deleted" => 0,
"ti.type" => 2
];
if(empty($limit) || $limit > 1000){
$limit = 1000;
}
if(empty($offset)){
$offset = 0;
}
if(!empty($id)){
$filter["us.id"] = $id;
}
if(!empty($userId)){
$filter["t.user"] = $userId;
}
if(!empty($productId)){
$filter["ti.product"] = $productId;
}
if(empty($dateStart) && !empty($dateEnd)){
$dateStart = date('Y-m-d', strtotime("-1 day",strtotime($dateEnd)));
}
if(empty($dateEnd) && !empty($dateStart)){
$dateEnd = date('Y-m-d', strtotime("+1 day",strtotime($dateStart)));
}
$dateStart = date('Y-m-d 00:00:00', strtotime($dateStart));
$dateEnd = date('Y-m-d 23:59:59', strtotime($dateEnd));
if(!empty($dateStart) && !empty($dateEnd)){
$filter["whereText"] = "t.dateRegister BETWEEN '{$dateStart}' AND '{$dateEnd}'";
}
$order = ["ti.id" => "ASC"];
$data = $this->repository->paginate("ti", null, $columns, $joins, $filter, $order, $limit, $offset);
if(count($data['rows']) == 0){
return $this->eadResponse(null, ErrorEnum::NO_CONTENT, null);
}
if($paginate == 1){
unset($data['searchText']);
return $this->json($data);
}
return $this->json($data['rows']);
}
/**
* Listagem de vendas dos cursos do EAD.
*
* @Route("/api/1/sales", methods={"GET"})
* @OA\Response(
* response=200,
* description="Retorna as vendas do EAD.",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="vendas_id", type="integer", example=1, description="Id da venda cadastrada no EAD."),
* @OA\Property(property="transacao_id", type="string", example="", description="Id da transação cadastrada no EAD."),
* @OA\Property(property="produto_id", type="integer", example="", description="Id do curso ou plano no EAD."),
* @OA\Property(property="valor", type="float", example="", description="Valor da transação."),
* @OA\Property(property="valor_liquido", type="float", example="", description="Valor da transação sem as taxas."),
* @OA\Property(property="taxas", type="float", example="", description="Taxas cobradas da transação."),
* @OA\Property(property="cupom", type="string", example="", description="Cupom utilizado na transação."),
* @OA\Property(property="lucro_ead", type="float", example="", description="Lucro do EAD na transação."),
* @OA\Property(property="nome_afiliado", type="string", example="Somente Hotmart, Eduzz, Provi, Braip, Monetizze, Kiwify, DigitalManagerGuru, AppMax, Doppus, Ticto, Abmex, PerfectPay, Evermart, HeroSpark, Yampi, CartPanda e Kirvano.", description="Nome do afiliado que indicou a venda."),
* @OA\Property(property="lucro_afiliado", type="float", example="Somente Hotmart, Eduzz, Provi, Braip, Monetizze, Kiwify, DigitalManagerGuru, AppMax, Doppus, Ticto, Abmex, PerfectPay, Evermart, HeroSpark, Yampi, CartPanda e Kirvano.", description="Lucro do afiliado na transação."),
* @OA\Property(property="data_transacao", type="datetime", example="", description="Data da trasanção."),
* @OA\Property(property="data_conclusao", type="datetime", example="", description="Data que pagamento foi recebido."),
* @OA\Property(property="tipo_pagamento", type="integer", example="", description="Forma utilizada de pagamento(1-Cartão de crédito / 2-Boleto)."),
* @OA\Property(property="status_transacao", type="integer", example="", description="1-Aguardando Pagamento / 2-Aprovado / 3-Cancelado / 4-Em disputa / 5-Reembolso em andamento / 6-Reembolso / 7-Chargeback / 8-Completo"),
* @OA\Property(property="aluno_id", type="integer", example="", description="Id do aluno cadastrado no EAD."),
* @OA\Property(property="nome_aluno", type="string", example="", description="Nome do aluno."),
* @OA\Property(property="email", type="string", example="", description="E-mail do aluno."),
* @OA\Property(property="faturamento_nome", type="string", example="", description="Nome utilizado na compra."),
* @OA\Property(property="faturamento_email", type="string", example="", description="E-mail utilizado na compra."),
* @OA\Property(property="faturamento_documento", type="string", example="", description="Documento utilizado na compra."),
* @OA\Property(property="faturamento_telefone", type="string", example="", description="Telefone utilizado na compra."),
* @OA\Property(property="faturamento_endereco", type="string", example="", description="Endereço utilizado na compra."),
* @OA\Property(property="faturamento_numero", type="string", example="", description="Número utilizado na compra."),
* @OA\Property(property="faturamento_complemento", type="string", example="", description="Complemento utilizado na compra."),
* @OA\Property(property="faturamento_bairro", type="string", example="", description="Bairro utilizado na compra."),
* @OA\Property(property="faturamento_cep", type="string", example="", description="CEP utilizado na compra."),
* @OA\Property(property="faturamento_cidade", type="string", example="", description="Cidade utilizado na compra."),
* @OA\Property(property="faturamento_uf", type="string", example="", description="UF utilizado na compra."),
* @OA\Property(property="vendedor_id", type="integer", example="", description="Id do vendedor cadastrado no EAD."),
* @OA\Property(property="nome_vendedor", type="string", example="", description="Nome do professor(a) do curso."),
* @OA\Property(property="tipo_venda", type="integer", example="", description="Tipo da venda(1-Vendas / 2-Assinaturas)."),
* @OA\Property(property="gateway", type="string", example="", description="1-Manual / 2-PagSeguro / 3-Paypal / 4-Hotmart / 5-Eduzz / 6-EAD Checkout / 7-Provi / 8-Braip / 9-Monetizze / 9-Kiwify / 10-DigitalManagerGuru / 11-AppMax / 12-Doppus / 13-Ticto / 14-MercadoPago / 15-Abmex / 16-PerfectPay / 17-Evermart / 18-HeroSpark / 19-Yampi / 20-CartPanda / 21-Kirvano"),
* @OA\Property(property="origem", type="integer", example="", description="1-Carrinho Padrão / 2-Carrinho customizado / 3-Página de chekcout / 4-Recorrência / 5-Manual / 6-Cobrança / 7-Compra com um clique / 8-Externo"),
* @OA\Property(property="utms_url", type="application/json", example="", description="UTM's URL")
* )
* )
*
* @OA\Response(
* response=204,
* description="No content"
* )
*
* @OA\Response(
* response=401,
* description="Token not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=401, description="Token not found"),
* @OA\Property(property="message", type="string", example="Token not found")
* )
* )
*
* @OA\Response(
* response=429,
* description="Too many requests",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=429, description="Too many requests"),
* @OA\Property(property="message", type="string", example="Too many requests")
* )
* )
*
* @OA\Response(
* response=500,
* description="Internal Server Error",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=500, description="Internal Server Error"),
* @OA\Property(property="message", type="string", example="Internal Server Error")
* )
* )
*
* @OA\Parameter(
* name="id",
* in="query",
* description="Venda Id, se enviar venda id não é necessário envio do código da transação",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="curso",
* in="query",
* description="Produto Id",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="transacao",
* in="query",
* description="Código da Transação, se enviar código da transação não é necessário envio da venda id",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="aluno_id",
* in="query",
* description="Aluno Id",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="vendedor_id",
* in="query",
* description="Vendedor Id",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="cupom",
* in="query",
* description="Cupom aplicado",
* @OA\Schema(type="string")
* )
*
* @OA\Parameter(
* name="status",
* in="query",
* description="1 - Aguardando Pagamento, 2 - Confirmado, 3 - Cancelado, 4 - Em distputa, 5 - Estorno em andamento, 6 - Reembolso, 7 - Chargeback",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="data_inicio",
* in="query",
* description="Data inicial início da transação (yyyy-mm-dd)",
* @OA\Schema(type="string")
* )
*
* @OA\Parameter(
* name="data_fim",
* in="query",
* description="Data final início da transação (yyyy-mm-dd)",
* @OA\Schema(type="string")
* )
*
* @OA\Parameter(
* name="paginate",
* in="query",
* description="Informaçoes para paginação",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="limit",
* in="query",
* description="Maximum number of data returned per page, default value 1000",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="offset",
* in="query",
* description="Indicates the start of reading, if not informed default value will be 0",
* @OA\Schema(type="integer")
* )
*
* @OA\Tag(name="Transações")
* @Security(name="Bearer")
*
*/
public function getTransactionItem(Request $request)
{
$this->requestUtil->setRequest($request)->setData();
$columns = [
"ti.id AS vendas_id",
"t.hash AS transacao_id",
"p.id AS produto_id",
"ti.amount AS valor_pago",
"ti.netAmount AS valor_liquido",
"ti.feeAmount AS taxas",
"ti.couponKey AS cupom",
"ti.commissionAmount AS comissao_professor",
"ti.commissionPercent AS porcentagem_professor",
"ti.affiliateName AS nome_afiliado",
"ti.affiliateCommission AS comissao_afiliado",
"ti.netFinalAmount AS lucro_ead",
"DATE_FORMAT(t.dateRegister, '%Y-%m-%d %H:%i:%s') AS data_transacao",
"DATE_FORMAT(t.dateApprove, '%Y-%m-%d %H:%i:%s') AS data_conclusao",
"t.paymentMethod AS tipo_pagamento",
"t.status AS status_transacao",
"u.id AS aluno_id",
"u.name AS nome",
"u.email",
"uci.name AS faturamento_nome",
"uci.email AS faturamento_email",
"uci.document AS faturamento_documento",
"uci.phone AS faturamento_telefone",
"uci.address AS faturamento_endereco",
"uci.addressNumber AS faturamento_numero",
"uci.addressComplement AS faturamento_complemento",
"uci.addressNeighborhood AS faturamento_bairro",
"uci.zipCode AS faturamento_cep",
"c.name AS faturamento_cidade",
"s.uf AS faturamento_uf",
"uv.id AS vendedor_id",
"uv.name AS nome_vendedor",
"ti.type AS tipo_venda",
"t.gateway",
"t.origin AS origem",
"ti.utmsUrl AS utms_url"
];
$transactionClass = Transaction::class;
$productClass = Product::class;
$productCouponClass = ProductCoupon::class;
$userClass = User::class;
$userCheckoutInfoClass = UserCheckoutInfo::class;
$cityClass = City::class;
$stateClass = State::class;
$joins = [
"{$productClass} AS p" => "p.id = ti.product",
"{$transactionClass} AS t" => "t.id = ti.transaction AND t.deleted = 0",
"{$userClass} AS u" => "u.id = t.user",
"{$userClass} AS uv" => "uv.id = ti.userSeller",
"{$userCheckoutInfoClass} AS uci" => ["LEFT", "uci.id = t.userCheckoutInfo"],
"{$cityClass} AS c" => ["LEFT", "c.id = uci.city"],
"{$stateClass} AS s" => ["LEFT", "s.id = uci.state"]
];
$transactionItemId = $request->get('id');
$productId = $request->get('curso');
$transactionHash = $request->get('transacao');
$userId = $request->get('aluno_id');
$userSeller = $request->get('vendedor_id');
$transactionStatus = $request->get('status');
$transactionStart = $request->get('data_inicio');
$transactionEnd = $request->get('data_fim');
$paginate = $request->get('paginate');
$limit = (int)$request->get('limit');
$offset = (int)$request->get('offset');
$filter = [
"t.user" => [ "!=", 1 ],
"ti.deleted" => 0
];
if(empty($limit) || $limit > 1000){
$limit = 1000;
}
if(empty($offset)){
$offset = 0;
}
if(!empty($userId)){
$filter["t.user"] = $userId;
}
if(!empty($transactionHash)){
$filter["t.hash"] = $transactionHash;
}
if(!empty($transactionStatus)){
$filter["t.status"] = $transactionStatus;
}
if(!empty($transactionStatus)){
$filter["t.status"] = $transactionStatus;
}
if(empty($transactionStart) && !empty($transactionEnd)){
$transactionStart = date('Y-m-d', strtotime("-1 day",strtotime($transactionEnd)));
}
if(empty($transactionEnd) && !empty($transactionStart)){
$transactionEnd = date('Y-m-d', strtotime("+1 day",strtotime($transactionStart)));
}
if(!empty($transactionStart) && !empty($transactionEnd)){
$filter["whereText"] = " DATE_FORMAT(t.dateRegister, '%Y-%m-%d') BETWEEN '{$transactionStart}' AND '{$transactionEnd}'";
}
if(!empty($productId)){
$filter["ti.product"] = $productId;
}
if(!empty($transactionItemId)){
$filter["ti.id"] = $transactionItemId;
}
if(!empty($userSeller)){
$filter["ti.userSeller"] = $userSeller;
}
$order = ["ti.id" => "ASC"];
$data = $this->repository->paginate(
"ti",
null,
$columns,
$joins,
$filter,
$order,
$limit,
$offset
);
if(count($data['rows']) == 0){
return $this->eadResponse(null, ErrorEnum::NO_CONTENT, null);
}
if($paginate == 1){
unset($data['searchText']);
return $this->json($data);
}
return $this->json($data['rows']);
}
/**
* Excluir uma transação do EAD.
*
* @Route("/api/1/sales/{id}", methods={"DELETE"})
* @OA\Response(
* response=200,
* description="Success",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=200, description="Success"),
* @OA\Property(property="message", type="string", example="Success"),
* @OA\Property(property="data", nullable=true, type="application/json", example="null"),
* )
* )
*
* @OA\Response(
* response=401,
* description="Token not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=401, description="Token not found"),
* @OA\Property(property="message", type="string", example="Token not found")
* )
* )
*
* @OA\Response(
* response=404,
* description="Not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=404, description="Not found"),
* @OA\Property(property="message", type="string", example="Not found"),
* @OA\Property(
* property="data",
* type="array",
* collectionFormat="multi",
* @OA\Items(
* type="string",
* example="field"
* )
* ),
* )
* )
*
* @OA\Response(
* response=429,
* description="Too many requests",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=429, description="Too many requests"),
* @OA\Property(property="message", type="string", example="Too many requests")
* )
* )
*
* @OA\Response(
* response=500,
* description="Internal Server Error",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=500, description="Internal Server Error"),
* @OA\Property(property="message", type="string", example="Internal Server Error")
* )
* )
*
* @OA\Parameter(
* name="id",
* in="path",
* description="Transação Id",
* required=true,
* @OA\Schema(type="string")
* )
*
* @OA\Tag(name="Transações")
* @Security(name="Bearer")
*
*/
public function deleteTransaction(Request $request)
{
$this->requestUtil->setRequest($request)->setData();
$transactionId = $request->get('id');
$transaction = $this->em->getRepository(Transaction::class)->findOneBy([
"id" => $transactionId,
"deleted" => TransactionItemEnum::ITEM_NO_DELETED
]);
if (!$transaction) {
return $this->eadResponse(null, ErrorEnum::NOT_FOUND, ErrorEnum::MESSAGE_NOT_FOUND);
}
$this->em->getRepository(Transaction::class)->delete($transaction, TrashEnum::TRANSACTION);
$this->userLogService->logDelete(
"transaction",
$transaction->getId(),
null,
UserLogEnum::ORIGIN_CLIENT_API
);
return $this->eadResponse(null, ErrorEnum::SUCCESS, ErrorEnum::MESSAGE_SUCCESS);
}
}