<?php
namespace App\EventListener;
use App\Message\ManualRegistrationMessage;
use App\Services\Functions;
use App\Services\PromoGetter;
use App\StripeManager\CreateCustomer;
use Pimcore\Event\Model\ElementEventInterface;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Log\ApplicationLogger;
use Pimcore\Model\Asset;
use Pimcore\Model\DataObject\MembersUser;
use Symfony\Component\Messenger\MessageBusInterface;
use Carbon\Carbon;
use Exception;
use Pimcore\Log\Simple;
use Pimcore\Model\DataObject\Service;
use Pimcore\Model\DataObject\Folder;
use Pimcore\Model\DataObject\MemberStripeAccount;
use Pimcore\Model\DataObject\PromoRules;
class MembersListener
{
private $bus;
private $logger;
public function __construct(MessageBusInterface $bus, ApplicationLogger $logger)
{
$this->bus = $bus;
$this->logger = $logger;
}
public function onPreAdd(ElementEventInterface $e)
{
if ($e instanceof DataObjectEvent) {
$object = $e->getObject();
if ($object instanceof MembersUser) {
$bytes = openssl_random_pseudo_bytes(4);
$pwd = bin2hex($bytes);
// $group = \Pimcore\Model\DataObject\MembersGroup::getByName('Subscriber',1);
if (empty($object->getPassword())) {
$object->setPassword($pwd);
$object->setTempPlainPwd($pwd);
} else {
$object->setTempPlainPwd($object->getPassword());
}
$object->setActive(false);
$object->setCreatedDate(Carbon::now());
$object->setLastUpdateDate(Carbon::now());
// $object->setGroups([$group]);
}
}
}
public function onPreUpdate(ElementEventInterface $e)
{
if ($e instanceof DataObjectEvent) {
$object = $e->getObject();
if ($object instanceof \Pimcore\Model\DataObject\MembersUser) {
try {
if (!empty($object->getSource()) && $object->getActive()) {
// $object->setStripeCustomerId($customerStripeId);
$source = $object->getSource();
if ($source !== null) {
$MemberStripeAccount = new MemberStripeAccount\Listing();
$MemberStripeAccount->setUnpublished(true);
$MemberStripeAccount->setCondition('customerId = ? AND source__id = ?', [
$object->getId(),
$object->getSource()->getId()
]);
$MemberStripeAccount->setLimit(1);
$stripeDataObj = $MemberStripeAccount->current();
if ($stripeDataObj == null || null == ($customerStripeId = $stripeDataObj->getStripeCustomerId())) {
$customerStripeId = CreateCustomer::add($object);
}
if (!empty($customerStripeId)) {
$folder = Folder::getByPath(PIMCORE_MEMBER_STRIPE_ACCOUNT_FOLDER);
if (!($folder instanceof Folder))
$folder = Service::createFolderByPath(PIMCORE_MEMBER_STRIPE_ACCOUNT_FOLDER);
if ($stripeDataObj == null) {
$stripeDataObj = new MemberStripeAccount();
$stripeDataObj->setKey($object->getId() . '_' . $customerStripeId);
$stripeDataObj->setParent($folder);
}
$stripeDataObj->setCustomerId($object->getId());
$stripeDataObj->setSource($source);
$stripeDataObj->setStripeCustomerId($customerStripeId);
$stripeDataObj->setPublished(true);
$stripeDataObj->save();
$object->setSource(null);
$object->setStripeCustomerId(null);
$object->setStripeData($this->getUserSourceList($object));
}
}
}
/** $pathConvention could be "/restricted-assets/{MembersKey}-{MembersUsername}" */
$pathConvention = Functions::getPathConvention([$object->getKey(), $object->getUserName()]);
// Check Asset folder
$storeAssetsFolder = Asset\Folder::getByPath($pathConvention);
if (!($storeAssetsFolder instanceof Asset\Folder))
$storeAssetsFolder = Asset\Service::createFolderByPath($pathConvention);
// Check and move Gallery Images
foreach ($object->getDocuments() as $document) {
if ($document instanceof Asset) {
$document = Functions::moveAssetToFolder($document, $storeAssetsFolder);
}
}
$promos = PromoRules::getById($object->getRules());
if (!empty($promos)) {
$promoTable = [];
foreach ($promos->getPromo() as $i => $promo) {
$priceObj = $promo['price']->getData();
$price = $priceObj->getPriceId();
$promotionObj = $promo['promo']->getData();
$promotion = $promotionObj->getPromoId();
$promoTable[$i][] = $price;
$promoTable[$i][] = $promotion;
}
$msa = new MemberStripeAccount\Listing();
$msa->setCondition('customerId = ? AND source__id = ?', [
$object->getId(),
$promos->getAccount()
]);
$msa = $msa->current();
try {
if ($promoTable && $msa !== false) {
$msa->setPromoCode($promoTable);
$msa->save();
$object->setRules(null);
}
} catch (Exception $e) {
$this->logger->error($e->getMessage());
}
// $object->setRules(null);
}
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
}
}
}
private function getUserSourceList($object)
{
return MemberStripeAccount::getByCustomerId($object->getId())->getData();
}
public function onPostUpdate(ElementEventInterface $e)
{
try {
if ($e instanceof DataObjectEvent) {
$object = $e->getObject();
if ($object instanceof MembersUser) {
if ($object->getStripeData()) {
foreach ($object->getStripeData() as $stripeAccount) {
if ($stripeAccount->getSource()->getServiceEndpoint()?->getHref()) {
$promoCodes = PromoGetter::getUserPromoCodes($stripeAccount->getSource()->getObjectKey(), $object);
if (isset($object->getGroups()[0])) {
$this->updateUser($object->getEmail(), $object->getPassword(), $object->getGroups()[0]->getName(), $object->getActive(), $stripeAccount->getSource()->getServiceEndpoint()->getHref(), $promoCodes);
} else {
$this->logger->warning("Missing group " . $object->getId());
}
}
}
} elseif ($object->getSource()) {
$promoCodes = PromoGetter::getUserPromoCodes($object->getSource()->getObjectKey(), $object);
if (isset($object->getGroups()[0])) {
$this->updateUser($object->getEmail(), $object->getPassword(), $object->getGroups()[0]->getName(), $object->getActive(), $object->getSource()->getServiceEndpoint()->getHref(), $promoCodes);
} else {
$this->logger->warning("Missing group " . $object->getId());
}
}
if (empty($object->getMailSent()) && empty($object->getLastLogin()) && $object->getActive()) {
$this->logger->info('Invio mail registrazione');
$this->bus->dispatch(new ManualRegistrationMessage($object));
}
if ($object->getActive() && $object->getSource()) {
$promoCodes = PromoGetter::getUserPromoCodes($object->getSource()->getObjectKey(), $object);
if (isset($object->getGroups()[0])) {
$this->registrationToServicePortal($object->getUserName(), $object->getTempPlainPwd(), $object->getGroups()[0]->getName(), $object->getSource()->getServiceEndpoint()->getHref(), $promoCodes);
} else {
$this->logger->warning("Missing group " . $object->getId());
}
// $object->setSource(null);
// $object->save();
}
}
}
} catch (\Exception $e) {
$this->logger->error($e);
}
}
public function onPostAdd(ElementEventInterface $e)
{
// if ($e instanceof DataObjectEvent) {
// $object = $e->getObject();
//
// if($object instanceof MembersUser){
// if (empty($object->getMailSent())) {
// if ($object->getActive() && !empty($object->getTempPlainPwd())){
// $this->bus->dispatch(new ManualRegistrationMessage($object));
// }
// }
// }
// }
}
public function onPostDelete(ElementEventInterface $e)
{
if ($e instanceof DataObjectEvent) {
$object = $e->getObject();
if ($object instanceof MembersUser) {
$userStripeAccounts = MemberStripeAccount::getByCustomerId($object->getId());
foreach ($userStripeAccounts as $userStripeAccount) {
$userStripeAccount->delete();
}
}
}
}
public function onRegistrationConfirm(\MembersBundle\Event\GetResponseUserEvent $e)
{
try {
$object = $e->getUser();
if ($object instanceof MembersUser) {
$object->setActive(true);
$promoCodes = PromoGetter::getUserPromoCodes($object->getSource()->getObjectKey(), $object);
$this->registrationToServicePortal($object->getUserName(), $object->getTempPlainPwd(), $object->getGroups()[0]->getName(), $object->getSource()->getServiceEndpoint()->getHref(), $promoCodes);
// $object->setSource(null);
// $object->save();
}
} catch (\Exception $e) {
$this->logger->error($e);
}
}
private function updateUser($user, $password, $type, $active, $endpoint, $promo)
{
try {
$data = array(
'email' => $user,
'pwd' => $password,
'type' => $type,
'active' => $active ? 1 : 0,
'authorizationKey' => '9825ec00fe638ad48591b0016c1916f4484aa3683168c8dcb97174bb86894d55',
'promo' => serialize($promo)
);
$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)';
$json = json_encode($data);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $endpoint . '/api/updateUser',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_USERAGENT => $agent,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_VERBOSE => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $json,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
),
));
$response = curl_exec($curl);
$result = json_decode($response, true);
if ($result === false || empty($result)) {
$this->logger->error(curl_error($curl));
return false;
}
if ($result['error']) {
$this->logger->error($result);
}
curl_close($curl);
$this->logger->info($response);
// return $response && $response['success'] == false ? false : true;
} catch (\Exception $e) {
$this->logger->error($e);
return false;
}
}
private function registrationToServicePortal($user, $password, $type, $endpoint, $promo)
{
try {
$data = array(
'email' => $user,
'pwd' => $password,
'type' => $type,
'authorizationKey' => '9825ec00fe638ad48591b0016c1916f4484aa3683168c8dcb97174bb86894d55',
'promo' => serialize($promo)
);
$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)';
$json = json_encode($data);
$curl = curl_init();
Simple::log('member', $endpoint . '/api/userRegistration');
curl_setopt_array($curl, array(
CURLOPT_URL => $endpoint . '/api/userRegistration',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_USERAGENT => $agent,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_VERBOSE => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $json,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
),
));
$response = curl_exec($curl);
$result = json_decode($response, true);
if ($result === false || empty($result)) {
throw new Exception(curl_error($curl), curl_errno($curl));
}
if ($result['error']) {
$this->logger->error($result);
}
curl_close($curl);
// return $response && $response['success'] == false ? false : true;
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
return false;
}
}
}