Fix customer retrieval from paymongo #799

This commit is contained in:
Ramon Gutierrez 2024-10-02 13:28:27 +08:00
parent 5056637b66
commit d2a0638ffa
2 changed files with 53 additions and 17 deletions

View file

@ -6,6 +6,7 @@ use Symfony\Component\HttpFoundation\Request;
use Catalyst\ApiBundle\Component\Response as ApiResponse; use Catalyst\ApiBundle\Component\Response as ApiResponse;
use App\Service\PayMongoConnector; use App\Service\PayMongoConnector;
use App\Entity\Customer;
use App\Entity\Vehicle; use App\Entity\Vehicle;
use App\Entity\Subscription; use App\Entity\Subscription;
use App\Entity\CustomerVehicle; use App\Entity\CustomerVehicle;
@ -42,6 +43,8 @@ class SubscriptionController extends ApiController
$plan = $pm->getPlanByBatterySize($batts[0]->getSize()); $plan = $pm->getPlanByBatterySize($batts[0]->getSize());
} }
error_log("FOUND PLAN FOR $vid: " . print_r($plan, true));
// response // response
return new ApiResponse(true, '', [ return new ApiResponse(true, '', [
'plan' => $plan, 'plan' => $plan,
@ -72,6 +75,7 @@ class SubscriptionController extends ApiController
$validity = $this->validateRequest($req, [ $validity = $this->validateRequest($req, [
'plan_id', 'plan_id',
'cv_id', 'cv_id',
'email',
]); ]);
if (!$validity['is_valid']) { if (!$validity['is_valid']) {
@ -84,6 +88,21 @@ class SubscriptionController extends ApiController
return new ApiResponse(false, 'No customer information found.'); return new ApiResponse(false, 'No customer information found.');
} }
// verify email does not belong to someone else
$email = $req->request->get('email');
$qb = $this->em->getRepository(Customer::class)
->createQueryBuilder('c')
->select('c')
->where('c.email = :email')
->andWhere('c.id != :cust_id')
->setParameter('email', $email)
->setParameter('cust_id', $cust->getID());
$email_exists = $qb->getQuery()->getOneOrNullResult();
if (!empty($email_exists)) {
return new ApiResponse(false, 'Email is already in use. Please use a different email address.');
}
// get customer vehicle // get customer vehicle
$cv = $this->em->getRepository(CustomerVehicle::class)->find($req->request->get('cv_id')); $cv = $this->em->getRepository(CustomerVehicle::class)->find($req->request->get('cv_id'));
@ -101,7 +120,7 @@ class SubscriptionController extends ApiController
$this->initializeSubscriptionPayMongoConnector($pm); $this->initializeSubscriptionPayMongoConnector($pm);
// get paymongo customer // get paymongo customer
$pm_cust = $pm->findOrCreateCustomer($cust); $pm_cust = $pm->findOrCreateCustomer($email, $cust);
if (empty($pm_cust)) { if (empty($pm_cust)) {
return new ApiResponse(false, 'Error retrieving customer record. Please try again later.'); return new ApiResponse(false, 'Error retrieving customer record. Please try again later.');
} }
@ -132,10 +151,17 @@ class SubscriptionController extends ApiController
$obj = new Subscription(); $obj = new Subscription();
$obj->setCustomer($cust) $obj->setCustomer($cust)
->setCustomerVehicle($cv) ->setCustomerVehicle($cv)
->setEmail($email)
->setStatus(SubscriptionStatus::PENDING) ->setStatus(SubscriptionStatus::PENDING)
->setExtApiId($pm_sub['response']['data']['id']) ->setExtApiId($pm_sub['response']['data']['id'])
->setMetadata($pm_sub['response']['data']); ->setMetadata($pm_sub['response']['data']);
// if requested to save email, save it
if (!empty($req->request->get('remember_email'))) {
$cust->setEmail($email);
}
// save stuff to db
$this->em->persist($obj); $this->em->persist($obj);
$this->em->flush(); $this->em->flush();

View file

@ -2,12 +2,15 @@
namespace App\Service; namespace App\Service;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Psr7; use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Exception\RequestException;
use App\Entity\Customer; use App\Entity\Customer;
use App\Entity\BatterySize; use App\Entity\BatterySize;
use Doctrine\ORM\Query\Parameter;
class PayMongoConnector class PayMongoConnector
{ {
@ -18,9 +21,12 @@ class PayMongoConnector
protected $public_hash; protected $public_hash;
protected $secret_hash; protected $secret_hash;
public function __construct($base_url) protected $sub_months;
public function __construct($base_url, ParameterBagInterface $params)
{ {
$this->base_url = $base_url; $this->base_url = $base_url;
$this->sub_months = $params->get('subscription_months');
} }
public function initialize($public_key, $secret_key) public function initialize($public_key, $secret_key)
@ -94,7 +100,7 @@ class PayMongoConnector
public function getPlans() public function getPlans()
{ {
return $this->doRequest('/v1/subscriptions/plans', 'GET'); return $this->doRequest('/v1/subscriptions/plans?limit=100', 'GET');
} }
public function getPlanByBatterySize(BatterySize $bsize) public function getPlanByBatterySize(BatterySize $bsize)
@ -129,7 +135,7 @@ class PayMongoConnector
'description' => $plan_data['description'], 'description' => $plan_data['description'],
'interval' => $plan_data['interval'], 'interval' => $plan_data['interval'],
'interval_count' => $plan_data['interval_count'], 'interval_count' => $plan_data['interval_count'],
'cycle_count' => $plan_data['cycle_count'], //'cycle_count' => $plan_data['cycle_count'],
'name' => $plan_data['name'], 'name' => $plan_data['name'],
'metadata' => $plan_data['metadata'], 'metadata' => $plan_data['metadata'],
], ],
@ -169,6 +175,7 @@ class PayMongoConnector
'description' => "Motolite Battery Subscription Plan", 'description' => "Motolite Battery Subscription Plan",
'interval' => 'monthly', 'interval' => 'monthly',
'interval_count' => 1, 'interval_count' => 1,
//'cycle_count' => $this->sub_months,
'metadata' => [ 'metadata' => [
'battery_size_id' => (string)$bsize->getID(), 'battery_size_id' => (string)$bsize->getID(),
], ],
@ -183,7 +190,7 @@ class PayMongoConnector
return $this->doRequest('/v1/customers?email=' . $email, 'GET'); return $this->doRequest('/v1/customers?email=' . $email, 'GET');
} }
public function createCustomer(Customer $cust) public function createCustomer(Customer $cust, $email_override = "")
{ {
$body = [ $body = [
'data' => [ 'data' => [
@ -191,7 +198,7 @@ class PayMongoConnector
'first_name' => $cust->getFirstName(), 'first_name' => $cust->getFirstName(),
'last_name' => $cust->getLastName(), 'last_name' => $cust->getLastName(),
'phone' => "+63" . $cust->getPhoneMobile(), 'phone' => "+63" . $cust->getPhoneMobile(),
'email' => $cust->getEmail(), 'email' => $email_override ?? $cust->getEmail(),
'default_device' => 'email', 'default_device' => 'email',
], ],
], ],
@ -236,30 +243,33 @@ class PayMongoConnector
return false; return false;
} }
public function findOrCreateCustomer(Customer $cust) public function findOrCreateCustomer($email, Customer $cust)
{ {
$email = $cust->getEmail(); error_log("FINDING RECORD FOR $email");
// if no email, then we don't need to update
if (empty($email)) {
return false;
}
// check if we have an existing paymongo customer with this email // check if we have an existing paymongo customer with this email
$found_cust = $this->findCustomerByEmail($email); $found_cust = $this->findCustomerByEmail($email);
$pm_cust = null; $pm_cust = null;
error_log("FOUND CUSTOMER?");
error_log(print_r($found_cust, true));
if (isset($found_cust['response']['data'][0]['id'])) { if (isset($found_cust['response']['data'][0]['id'])) {
// we found a customer record // we found a customer record
$pm_cust = $found_cust['response']['data'][0]; $pm_cust = $found_cust['response']['data'][0];
} else { } else {
// we create a new customer record error_log("CREATING CUSTOMER");
$new_cust = $this->createCustomer($cust);
if (isset($new_cust['response']['data'][0]['id'])) { // we create a new customer record
$new_cust = $this->createCustomer($cust, $email);
error_log("NEW CUST RESPONSE");
error_log(print_r($new_cust, true));
if (isset($new_cust['response']['data']['id'])) {
// customer record was created successfully // customer record was created successfully
$pm_cust = $new_cust['response']['data'][0]; $pm_cust = $new_cust['response']['data'];
} }
} }