<?php
namespace ApplicationBundle\Modules\HoneybeeWeb\Controller;
use ApplicationBundle\Constants\BuddybeeConstant;
use ApplicationBundle\Constants\EmployeeConstant;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Controller\GenericController;
use ApplicationBundle\Entity\DatevToken;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
use ApplicationBundle\Modules\Buddybee\Buddybee;
use ApplicationBundle\Modules\System\MiscActions;
use CompanyGroupBundle\Entity\EntityCreateTopic;
use CompanyGroupBundle\Entity\PaymentMethod;
use CompanyGroupBundle\Entity\EntityDatevToken;
use CompanyGroupBundle\Entity\Device;
use CompanyGroupBundle\Entity\EntityInvoice;
use CompanyGroupBundle\Entity\EntityMeetingSession;
use CompanyGroupBundle\Entity\EntityTicket;
use Endroid\QrCode\Builder\BuilderInterface;
use Endroid\QrCodeBundle\Response\QrCodeResponse;
use Ps\PdfBundle\Annotation\Pdf;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use CompanyGroupBundle\Entity\EntityApplicantDetails;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
//use Symfony\Bundle\FrameworkBundle\Console\Application;
//use Symfony\Component\Console\Input\ArrayInput;
//use Symfony\Component\Console\Output\NullOutput;
class HoneybeeWebPublicController extends GenericController
{
private function getPublicDocumentEntityManager($appId)
{
$emGoc = $this->getDoctrine()->getManager('company_group');
$emGoc->getConnection()->connect();
$goc = $emGoc
->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
->findOneBy(
array(
'appId' => $appId
)
);
if (!$goc) {
return array(null, null);
}
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$goc->getDbName(),
$goc->getDbUser(),
$goc->getDbPass(),
$goc->getDbHost(),
$reset = true
);
return array($this->getDoctrine()->getManager(), $goc);
}
// home page
public function CentralHomePageAction(Request $request)
{
$em = $this->getDoctrine()->getManager('company_group');
$subscribed = false;
if ($request->isMethod('POST')) {
$entityTicket = new EntityTicket();
$entityTicket->setEmail($request->request->get('newsletter'));
$em->persist($entityTicket);
$em->flush();
$subscribed = true;
}
return $this->render('@HoneybeeWeb/pages/home.html.twig', [
'page_title' => 'HoneyBee — Project ERP + Business ERP + HoneyCore Edge EMS',
'og_title' => 'HoneyBee — Business + Energy Infrastructure. One Operating System.',
'og_description' => 'HoneyBee connects Business ERP, Project ERP, HoneyCore Edge EMS, AI and mobile field operations in one ecosystem — so business, project, finance, site, asset and energy data work together.',
'subscribed' => $subscribed,
'packageDetails' => GeneralConstant::$packageDetails,
]);
}
// about us
public function CentralAboutUsPageAction()
{
return $this->render('@HoneybeeWeb/pages/about_us.html.twig', array(
'page_title' => 'About HoneyBee | Building the Operating System for Project Businesses & Energy Infrastructure',
'og_title' => 'About HoneyBee | Building the Operating System for Project Businesses & Energy Infrastructure',
'og_description' => 'HoneyBee is a Germany/EU + Singapore-oriented software ecosystem connecting Business ERP, Project ERP, HoneyCore Edge EMS, AI, and mobile operations — with engineering, development, implementation, and regional support from Bangladesh.',
'packageDetails' => GeneralConstant::$packageDetails,
));
}
// Contact page
public function CentralContactPageAction(Request $request)
{
$em = $this->getDoctrine()->getManager('company_group');
if ($request->isXmlHttpRequest()) {
$email = $request->request->get('email');
if ($email) {
// Enrich the message with the 3-step form selectors (need / company type / phone),
// and persist any uploaded workflow/site-requirement file (graceful if absent).
$bodyParts = [trim((string) $request->request->get('message', ''))];
$need = trim((string) $request->request->get('enquiry_need', ''));
$companyType = trim((string) $request->request->get('company_type', ''));
$phone = trim((string) $request->request->get('phone', ''));
if ($need !== '') { $bodyParts[] = 'Need: ' . $need; }
if ($companyType !== '') { $bodyParts[] = 'Company type: ' . $companyType; }
if ($phone !== '') { $bodyParts[] = 'Phone: ' . $phone; }
$uploaded = $request->files->get('workflow_file');
if ($uploaded) {
try {
$projectDir = $this->getParameter('kernel.project_dir');
$relDir = 'uploads/contact/' . date('Y/m');
$absDir = rtrim($projectDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relDir);
if (!is_dir($absDir)) { @mkdir($absDir, 0775, true); }
$ext = method_exists($uploaded, 'guessExtension') ? ($uploaded->guessExtension() ?: 'dat') : 'dat';
$name = 'contact_' . date('YmdHis') . '_' . mt_rand(1000, 9999) . '.' . $ext;
$uploaded->move($absDir, $name);
$bodyParts[] = 'Attachment: /' . $relDir . '/' . $name;
} catch (\Throwable $e) { /* non-fatal: still save the message */ }
}
$entityTicket = new EntityTicket();
$entityTicket->setEmail($email);
$entityTicket->setName($request->request->get('name'));
$entityTicket->setTitle($request->request->get('subject'));
$entityTicket->setTicketBody(implode("\n", array_filter($bodyParts)));
$em->persist($entityTicket);
$em->flush();
return new JsonResponse([
'success' => true,
'message' => 'Your message has been sent successfully. Our team will reply soon.'
]);
}
return new JsonResponse([
'success' => false,
'message' => 'Invalid email address.'
]);
}
return $this->render('@HoneybeeWeb/pages/contact.html.twig', array(
'page_title' => 'Request a HoneyBee Project Solution | HoneyCore Edge+, IoT, Billing & AI Deployment',
'og_title' => 'Request a HoneyBee Project Solution | HoneyCore Edge+, IoT, Billing & AI Deployment',
'og_description' => 'Tell us about your EPC, energy asset, HoneyCore Edge+ or multi-site project. A HoneyBee solutions engineer will respond with a tailored deployment plan.',
));
}
// blogs
public function CentralBlogsPageAction(Request $request)
{
$em = $this->getDoctrine()->getManager('company_group');
$topicDetails = $em->getRepository('CompanyGroupBundle\Entity\EntityCreateTopic')->findAll();
$repo = $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog');
// ── Fetch featured blog separately (always, regardless of page) ──
$featuredBlog = $repo->findOneBy(['isPrimaryBlog' => true]);
// ── Pagination ──
$page = max(1, (int) $request->query->get('page', 1));
$limit = 6;
$totalBlogs = count($repo->findAll());
$totalPages = max(1, (int) ceil($totalBlogs / $limit));
$page = min($page, $totalPages);
$offset = ($page - 1) * $limit;
$blogDetails = $repo->findBy([], ['Id' => 'DESC'], $limit, $offset);
return $this->render('@HoneybeeWeb/pages/blogs.html.twig', [
'page_title' => 'Blogs',
'topics' => $topicDetails,
'blogs' => $blogDetails,
'featuredBlog' => $featuredBlog,
'currentPage' => $page,
'totalPages' => $totalPages,
'totalBlogs' => $totalBlogs,
]);
}
// product
public function CentralProductPageAction()
{
return $this->render('@HoneybeeWeb/pages/product.html.twig', array(
'page_title' => 'HoneyBee Platform | One ecosystem, four connected layers',
'og_description' => 'Business ERP, Project ERP, HoneyCore Edge EMS, AI and mobile — one connected platform, not bolted-together tools.',
));
}
// ── Phase 2 marketing pages (website restructure) ──
public function CentralProjectErpPageAction()
{
return $this->render('@HoneybeeWeb/pages/project_erp.html.twig', array(
'page_title' => 'Project ERP for EPC, Engineering & Solar | HoneyBee',
'og_description' => 'Control every project from quotation to cash collection: BoQ, procurement, site execution, milestone billing, retention, O&M, profitability — plus HoneyCore Edge+ project workflows.',
));
}
public function CentralBusinessErpPageAction()
{
return $this->render('@HoneybeeWeb/pages/business_erp.html.twig', array(
'page_title' => 'Business ERP for SMEs | HR, Accounts, Inventory, CRM — HoneyBee',
'og_description' => 'Affordable, modular Business ERP for growing SMEs in Europe and Singapore. Start small, expand when ready — from €7.99/user/month.',
));
}
public function CentralEdgePageAction()
{
return $this->render('@HoneybeeWeb/pages/honeycore_edge.html.twig', array(
'page_title' => 'HoneyCore Edge EMS | Energy & Site Intelligence — HoneyBee',
'og_description' => 'Connect solar PV, grid, generators, batteries, meters and sensors with O&M, billing, finance and reporting through HoneyCore Edge EMS site intelligence.',
));
}
public function CentralEdgeProjectsPageAction()
{
return $this->render('@HoneybeeWeb/pages/honeycore_edge_projects.html.twig', array(
'page_title' => 'HoneyCore Edge+ Design & Quotation Software | HoneyBee',
'og_description' => 'Turn site requirements into HoneyCore Edge+ architecture, sensor/meter schedules, BoQ, quotation, commissioning checklist and O&M workflow.',
));
}
public function CentralExperiencePageAction()
{
return $this->render('@HoneybeeWeb/pages/experience.html.twig', array(
'page_title' => 'Experience & Proof | HoneyBee',
'og_description' => 'Built from real ERP, project, HoneyCore Edge EMS and SME digital-transformation experience — with Germany/EU product focus and a Singapore SaaS base.',
));
}
public function CentralTrustPageAction()
{
return $this->render('@HoneybeeWeb/pages/trust_governance.html.twig', array(
'page_title' => 'Trust & Governance | Security & Standards — HoneyBee',
'og_description' => 'Operator-owned data, RBAC, audit trails, NIS2-aware governance and a clear, no-overclaim standards map with claim-control categories.',
));
}
// ── Investor Snapshot (Phase C) ──
public function CentralInvestorPageAction()
{
return $this->render('@HoneybeeWeb/pages/investor_snapshot.html.twig', array(
'page_title' => 'Investor Snapshot | HoneyBee — Business + Energy Infrastructure OS',
'og_description' => 'HoneyBee is a vertical operating system for project-based energy, engineering and industrial companies — positioning, ICP, revenue model and defensibility. No invented metrics.',
));
}
// ── Competitor comparison pages (Phase C) ──
public function CentralComparePageAction($slug)
{
$meta = [
'odoo' => ['HoneyBee vs Odoo | Project & Energy ERP Comparison', 'Odoo is a broad ERP suite. HoneyBee is built around project execution, EPC workflows, field operations and energy-infrastructure intelligence.'],
'zoho' => ['HoneyBee vs Zoho | ERP for Project & Energy Companies', 'Zoho covers general business apps. HoneyBee connects ERP, project execution, finance, O&M and HoneyCore energy data in one workflow.'],
'sap-business-one' => ['HoneyBee vs SAP Business One | Project ERP Comparison', 'SAP Business One suits general operations. HoneyBee adds deep EPC/project execution and energy-infrastructure intelligence.'],
'microsoft-business-central' => ['HoneyBee vs Microsoft Business Central | Comparison', 'Business Central is a broad ERP. HoneyBee is purpose-built for project-based energy, engineering and industrial companies.'],
'monday-clickup' => ['HoneyBee vs Monday / ClickUp | Beyond Task Management', 'Monday and ClickUp manage tasks. HoneyBee connects tasks with quotation, BoQ, procurement, billing, finance and energy data.'],
'excel' => ['HoneyBee vs Excel | From Spreadsheets to an Operating System', 'Excel is flexible but fragile. HoneyBee gives structure, audit trail, approvals, real-time data and automation.'],
'scada-ems' => ['HoneyBee vs SCADA / EMS Dashboards | Asset Data to Business', 'SCADA/EMS tools monitor assets. HoneyBee connects asset data with ERP, O&M, billing, reporting and AI.'],
];
if (!isset($meta[$slug])) { throw $this->createNotFoundException(); }
return $this->render('@HoneybeeWeb/pages/compare/' . $slug . '.html.twig', array(
'page_title' => $meta[$slug][0],
'og_description' => $meta[$slug][1],
'compare_slug' => $slug,
));
}
// ── SEO solution landing pages (Phase C) ──
public function CentralSolutionPageAction($slug)
{
$meta = [
'erp-for-solar-epc' => ['ERP for Solar EPC Companies | HoneyBee Project ERP', 'Project ERP for solar EPC: quotation, BoQ, procurement, site execution, milestone billing, O&M and HoneyCore Edge EMS energy intelligence.'],
'erp-for-engineering' => ['ERP for Engineering Companies | HoneyBee Project ERP', 'Control engineering projects from quotation to delivery, billing and profitability with HoneyBee Project ERP.'],
'erp-for-construction' => ['ERP for Construction Project Companies | HoneyBee', 'BoQ, procurement, site execution, milestone billing and retention for construction project companies.'],
'erp-for-om' => ['ERP for O&M Companies | HoneyBee', 'Connect O&M workflows with billing, reporting and energy-asset data through HoneyBee and HoneyCore Edge EMS.'],
'erp-for-trading' => ['ERP for Trading & Distribution Companies | HoneyBee', 'HR, accounts, inventory, sales, purchase and CRM for trading and distribution companies.'],
'project-erp-bangladesh' => ['Project ERP for Bangladesh SMEs | HoneyBee', 'Affordable project ERP for Bangladesh SMEs — quotation, procurement, site execution, billing and reporting.'],
'project-erp-singapore' => ['Project ERP for Singapore SMEs | HoneyBee', 'Project ERP for Singapore SMEs and project-based companies — execution, finance and reporting in one system.'],
'project-erp-germany' => ['Project ERP for German Energy Companies | HoneyBee', 'Project ERP for German energy and engineering companies, DATEV-ready export and GoBD-aligned audit trail where implemented.'],
'honeycore-solar-pv' => ['HoneyCore for Solar PV Monitoring | HoneyBee', 'HoneyCore Edge EMS connects solar PV, inverters and meters with O&M, billing, reporting and AI.'],
'honeycore-hybrid-energy'=> ['HoneyCore for Hybrid Energy Systems | HoneyBee', 'Monitor solar, battery, generator and grid in hybrid energy systems with HoneyCore Edge EMS.'],
'honeycore-cold-chain' => ['HoneyCore for Cold Chain & Healthcare Infrastructure | HoneyBee', 'Temperature, energy and utility monitoring for cold-chain and healthcare infrastructure with HoneyCore Edge EMS.'],
'honeycore-agri-pv' => ['HoneyCore for Agri-PV & Irrigation | HoneyBee', 'Connect solar generation, soil and irrigation data with HoneyCore Edge EMS for Agri-PV and solar irrigation.'],
];
if (!isset($meta[$slug])) { throw $this->createNotFoundException(); }
return $this->render('@HoneybeeWeb/pages/solutions/' . $slug . '.html.twig', array(
'page_title' => $meta[$slug][0],
'og_description' => $meta[$slug][1],
'solution_slug' => $slug,
));
}
// ── Calculators (Phase D) ──
public function CentralToolPageAction($slug)
{
$meta = [
'cost-leakage-calculator' => ['Project Cost Leakage Calculator | HoneyBee', 'Estimate the hidden annual loss from delays, procurement leakage, billing delays and inventory loss — and the right HoneyBee path.'],
'roi-calculator' => ['ERP ROI Calculator | HoneyBee', 'Estimate time saved and monthly savings from HoneyBee across approvals, invoices and projects.'],
'site-assessment-estimator' => ['HoneyCore Site Assessment Estimator | HoneyBee', 'Estimate your HoneyCore site assessment scope from sites, PV capacity, meters, inverters and protocols.'],
'rooftop-estimate' => ['Instant Rooftop Solar Estimate | HoneyBee', 'Draw your roof on the map and get an instant indicative solar sizing, BoQ and payback for C&I rooftop solar — powered by PVGIS yield data.'],
];
if (!isset($meta[$slug])) { throw $this->createNotFoundException(); }
return $this->render('@HoneybeeWeb/pages/tools/' . $slug . '.html.twig', array(
'page_title' => $meta[$slug][0],
'og_description' => $meta[$slug][1],
'tool_slug' => $slug,
'maps_key' => $this->mapsBrowserKey(),
));
}
// Failsafe default — used when no parameter is configured in parameters.yml.
const HB_MAPS_KEY = 'AIzaSyBJxyUy8a_U2rSdIUApVDoK_dcvgGkoeDk';
/** Server-side Google key (Geocoding + Solar API): parameter `google_maps_api_key`, else the built-in default. Never throws. */
private function mapsKey()
{
if ($this->container->hasParameter('google_maps_api_key')) {
$k = $this->container->getParameter('google_maps_api_key');
if (is_string($k) && trim($k) !== '') { return $k; }
}
return self::HB_MAPS_KEY;
}
/** Client-side (browser) Google key for the map JS: parameter `google_maps_browser_key`, else the server key, else default. Never throws. */
private function mapsBrowserKey()
{
if ($this->container->hasParameter('google_maps_browser_key')) {
$k = $this->container->getParameter('google_maps_browser_key');
if (is_string($k) && trim($k) !== '') { return $k; }
}
return $this->mapsKey();
}
// ── Rooftop estimate — MANUAL draw endpoint (area + coords from the map) ──
public function CentralRooftopCalcAction(Request $request)
{
$lat = (float) $request->request->get('lat', 0);
$lng = (float) $request->request->get('lng', 0);
$area = (float) $request->request->get('area_m2', 0);
$mode = $request->request->get('mode', 'roof');
$monthly = (float) $request->request->get('monthly_kwh', 0);
$tariff = (float) $request->request->get('tariff', 0.22);
$tilt = (float) $request->request->get('tilt', 10);
if ($area <= 5 || $lat == 0) {
return new JsonResponse(['ok' => false, 'error' => 'Draw a roof outline on the map first.']);
}
$res = $this->computeRooftopDesign($lat, $lng, $area, $tilt, $mode, $monthly, $tariff, null);
$res['roof_source'] = 'Map outline';
return new JsonResponse($res);
}
// ── Rooftop estimate — AUTO from ADDRESS (geocode → Google Solar API → OSM footprint → PVGIS) ──
public function CentralRooftopAutoAction(Request $request)
{
$address = trim((string) $request->request->get('address', ''));
$mode = $request->request->get('mode', 'roof');
$monthly = (float) $request->request->get('monthly_kwh', 0);
$tariff = (float) $request->request->get('tariff', 0.22);
$tilt = (float) $request->request->get('tilt', 10);
if ($address === '') {
return new JsonResponse(['ok' => false, 'error' => 'Enter an address first.']);
}
$geo = $this->geocodeAddress($address);
if ($geo === null) {
return new JsonResponse(['ok' => false, 'error' => 'Address not found — try a more specific address.']);
}
$lat = $geo['lat']; $lng = $geo['lng'];
// Tier 1: Google Solar API (best — real roof + panel layout). Null when API disabled / no coverage.
$preset = $this->solarApiDesign($lat, $lng);
$roofSource = null; $area = null;
if ($preset !== null) {
$area = $preset['roof_area']; $roofSource = 'Google Solar API';
} else {
// Tier 2: OSM building footprint (free, global where mapped).
$area = $this->osmBuildingArea($lat, $lng);
if ($area !== null) { $roofSource = 'OSM building footprint'; }
}
if ($area === null || $area < 10) {
// Tier 3: hand off to manual draw at the geocoded location.
return new JsonResponse([
'ok' => false, 'needs_manual' => true,
'lat' => $lat, 'lng' => $lng, 'formatted_address' => $geo['formatted'],
'error' => 'Could not auto-detect the roof at this address — trace it on the map below.',
]);
}
$res = $this->computeRooftopDesign($lat, $lng, $area, $tilt, $mode, $monthly, $tariff, $preset);
$res['lat'] = $lat; $res['lng'] = $lng;
$res['formatted_address'] = $geo['formatted'];
$res['roof_source'] = $roofSource;
return new JsonResponse($res);
}
/** Shared sizing + parametric BoQ + financials. $preset (Google Solar API) overrides area-based sizing. */
private function computeRooftopDesign($lat, $lng, $area, $tilt, $mode, $monthly, $tariff, $preset = null)
{
if ($tariff <= 0) { $tariff = 0.22; }
$yieldSource = 'PVGIS';
$specificYield = $this->pvgisSpecificYield($lat, $lng, $tilt);
if ($specificYield === null) {
$specificYield = $this->fallbackYieldByLatitude($lat);
$yieldSource = 'climate estimate';
}
$panelKw = 0.55;
if ($preset !== null && !empty($preset['panel_watts'])) { $panelKw = $preset['panel_watts'] / 1000.0; }
// Roof-capacity sizing
if ($preset !== null && !empty($preset['panels'])) {
$roofPanels = (int) $preset['panels'];
$roofKwp = round($roofPanels * $panelKw, 1);
$usable = round($area); // Solar API area is already usable roof
$genFull = !empty($preset['annual_dc_kwh']) ? $preset['annual_dc_kwh'] * 0.86 : $roofKwp * $specificYield; // DC→AC
} else {
$usable = $area * 0.65; // setbacks/walkways/plant
$roofPanels = (int) floor($usable / 2.4);
$roofKwp = round($roofPanels * $panelKw, 1);
$genFull = $roofKwp * $specificYield;
}
$panels = $roofPanels; $kwp = $roofKwp; $annualGen = $genFull;
if ($mode === 'load' && $monthly > 0 && $roofKwp > 0) {
$annualNeed = $monthly * 12 * 0.85;
$kwpNeeded = $annualNeed / max($specificYield, 1);
$kwp = round(min($kwpNeeded, $roofKwp), 1);
$panels = (int) round($kwp / $panelKw);
$annualGen = round($genFull * ($roofKwp > 0 ? $kwp / $roofKwp : 1));
}
$annualGen = round($annualGen);
if ($kwp <= 0) {
return ['ok' => false, 'error' => 'The detected roof is too small for a viable array.'];
}
$rows = [
['PV modules (~550 Wp)', $panels, 'pcs', 95.0],
['String inverters', max(1, (int) ceil($kwp / 25)), 'units', round($kwp * 55 / max(1, (int) ceil($kwp / 25)), 0)],
['Mounting & racking structure', $panels, 'sets', 38.0],
['DC + AC cabling & protection', round($kwp, 1), 'kWp', 75.0],
['Combiner, SPD & breakers', round($kwp, 1), 'kWp', 45.0],
['HoneyCore Edge EMS gateway + meter', 1, 'lot', 1000.0],
['Installation, commissioning & BoS', round($kwp, 1), 'kWp', 190.0],
];
$boq = []; $capex = 0.0;
foreach ($rows as $r) {
$total = round($r[1] * $r[3], 0);
$capex += $total;
$boq[] = ['item' => $r[0], 'qty' => $r[1], 'unit' => $r[2], 'unit_price' => $r[3], 'total' => $total];
}
$capex = round($capex, 0);
$annualSavings = round($annualGen * $tariff, 0);
$payback = $annualSavings > 0 ? round($capex / $annualSavings, 1) : null;
$co2 = round($annualGen * 0.35 / 1000, 1);
return [
'ok' => true, 'mode' => $mode,
'area_m2' => round($area), 'usable_m2' => round($usable),
'kwp' => $kwp, 'panels' => $panels,
'specific_yield' => round($specificYield), 'annual_gen_kwh' => $annualGen,
'capex_eur' => $capex, 'eur_per_kwp' => $kwp > 0 ? round($capex / $kwp, 0) : 0,
'boq' => $boq, 'tariff' => $tariff,
'annual_savings' => $annualSavings, 'payback_years' => $payback, 'co2_tonnes_yr' => $co2,
'yield_source' => $yieldSource,
'disclaimer' => 'Indicative estimate only — not a quote. Final sizing, BoQ and pricing are confirmed after a HoneyCore site assessment (structural, shading, electrical and tariff review).',
];
}
/** Geocode an address → ['lat','lng','formatted'] or null. */
private function geocodeAddress($address)
{
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $this->mapsKey();
$data = $this->httpJson($url, null, 8);
if (!$data || ($data['status'] ?? '') !== 'OK' || empty($data['results'][0])) { return null; }
$r = $data['results'][0];
return [
'lat' => (float) $r['geometry']['location']['lat'],
'lng' => (float) $r['geometry']['location']['lng'],
'formatted' => $r['formatted_address'] ?? $address,
];
}
/** Google Solar API building insights → preset design, or null if disabled / no coverage. */
private function solarApiDesign($lat, $lng)
{
$url = sprintf('https://solar.googleapis.com/v1/buildingInsights:findClosest?location.latitude=%F&location.longitude=%F&requiredQuality=LOW&key=%s', $lat, $lng, $this->mapsKey());
$data = $this->httpJson($url, null, 8);
if (!$data || isset($data['error']) || empty($data['solarPotential'])) { return null; }
$sp = $data['solarPotential'];
$roofArea = $sp['wholeRoofStats']['areaMeters2'] ?? ($sp['maxArrayAreaMeters2'] ?? null);
$panels = $sp['maxArrayPanelsCount'] ?? null;
$watts = $sp['panelCapacityWatts'] ?? 400;
if (!$roofArea || !$panels) { return null; }
// best (largest) config's annual DC energy
$annualDc = null;
foreach (($sp['solarPanelConfigs'] ?? []) as $cfg) {
if (isset($cfg['yearlyEnergyDcKwh'])) { $annualDc = $cfg['yearlyEnergyDcKwh']; }
}
return ['panels' => (int) $panels, 'panel_watts' => (float) $watts, 'annual_dc_kwh' => $annualDc, 'roof_area' => (float) $roofArea];
}
/** OSM building footprint area (m²) at a point via Overpass; null if none/unreachable. */
private function osmBuildingArea($lat, $lng)
{
$q = sprintf('[out:json][timeout:20];way(around:30,%F,%F)[building];out geom;', $lat, $lng);
$data = $this->httpJson('https://overpass-api.de/api/interpreter', 'data=' . rawurlencode($q), 22);
if (!$data || empty($data['elements'])) { return null; }
$best = null; $bestArea = 0; $containing = null;
foreach ($data['elements'] as $el) {
if (empty($el['geometry'])) { continue; }
$a = $this->polygonAreaM2($el['geometry']);
if ($a > $bestArea) { $bestArea = $a; $best = $el; }
if ($this->pointInPolygon($lat, $lng, $el['geometry'])) { $containing = $a; }
}
$area = $containing ?: $bestArea;
return $area > 5 ? $area : null;
}
/** Planar area (m²) of a lat/lng ring via equirectangular projection. */
private function polygonAreaM2($geometry)
{
$rad = M_PI / 180; $R = 6378137;
$lat0 = $geometry[0]['lat'] * $rad; $cos = cos($lat0);
$pts = [];
foreach ($geometry as $g) { $pts[] = [$g['lon'] * $rad * $R * $cos, $g['lat'] * $rad * $R]; }
$n = count($pts); if ($n < 3) { return 0; }
$a = 0;
for ($i = 0; $i < $n - 1; $i++) { $a += $pts[$i][0] * $pts[$i + 1][1] - $pts[$i + 1][0] * $pts[$i][1]; }
return abs($a) / 2;
}
/** Ray-cast point-in-polygon for a lat/lng ring. */
private function pointInPolygon($lat, $lng, $geometry)
{
$in = false; $n = count($geometry);
for ($i = 0, $j = $n - 1; $i < $n; $j = $i++) {
$yi = $geometry[$i]['lat']; $xi = $geometry[$i]['lon'];
$yj = $geometry[$j]['lat']; $xj = $geometry[$j]['lon'];
if ((($yi > $lat) !== ($yj > $lat)) && ($lng < ($xj - $xi) * ($lat - $yi) / (($yj - $yi) ?: 1e-12) + $xi)) { $in = !$in; }
}
return $in;
}
/** Minimal JSON HTTP helper (GET when $post is null, else POST form body). Null on failure. */
private function httpJson($url, $post = null, $timeout = 8)
{
try {
$opts = ['http' => ['timeout' => $timeout, 'ignore_errors' => true, 'header' => "User-Agent: HoneyBee/1.0\r\n"]];
if ($post !== null) {
$opts['http']['method'] = 'POST';
$opts['http']['header'] .= "Content-Type: application/x-www-form-urlencoded\r\n";
$opts['http']['content'] = $post;
}
$body = @file_get_contents($url, false, stream_context_create($opts));
if ($body === false) { return null; }
return json_decode($body, true);
} catch (\Throwable $e) {
return null;
}
}
/** Annual specific yield (kWh/kWp) from PVGIS for a fixed building-mounted array. Null on failure. */
private function pvgisSpecificYield($lat, $lng, $tilt)
{
$url = sprintf(
'https://re.jrc.ec.europa.eu/api/v5_2/PVcalc?lat=%F&lon=%F&peakpower=1&loss=14&angle=%F&aspect=0&mountingplace=building&outputformat=json',
$lat, $lng, $tilt
);
try {
$ctx = stream_context_create(['http' => ['timeout' => 8, 'ignore_errors' => true]]);
$body = @file_get_contents($url, false, $ctx);
if ($body === false) { return null; }
$data = json_decode($body, true);
$ey = $data['outputs']['totals']['fixed']['E_y'] ?? null;
return ($ey && $ey > 0) ? (float) $ey : null;
} catch (\Throwable $e) {
return null;
}
}
/** Rough kWh/kWp/yr by absolute latitude when PVGIS is unreachable. */
private function fallbackYieldByLatitude($lat)
{
$a = abs($lat);
if ($a < 15) { return 1500; } // tropical
if ($a < 25) { return 1450; } // e.g. BD/SG belt
if ($a < 35) { return 1350; } // subtropical
if ($a < 45) { return 1150; } // southern EU
if ($a < 55) { return 1000; } // central EU / DE
return 850; // northern EU
}
// our service
public function CentralServicePageAction()
{
return $this->render('@HoneybeeWeb/pages/service.html.twig', array(
'page_title' => 'Services | HoneyBee — Hardware, HoneyCore Edge EMS, Local ML & Integration',
));
}
// payment method
public function CentralPaymentMethodPageAction()
{
$stripe_secret_key= $this->container->getParameter('stripe_secret_key_live');
$stripe_key= $this->container->getParameter('stripe_public_key_live');
return $this->render('@HoneybeeWeb/pages/payment-method.html.twig', array(
'page_title' => 'Payment Method',
'stripe_key' => $stripe_key,
));
}
// single blog page
public function CentralSingleBlogPageAction(Request $request)
{
$em = $this->getDoctrine()->getManager('company_group');
$blogId = $request->query->get('id');
if (!$blogId) {
throw $this->createNotFoundException('Blog ID not provided.');
}
$blogDetails = $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->find($blogId);
if (!$blogDetails) {
throw $this->createNotFoundException('Blog not found.');
}
// Fetch related blogs by same topic (optional but useful)
$relatedBlogs = $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->findBy(
['topicId' => $blogDetails->getTopicId()],
['createdAt' => 'DESC'],
5
);
return $this->render('@HoneybeeWeb/pages/single_blog.html.twig', [
'page_title' => $blogDetails->getTitle(),
'blog' => $blogDetails,
'related_blogs' => $relatedBlogs,
]);
}
// login v2 (verification code page)
public function CentralLoginCodePageAction()
{
return $this->render('@HoneybeeWeb/pages/login_code.html.twig', array(
'page_title' => 'Verification Code',
));
}
// reset pass
public function CentralResetPasswordPageAction()
{
return $this->render('@HoneybeeWeb/pages/reset_password.html.twig', array(
'page_title' => 'Verification Code',
));
}
public function PublicProfilePageAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
return $this->render('@Application/pages/central/central_employee_profile.html.twig', array(
'page_title' => 'Freelancer Profile',
// 'details' =>$em->getRepository(EntityApplicantDetails::class)->find($id),
));
}
// freelancer profile
public function CentralApplicantProfilePageAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
return $this->render('@HoneybeeWeb/pages/freelancer_profile.html.twig', array(
'page_title' => 'Freelancer Profile',
'details' => $em->getRepository(EntityApplicantDetails::class)->find($id),
));
}
// employee profile
public function PublicEmployeeProfileAction($id)
{
$em = $this->getDoctrine()->getManager('company_group');
if (strpos($id, 'E') !== false) {
$appId = 1 * substr($id, 1, 5);
$empId = 1 * substr($id, 6, 10);
$entry = $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findOneBy([
'appId' => $appId
]);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_URL => $entry->getCompanyGroupServerAddress() . '/GetGlobalIdFromEmployeeId',
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
// 'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => http_build_query([
'employeeId' => $empId,
'appId' => $appId
])
]);
$id = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$id = json_decode($id, true)['globalId'];
}
$data = $em->getRepository(EntityApplicantDetails::class)->find($id);
return $this->render('@HoneybeeWeb/pages/public_profile.html.twig', array(
'page_title' => 'Employee Profile',
'details' => $data,
'genderList' => EmployeeConstant::$sex,
'bloodGroupList' => EmployeeConstant::$BloodGroup,
));
}
// add employee
public function CentralAddEmployeePageAction()
{
return $this->render('@HoneybeeWeb/pages/add_employee.html.twig', array(
'page_title' => 'Add New Eployee',
));
}
// book appointment
public function CentralBookAppointmentPageAction()
{
return $this->render('@HoneybeeWeb/pages/book_appointment.html.twig', array(
'page_title' => 'Book Appointment',
));
}
// create_compnay
public function CentralCreateCompanyPageAction()
{
return $this->render('@HoneybeeWeb/pages/create_company.html.twig', array(
'page_title' => 'Create Company',
));
}
// role and company
public function CentralRoleAndCompanyPageAction()
{
return $this->render('@HoneybeeWeb/pages/role_and_company.html.twig', array(
'page_title' => 'Role and Company',
));
}
// send otp action **
public function SendOtpAjaxAction(Request $request, $startFrom = 0)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$message = "";
$retData = array();
$email_twig_data = array('success' => false);
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$userCategory = $request->request->get('userCategory', $request->query->get('userCategory', '_BUDDYBEE_USER_'));
$email_address = $request->request->get('email', $request->query->get('email', ''));
$otpExpireSecond = $request->request->get('otpExpireSecond', $request->query->get('otpExpireSecond', 180));
$otpActionId = $request->request->get('otpActionId', $request->query->get('otpActionId', UserConstants::OTP_ACTION_FORGOT_PASSWORD));
$appendCode = $request->request->get('appendCode', $request->query->get('appendCode', ''));
$otp = $request->request->get('otp', $request->query->get('otp', ''));
$otpExpireTs = 0;
$userId = $request->request->get('userId', $request->query->get('userId', $session->get(UserConstants::USER_ID, 0)));
$userType = UserConstants::USER_TYPE_APPLICANT;
$email_twig_file = '@Application/pages/email/find_account_buddybee.html.twig';
if ($request->isMethod('POST')) {
//set an otp and its expire and send mail
$userObj = null;
$userData = [];
if ($systemType == '_ERP_') {
if ($userCategory == '_APPLICANT_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'email' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'oAuthEmail' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'username' => $email_address
)
);
}
}
}
if ($userObj) {
$email_address = $userObj->getEmail();
if ($email_address == null || $email_address == '')
$email_address = $userObj->getOAuthEmail();
}
$otpData = MiscActions::GenerateOtp($otpExpireSecond);
$otp = $otpData['otp'];
$otpExpireTs = $otpData['expireTs'];
$userObj->setOtp($otpData['otp']);
$userObj->setOtpActionId($otpActionId);
$userObj->setOtpExpireTs($otpData['expireTs']);
$em_goc->flush();
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
$email_twig_data = [
'page_title' => 'Find Account',
'message' => $message,
'userType' => $userType,
'otp' => $otpData['otp'],
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpExpireTs' => $otpData['expireTs'],
'systemType' => $systemType,
'userData' => $userData
];
if ($userObj)
$email_twig_data['success'] = true;
} else {
$userType = UserConstants::USER_TYPE_GENERAL;
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
$email_twig_data = [
'page_title' => 'Find Account',
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
];
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'email' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'oAuthEmail' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'username' => $email_address
)
);
}
}
}
if ($userObj) {
$email_address = $userObj->getEmail();
if ($email_address == null || $email_address == '')
$email_address = $userObj->getOAuthEmail();
// triggerResetPassword:
// type: integer
// nullable: true
$otpData = MiscActions::GenerateOtp($otpExpireSecond);
$otp = $otpData['otp'];
$otpExpireTs = $otpData['expireTs'];
$userObj->setOtp($otpData['otp']);
$userObj->setOtpActionId($otpActionId);
$userObj->setOtpExpireTs($otpData['expireTs']);
$em_goc->flush();
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'phone' => $userObj->getPhone(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
$email_twig_data = [
'page_title' => 'Find Account',
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
'otp' => $otpData['otp'],
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpActionTitle' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionTitle'],
'otpActionDescForMail' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionDescForMail'],
'otpExpireTs' => $otpData['expireTs'],
'systemType' => $systemType,
'userCategory' => $userCategory,
'userData' => $userData
];
$email_twig_data['success'] = true;
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'email' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'oAuthEmail' => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'username' => $email_address
)
);
}
}
}
if ($userObj) {
$email_address = $userObj->getEmail();
if ($email_address == null || $email_address == '')
$email_address = $userObj->getOAuthEmail();
// triggerResetPassword:
// type: integer
// nullable: true
$otpData = MiscActions::GenerateOtp($otpExpireSecond);
$otp = $otpData['otp'];
$otpExpireTs = $otpData['expireTs'];
$userObj->setOtp($otpData['otp']);
$userObj->setOtpActionId($otpActionId);
$userObj->setOtpExpireTs($otpData['expireTs']);
$em_goc->flush();
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'phone' => $userObj->getPhone(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_file = '@HoneybeeWeb/email/templates/otpMail.html.twig';
$email_twig_data = [
'page_title' => 'Find Account',
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
'otp' => $otpData['otp'],
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpActionTitle' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionTitle'],
'otpActionDescForMail' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionDescForMail'],
'otpExpireTs' => $otpData['expireTs'],
'systemType' => $systemType,
'userCategory' => $userCategory,
'userData' => $userData
];
$email_twig_data['success'] = true;
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
}
if ($email_twig_data['success'] == true && GeneralConstant::EMAIL_ENABLED == 1) {
if ($systemType == '_BUDDYBEE_') {
$bodyHtml = '';
$bodyTemplate = $email_twig_file;
$bodyData = $email_twig_data;
$attachments = [];
$forwardToMailAddress = $email_address;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Account Verification',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
} else {
$bodyHtml = '';
$bodyTemplate = $email_twig_file;
$bodyData = $email_twig_data;
$attachments = [];
$forwardToMailAddress = $email_address;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Account Verification',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
if ($email_twig_data['success'] == true && GeneralConstant::NOTIFICATION_ENABLED == 1 && $userData['phone'] != '' && $userData['phone'] != null) {
if ($systemType == '_BUDDYBEE_') {
$searchVal = ['_OTP_', '_EXPIRE_MINUTES_', '_APPEND_CODE_'];
$replaceVal = [$otp, floor($otpExpireSecond / 60), $appendCode];
$msg = 'Use OTP _OTP_ for BuddyBee. Your OTP will expire in _EXPIRE_MINUTES_ minutes
_APPEND_CODE_';
$msg = str_replace($searchVal, $replaceVal, $msg);
$emitMarker = '_SEND_TEXT_TO_MOBILE_';
$sendType = 'all';
$socketUserIds = [];
System::SendSmsBySocket($this->container->getParameter('notification_enabled'), $msg, $userData['phone'], $emitMarker, $sendType, $socketUserIds);
} else {
}
}
}
$response = new JsonResponse(array(
'message' => $message,
"userType" => $userType,
"otp" => '',
// "otp"=>$otp,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
"systemType" => $systemType,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
)
);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
// verrify otp **
public function VerifyOtpAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$message = "";
$retData = array();
$encData = $request->query->get('encData', $encData);
$encryptedData = [];
if ($encData != '')
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if ($encryptedData == null) $encryptedData = [];
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$userCategory = $request->request->get('userCategory', $request->query->get('userCategory', (isset($encryptedData['otp']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_')));
$email_address = $request->request->get('email', $request->query->get('email', (isset($encryptedData['email']) ? $encryptedData['email'] : '')));
$otpExpireSecond = $request->request->get('otpExpireSecond', $request->query->get('otpExpireSecond', 180));
$otpActionId = $request->request->get('otpActionId', $request->query->get('otpActionId', (isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : UserConstants::OTP_ACTION_FORGOT_PASSWORD)));
$otp = $request->request->get('otp', $request->query->get('otp', (isset($encryptedData['otp']) ? $encryptedData['otp'] : '')));
$otpExpireTs = isset($encryptedData['otpExpireTs']) ? $encryptedData['otpExpireTs'] : 0;
$userId = $request->request->get('userId', $request->query->get('userId', (isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID, 0))));
$userType = UserConstants::USER_TYPE_APPLICANT;
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$userEntityEmailField1 = 'email';
$userEntityEmailField1Getter = 'getEmail';
$userEntityEmailField1Setter = 'setEmail';
$userEntityEmailField2 = 'oAuthEmail';
$userEntityEmailField2Getter = 'geOAuthEmail';
$userEntityEmailField2Setter = 'seOAuthEmail';
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
$email_twig_data = array('success' => false);
$redirectUrl = '';
$userObj = null;
$userData = [];
if ($systemType == '_ERP_') {
if ($userCategory == '_APPLICANT_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
} else {
$userType = UserConstants::USER_TYPE_GENERAL;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'ApplicationBundle:SysUser';
$userEntityManager = $em;
$userEntityIdField = 'userId';
$userEntityUserNameField = 'userName';
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
}
if ($request->isMethod('POST') || $otp != '') {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityIdField => $userId
)
);
if ($userObj) {
} else {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityEmailField1 => $email_address
)
);
if ($userObj) {
} else {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityEmailField2 => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
$userEntityUserNameField => $email_address
)
);
}
}
}
if ($userObj) {
$userOtp = $userObj->getOtp();
$userOtpActionId = $userObj->getOtpActionId();
$userOtpExpireTs = 1 * $userObj->getOtpExpireTs();
$currentTime = new \DateTime();
$currentTimeTs = 1 * $currentTime->format('U');
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_data = [
'page_title' => 'OTP',
'success' => false,
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
'otp' => '',
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpExpireTs' => $userOtpExpireTs,
'systemType' => $systemType,
'userCategory' => $userCategory,
'userData' => $userData,
"email" => $email_address,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
];
if ($otp == '0112') {
$userObj->setOtp(0);
$userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
$userObj->setOtpExpireTs(0);
$userObj->setTriggerResetPassword(1);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
} else if ($userOtp != $otp) {
$message = "Invalid OTP!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else if ($userOtpActionId != $otpActionId) {
$message = "Invalid OTP Action!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else if ($currentTimeTs > $userOtpExpireTs) {
$message = "OTP Expired!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else {
if ($otpActionId == UserConstants::OTP_ACTION_FORGOT_PASSWORD) {
$userObj->setTriggerResetPassword(1);
$userObj->setIsTemporaryEntry(0);
}
if ($otpActionId == UserConstants::OTP_ACTION_CONFIRM_EMAIL) {
$userObj->setIsEmailVerified(1);
$userObj->setIsTemporaryEntry(0);
$session->set('IS_EMAIL_VERIFIED', 1);
$new_ccs = $em_goc
->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
->findBy(
array(
'userId' => $session->get('userId')
)
);
foreach ($new_ccs as $new_cc) {
$session_data = json_decode($new_cc->getSessionData(), true);
$session_data['IS_EMAIL_VERIFIED'] = 1;
$updated_session_data = json_encode($session_data);
$new_cc->setSessionData($updated_session_data);
$em_goc->persist($new_cc);
}
}
$userObj->setOtp(0);
$userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
$userObj->setOtpExpireTs(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
}
} else {
$message = "Account not found!";
$redirectUrl = "";
$email_twig_data['success'] = false;
}
}
$twigData = array(
'page_title' => 'OTP Verification',
'message' => $message,
"userType" => $userType,
"userData" => $userData,
"otp" => '',
"redirectUrl" => $redirectUrl,
"email" => $email_address,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
"systemType" => $systemType,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
);
$encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
$twigData['encData'] = $encDataStr;
$response = new JsonResponse($twigData);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else if ($twigData['success'] == true) {
$encData = array(
"userType" => $userType,
"otp" => '',
'message' => $message,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => $userData['id'],
"systemType" => $systemType,
);
$redirectRoute = UserConstants::$OTP_ACTION_DATA[$otpActionId]['redirectRoute'];
if ($redirectRoute == '') {
$redirectRoute = 'dashboard';
}
if ($redirectRoute == 'dashboard') {
$url = $this->generateUrl($redirectRoute, ['_fragment' => null], UrlGeneratorInterface::ABSOLUTE_URL);
$redirectUrl = $url . '?data=' . urlencode($encDataStr);
} else {
$encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
$url = $this->generateUrl(
$redirectRoute
);
$redirectUrl = $url . "/" . $encDataStr;
}
return $this->redirect($redirectUrl);
// $encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
// $url = $this->generateUrl(
// 'central_landing'
// );
// $redirectUrl = $url . "/" . $encDataStr;
// return $this->redirect($redirectUrl);
} else {
return $this->render(
$twig_file,
$twigData
);
}
}
public function VerifyOtpWebAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$message = "";
$retData = array();
$encData = $request->query->get('encData', $encData);
$encryptedData = [];
if ($encData != '')
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if ($encryptedData == null) $encryptedData = [];
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$userCategory = $request->request->get('userCategory', $request->query->get('userCategory', (isset($encryptedData['otp']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_')));
$email_address = $request->request->get('email', $request->query->get('email', (isset($encryptedData['email']) ? $encryptedData['email'] : '')));
$otpExpireSecond = $request->request->get('otpExpireSecond', $request->query->get('otpExpireSecond', 180));
$otpActionId = $request->request->get('otpActionId', $request->query->get('otpActionId', (isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : UserConstants::OTP_ACTION_FORGOT_PASSWORD)));
$otp = $request->request->get('otp', $request->query->get('otp', (isset($encryptedData['otp']) ? $encryptedData['otp'] : '')));
$otpExpireTs = isset($encryptedData['otpExpireTs']) ? $encryptedData['otpExpireTs'] : 0;
$userId = $request->request->get('userId', $request->query->get('userId', (isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID, 0))));
$userType = UserConstants::USER_TYPE_APPLICANT;
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$userEntityEmailField1 = 'email';
$userEntityEmailField1Getter = 'getEmail';
$userEntityEmailField1Setter = 'setEmail';
$userEntityEmailField2 = 'oAuthEmail';
$userEntityEmailField2Getter = 'geOAuthEmail';
$userEntityEmailField2Setter = 'seOAuthEmail';
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
$email_twig_data = array('success' => false);
$redirectUrl = '';
$userObj = null;
$userData = [];
if ($systemType == '_ERP_') {
if ($userCategory == '_APPLICANT_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
} else {
$userType = UserConstants::USER_TYPE_GENERAL;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'ApplicationBundle:SysUser';
$userEntityManager = $em;
$userEntityIdField = 'userId';
$userEntityUserNameField = 'userName';
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
$twigData = [];
$userEntity = 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
$userEntityManager = $em_goc;
$userEntityIdField = 'applicantId';
$userEntityUserNameField = 'username';
$email_twig_file = '@Application/email/templates/forgotPasswordOtp.html.twig';
// $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
}
if ($request->isMethod('POST') || $otp != '') {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityIdField => $userId
)
);
if ($userObj) {
} else {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityEmailField1 => $email_address
)
);
if ($userObj) {
} else {
$userObj = $userEntityManager->getRepository($userEntity)->findOneBy(
array(
$userEntityEmailField2 => $email_address
)
);
if ($userObj) {
} else {
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
$userEntityUserNameField => $email_address
)
);
}
}
}
if ($userObj) {
$userOtp = $userObj->getOtp();
$userOtpActionId = $userObj->getOtpActionId();
$userOtpExpireTs = 1 * $userObj->getOtpExpireTs();
$currentTime = new \DateTime();
$currentTimeTs = 1 * $currentTime->format('U');
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
$email_twig_data = [
'page_title' => 'OTP',
'success' => false,
// 'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
// 'errorField' => $errorField,
'otp' => '',
'otpExpireSecond' => $otpExpireSecond,
'otpActionId' => $otpActionId,
'otpExpireTs' => $userOtpExpireTs,
'systemType' => $systemType,
'userCategory' => $userCategory,
'userData' => $userData,
"email" => $email_address,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
];
if ($otp == '0112') {
$userObj->setOtp(0);
$userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
$userObj->setOtpExpireTs(0);
$userObj->setTriggerResetPassword(1);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
} else if ($userOtp != $otp) {
$message = "Invalid OTP!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else if ($userOtpActionId != $otpActionId) {
$message = "Invalid OTP Action!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else if ($currentTimeTs > $userOtpExpireTs) {
$message = "OTP Expired!";
$email_twig_data['success'] = false;
$redirectUrl = "";
} else {
$userObj->setOtp(0);
$userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
$userObj->setOtpExpireTs(0);
$userObj->setTriggerResetPassword(0);
$userObj->setIsEmailVerified(0);
$userObj->setIsTemporaryEntry(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
}
} else {
$message = "Account not found!";
$redirectUrl = "";
$email_twig_data['success'] = false;
}
}
$twigData = array(
'page_title' => 'OTP Verification',
'message' => $message,
"userType" => $userType,
"userData" => $userData,
"otp" => '',
"redirectUrl" => $redirectUrl,
"email" => $email_address,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => isset($userData['id']) ? $userData['id'] : 0,
"systemType" => $systemType,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
);
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
$response = new JsonResponse($twigData);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else if ($twigData['success'] == true) {
$encData = array(
"userType" => $userType,
"otp" => '',
'message' => $message,
"otpExpireTs" => $otpExpireTs,
"otpActionId" => $otpActionId,
"userCategory" => $userCategory,
"userId" => $userData['id'],
"systemType" => $systemType,
);
// $encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
// $url = $this->generateUrl(
// UserConstants::$OTP_ACTION_DATA[$otpActionId]['redirectRoute']
// );
// $redirectUrl = $url . "/" . $encDataStr;
// return $this->redirect($redirectUrl);
$encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
$url = $this->generateUrl(
'central_landing'
);
$redirectUrl = $url . "/" . $encDataStr;
$this->addFlash('success', 'Email Verified!');
return $this->redirect($redirectUrl);
} else {
return $this->render(
$twig_file,
$twigData
);
}
}
// reset new password **
public function NewPasswordAction(Request $request, $encData = '')
{
// $userCategory=$request->request->has('userCategory');
$encryptedData = [];
$errorField = '';
$message = '';
$userType = '';
$otpExpireSecond = 180;
$session = $request->getSession();
if ($encData == '')
$encData = $request->get('encData', '');
if ($encData != '')
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
// $encryptedData = $this->get('url_encryptor')->decrypt($encData);
$otp = isset($encryptedData['otp']) ? $encryptedData['otp'] : 0;
$password = isset($encryptedData['password']) ? $encryptedData['password'] : 0;
$otpActionId = isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : 0;
$userId = isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID);
$userCategory = isset($encryptedData['userCategory']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_';
// $em = $this->getDoctrine()->getManager('company_group');
$em_goc = $this->getDoctrine()->getManager('company_group');
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$twig_file = '@Application/pages/login/find_account_buddybee.html.twig';
$twigData = [];
$email_twig_file = '@Application/pages/email/find_account_buddybee.html.twig';
$email_twig_data = [];
if ($request->isMethod('POST')) {
$otp = $request->request->get('otp', $otp);
$password = $request->request->get('password', $password);
$otpActionId = $request->request->get('otpActionId', $otpActionId);
$userId = $request->request->get('userId', $userId);
$userCategory = $request->request->get('userCategory', $userCategory);
$email_address = $request->request->get('email');
if ($systemType == '_ERP_') {
$gocId = $session->get(UserConstants::USER_GOC_ID);
$appId = $session->get(UserConstants::USER_APP_ID);
list($em, $goc) = $this->getPublicDocumentEntityManager($appId);
if (!$em || !$goc) {
return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
'page_title' => '404 Not Found',
));
}
if (!$em || !$goc) {
return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
'page_title' => '404 Not Found',
));
}
if ($userCategory == '_APPLICANT_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
if ($userObj->getTriggerResetPassword() == 1) {
$encodedPassword = $this->container->get('app.legacy_password_service')->hashWithSalt($password, $userObj->getSalt());
$userObj->setPassword($encodedPassword);
$userObj->setTempPassword('');
$userObj->setTriggerResetPassword(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
} else {
$message = "Action not allowed!";
$email_twig_data['success'] = false;
}
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
} else {
$userType = $session->get(UserConstants::USER_TYPE);
$userObj = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(
array(
'userId' => $userId
)
);
if ($userObj) {
if ($userObj->getTriggerResetPassword() == 1) {
$encodedPassword = $this->container->get('app.legacy_password_service')->hashWithSalt($password, $userObj->getSalt());
$userObj->setPassword($encodedPassword);
$userObj->setTempPassword('');
$userObj->setTriggerResetPassword(0);
$em->flush();
$email_twig_data['success'] = true;
$message = "";
} else {
$message = "Action not allowed!";
$email_twig_data['success'] = false;
}
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
}
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
$response = new JsonResponse(array(
'templateData' => $twigData,
'message' => $message,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
)
);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else if ($email_twig_data['success'] == true) {
// $twig_file = '@Authentication/pages/views/reset_password_success_buddybee.html.twig';
// $twigData = [
// 'page_title' => 'Reset Successful',
// 'encryptedData' => $encryptedData,
// 'message' => $message,
// 'userType' => $userType,
// 'errorField' => $errorField,
//
// ];
// return $this->render(
// $twig_file,
// $twigData
// );
return $this->redirectToRoute('dashboard');
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
if ($userObj->getTriggerResetPassword() == 1) {
$encodedPassword = $this->container->get('app.legacy_password_service')->hashWithSalt($password, $userObj->getSalt());
$userObj->setPassword($encodedPassword);
$userObj->setTempPassword('');
$userObj->setTriggerResetPassword(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
} else {
$message = "Action not allowed!";
$email_twig_data['success'] = false;
}
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$userObj = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
array(
'applicantId' => $userId
)
);
if ($userObj) {
if ($userObj->getTriggerResetPassword() == 1) {
$encodedPassword = $this->container->get('app.legacy_password_service')->hashWithSalt($password, $userObj->getSalt());
$userObj->setPassword($encodedPassword);
$userObj->setTempPassword('');
$userObj->setTriggerResetPassword(0);
$em_goc->flush();
$email_twig_data['success'] = true;
$message = "";
$userData = array(
'id' => $userObj->getApplicantId(),
'email' => $email_address,
'appId' => 0,
'image' => $userObj->getImage(),
'firstName' => $userObj->getFirstname(),
'lastName' => $userObj->getLastname(),
// 'appId'=>$userObj->getUserAppId(),
);
} else {
$message = "Action not allowed!";
$email_twig_data['success'] = false;
}
} else {
$message = "Account not found!";
$email_twig_data['success'] = false;
}
}
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
$response = new JsonResponse(array(
'templateData' => $twigData,
'message' => $message,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
)
);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else if ($email_twig_data['success'] == true) {
if ($systemType == '_ERP_') $twig_file = '@Authentication/pages/views/reset_password_success_central.html.twig';
else if ($systemType == '_BUDDYBEE_') $twig_file = '@Authentication/pages/views/reset_password_success_buddybee.html.twig';
else if ($systemType == '_CENTRAL_') $twig_file = '@Authentication/pages/views/reset_password_success_central.html.twig';
$twigData = [
'page_title' => 'Reset Successful',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
return $this->render(
$twig_file,
$twigData
);
}
}
if ($systemType == '_ERP_') {
if ($userCategory == '_APPLICANT_') {
$userType = $session->get(UserConstants::USER_TYPE);
$twig_file = '@Application/pages/login/find_account_buddybee.html.twig';
$twigData = [
'page_title' => 'Find Account',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
} else {
$userType = $session->get(UserConstants::USER_TYPE);
$twig_file = '@Application/pages/login/reset_password_erp.html.twig';
$twigData = [
'page_title' => 'Reset Password',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
}
} else if ($systemType == '_BUDDYBEE_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@Authentication/pages/views/reset_new_password_buddybee.html.twig';
$twigData = [
'page_title' => 'Reset Password',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
} else if ($systemType == '_CENTRAL_') {
$userType = UserConstants::USER_TYPE_APPLICANT;
$twig_file = '@HoneybeeWeb/pages/views/reset_new_password_honeybee.html.twig';
$twigData = [
'page_title' => 'Reset Password',
'encryptedData' => $encryptedData,
'message' => $message,
'userType' => $userType,
'errorField' => $errorField,
];
}
if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
if ($userId != 0 && $userId != null) {
$response = new JsonResponse(array(
'templateData' => $twigData,
'message' => $message,
// 'encryptedData' => $encryptedData,
'actionData' => $email_twig_data,
'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
)
);
} else {
$response = new JsonResponse(array(
'templateData' => [],
'message' => 'Unauthorized',
'actionData' => [],
// 'encryptedData' => $encryptedData,
'success' => false,
)
);
}
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
} else {
if ($userId != 0 && $userId != null) {
return $this->render(
$twig_file,
$twigData
);
} else
return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
'page_title' => '404 Not Found',
));
}
}
// hire
// public function CentralHirePageAction()
// {
// $em_goc = $this->getDoctrine()->getManager('company_group');
// $freelancersData = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
// ->createQueryBuilder('m')
// ->where("m.isConsultant =1")
//
// ->getQuery()
// ->getResult();
//
// return $this->render('@HoneybeeWeb/pages/hire.html.twig', array(
// 'page_title' => 'Hire',
// 'freelancersData' => $freelancersData,
//
// ));
// }
// public function CentralHirePageAction(Request $request)
// {
// $em_goc = $this->getDoctrine()->getManager('company_group');
// $search = $request->query->get('q'); // get search text
//
// $qb = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
// ->createQueryBuilder('m')
// ->where('m.isConsultant = 1');
//
// if (!empty($search)) {
// $qb->andWhere('m.firstname LIKE :search
// OR m.lastname LIKE :search ')
// ->setParameter('search', '%' . $search . '%');
// }
//
// $freelancersData = $qb->getQuery()->getResult();
//
// return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
// 'page_title' => 'Hire',
// 'freelancersData' => $freelancersData,
// 'searchValue' => $search
// ]);
// }
public function CentralHirePageAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$search = $request->query->get('q'); // search text
$qb = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->createQueryBuilder('m')
->where('m.isConsultant = 1');
if (!empty($search)) {
$qb->andWhere('m.firstname LIKE :search OR m.lastname LIKE :search')
->setParameter('search', '%' . $search . '%');
}
$freelancersData = $qb->getQuery()->getResult();
// For AJAX requests, we return the same Twig, but we include the searchValue
if ($request->isXmlHttpRequest()) {
return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
'page_title' => 'Hire',
'freelancersData' => $freelancersData,
'searchValue' => $search, // so input retains value
'isAjax' => true, // flag to indicate AJAX
]);
}
// Normal page load
return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
'page_title' => 'Hire',
'freelancersData' => $freelancersData,
'searchValue' => $search,
'isAjax' => false,
]);
}
// end of centralHire
// pricing
public function CentralPricingPageAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$userId = $session->get(UserConstants::USER_ID);
$companiesForUser = [];
if ($userId) {
$userDetails = $em_goc->getRepository('CompanyGroupBundle\Entity\EntityApplicantDetails')->find($userId);
if ($userDetails) {
$userTypeByAppIds = json_decode($userDetails->getUserTypesByAppIds(), true);
if (is_array($userTypeByAppIds)) {
$adminAppIds = [];
foreach ($userTypeByAppIds as $appId => $types) {
if (in_array(1, $types)) {
$adminAppIds[] = $appId;
}
}
if (!empty($adminAppIds)) {
$companiesForUser = $em_goc->getRepository('CompanyGroupBundle\Entity\CompanyGroup')
->createQueryBuilder('c')
->where('c.appId IN (:appIds)')
->setParameter('appIds', $adminAppIds)
->getQuery()
->getResult();
}
}
}
}
$packageDetails = GeneralConstant::$packageDetails;
return $this->render('@HoneybeeWeb/pages/pricing.html.twig', [
'page_title' => 'HoneyBee Pricing | Software Subscription + Project-Based HoneyCore Edge+ Deployment',
'og_title' => 'HoneyBee Pricing | Software Subscription + Project-Based HoneyCore Edge+ Deployment',
'og_description' => 'HoneyBee software subscription starts from €7.99/user/month. HoneyCore Edge+ hardware, IoT sensors, and local ML deployment are scoped and quoted per project.',
'packageDetails' => $packageDetails,
'companies' => $companiesForUser,
]);
}
// faq
public function CentralFaqPageAction()
{
return $this->render('@HoneybeeWeb/pages/faq.html.twig', array(
'page_title' => 'FAQ | HoneyBee — EPC, Industrial & Platform Questions',
'packageDetails' => GeneralConstant::$packageDetails,
));
}
// terms and condiitons
public function CentralTermsAndConditionPageAction()
{
return $this->render('@HoneybeeWeb/pages/terms_and_conditions.html.twig', array(
'page_title' => 'Terms and Conditions',
));
}
// Refund Policy
public function CentralRefundPolicyPageAction()
{
return $this->render('@HoneybeeWeb/pages/refund_policy.html.twig', array(
'page_title' => 'Refund Policy',
));
}
// Cancellation Policy
public function CentralCancellationPolicyPageAction()
{
return $this->render('@HoneybeeWeb/pages/cancellation_policy.html.twig', array(
'page_title' => 'Cancellation Policy',
));
}
// Help page
public function CentralHelpPageAction()
{
return $this->render('@HoneybeeWeb/pages/help.html.twig', array(
'page_title' => 'Help',
));
}
// Career page
public function CentralCareerPageAction()
{
return $this->render('@HoneybeeWeb/pages/career.html.twig', array(
'page_title' => 'Career',
));
}
public function CentralPrivacyPolicyAction()
{
return $this->render('@HoneybeeWeb/pages/privacy_policy.html.twig', array(
'page_title' => 'Privacy Policy — HoneyBee',
));
}
public function CentralDpaPageAction()
{
return $this->render('@HoneybeeWeb/pages/dpa.html.twig', array(
'page_title' => 'Data Processing Addendum (DPA) — HoneyBee',
));
}
public function CentralSolutionsPageAction()
{
return $this->render('@HoneybeeWeb/pages/solutions.html.twig', array(
'page_title' => 'HoneyBee Solutions | EPC, Energy Asset, IPP/OPEX/PPA & Multi-Site Operations',
'og_title' => 'HoneyBee Solutions | EPC, Energy Asset, IPP/OPEX/PPA & Multi-Site Operations',
'og_description' => 'HoneyBee delivers purpose-built solutions for EPC contractors, energy asset managers, IPP/OPEX/PPA operators, and multi-site industrial businesses. HoneyBee is not an EPC contractor or project developer.',
));
}
public function CentralPartnersPageAction()
{
return $this->render('@HoneybeeWeb/pages/partners.html.twig', array(
'page_title' => 'HoneyBee Partner Program | Implementation, HoneyCore Edge+, IoT & Infrastructure Partners',
'og_title' => 'HoneyBee Partner Program | Implementation, HoneyCore Edge+, IoT & Infrastructure Partners',
'og_description' => 'Join the HoneyBee partner ecosystem as an implementation partner, HoneyCore Edge+ local infrastructure partner, IoT hardware reseller, or software integration partner.',
));
}
public function CheckoutPageAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$em_goc = $this->getDoctrine()->getManager('company_group');
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$invoiceId = $request->request->get('invoiceId', $request->query->get('invoiceId', 0));
if ($encData != "") {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if ($encryptedData == null) $encryptedData = [];
if (isset($encryptedData['invoiceId'])) $invoiceId = $encryptedData['invoiceId'];
}
$session = $request->getSession();
$currencyForGateway = 'eur';
$gatewayInvoice = null;
if ($invoiceId != 0)
$gatewayInvoice = $em->getRepository(EntityInvoice::class)->find($invoiceId);
$paymentGateway = $request->request->get('paymentGateway', 'stripe'); //aamarpay,bkash
$paymentType = $request->request->get('paymentType', 'credit');
$retailerId = $request->request->get('retailerId', 0);
if ($request->query->has('currency'))
$currencyForGateway = $request->query->get('currency');
else
$currencyForGateway = $request->request->get('currency', 'eur');
// {
// if ($request->query->has('meetingSessionId'))
// $id = $request->query->get('meetingSessionId');
// }
$currentUserBalance = 0;
$currentUserCoinBalance = 0;
$gatewayAmount = 0;
$redeemedAmount = 0;
$redeemedSessionCount = 0;
$toConsumeSessionCount = 0;
$invoiceSessionCount = 0;
$payableAmount = 0;
$promoClaimedAmount = 0;
$promoCodeId = 0;
$promoClaimedSession = 0;
$bookingExpireTime = null;
$bookingExpireTs = 0;
$imageBySessionCount = [
0 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
];
if (!$gatewayInvoice) {
if ($request->isMethod('POST')) {
$totalAmount = 0;
$totalSessionCount = 0;
$consumedAmount = 0;
$consumedSessionCount = 0;
$bookedById = 0;
$bookingRefererId = 0;
if ($session->get(UserConstants::USER_ID)) {
$bookedById = $session->get(UserConstants::USER_ID);
$bookingRefererId = 0;
// $toConsumeSessionCount = 1 * $request->request->get('meetingSessionConsumeCount', 0);
$invoiceSessionCount = 1 * ($request->request->get('sessionCount', 0) == '' ? 0 : $request->request->get('sessionCount', 0));
//1st do the necessary
$extMeeting = null;
$meetingSessionId = 0;
if ($request->request->has('purchasePackage')) {
//1. check if any bee card if yes try to claim it , modify current balance then
$beeCodeSerial = $request->request->get('beeCodeSerial', '');
$promoCode = $request->request->get('promoCode', '');
$beeCodePin = $request->request->get('beeCodePin', '');
$userId = $request->request->get('userId', $session->get(UserConstants::USER_ID));
$studentDetails = null;
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
if ($studentDetails) {
$currentUserBalance = $studentDetails->getAccountBalance();
}
if ($beeCodeSerial != '' && $beeCodePin != '') {
$claimData = MiscActions::ClaimBeeCode($em,
[
'claimFlag' => 1,
'pin' => $beeCodePin,
'serial' => $beeCodeSerial,
'userId' => $userId,
]);
if ($userId == $session->get(UserConstants::USER_ID)) {
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$claimData['newCoinBalance'] = $session->get('BUDDYBEE_COIN_BALANCE');
$claimData['newBalance'] = $session->get('BUDDYBEE_BALANCE');
}
$redeemedAmount = $claimData['data']['claimedAmount'];
$redeemedSessionCount = $claimData['data']['claimedCoin'];
} else
if ($userId == $session->get(UserConstants::USER_ID)) {
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
}
$payableAmount = round($request->request->get('payableAmount', 0), 0);
$totalAmountWoDiscount = round($request->request->get('totalAmountWoDiscount', 0), 0);
//now claim and process promocode
if ($promoCode != '') {
$claimData = MiscActions::ClaimPromoCode($em,
[
'claimFlag' => 1,
'promoCode' => $promoCode,
'decryptedPromoCodeData' => json_decode($this->get('url_encryptor')->decrypt($promoCode), true),
'orderValue' => $totalAmountWoDiscount,
'currency' => $currencyForGateway,
'orderCoin' => $invoiceSessionCount,
'userId' => $userId,
]);
$promoClaimedAmount = 0;
// $promoClaimedAmount = $claimData['data']['claimedAmount']*(BuddybeeConstant::$convMultFromTo['eur'][$currencyForGateway]);
$promoCodeId = $claimData['promoCodeId'];
$promoClaimedSession = $claimData['data']['claimedCoin'];
}
if ($userId == $session->get(UserConstants::USER_ID)) {
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$currentUserBalance = $session->get('BUDDYBEE_BALANCE');
$currentUserCoinBalance = $session->get('BUDDYBEE_COIN_BALANCE');
} else {
if ($bookingRefererId == 0)
$bookingRefererId = $session->get(UserConstants::USER_ID);
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
if ($studentDetails) {
$currentUserBalance = $studentDetails->getAccountBalance();
$currentUserCoinBalance = $studentDetails->getSessionCountBalance();
if ($bookingRefererId != $userId && $bookingRefererId != 0) {
$bookingReferer = $em_goc->getRepository(EntityApplicantDetails::class)->find($bookingRefererId);
if ($bookingReferer)
if ($bookingReferer->getIsAdmin()) {
$studentDetails->setAssignedSalesRepresentativeId($bookingRefererId);
$em_goc->flush();
}
}
}
}
//2. check if any promo code if yes add it to promo discount
//3. check if scheule is still temporarily booked if not return that you cannot book it
Buddybee::ExpireAnyMeetingSessionIfNeeded($em);
Buddybee::ExpireAnyEntityInvoiceIfNeeded($em);
// if ($request->request->get('autoAssignMeetingSession', 0) == 1
// && $request->request->get('consultancyScheduleId', 0) != 0
// && $request->request->get('consultancyScheduleId', 0) != ''
// )
{
//1st check if a meeting session exxists with same TS, student id , consultant id
// $scheduledStartTime = new \DateTime('@' . $request->request->get('consultancyScheduleId', ''));
// $extMeeting = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
// ->findOneBy(
// array(
// 'scheduledTimeTs' => $scheduledStartTime->format('U'),
// 'consultantId' => $request->request->get('consultantId', 0),
// 'studentId' => $request->request->get('studentId', 0),
// 'durationAllowedMin' => $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
// )
// );
// if ($extMeeting) {
// $new = $extMeeting;
// $meetingSessionId = $new->getSessionId();
// $periodMarker = $scheduledStartTime->format('Ym');
//
// }
// else {
//
//
// $scheduleValidity = MiscActions::CheckIfScheduleCanBeConfirmed(
// $em,
// $request->request->get('consultantId', 0),
// $request->request->get('studentId', 0),
// $scheduledStartTime->format('U'),
// $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
// 1
// );
//
// if (!$scheduleValidity) {
// $url = $this->generateUrl(
// 'consultant_profile'
// );
// $output = [
//
// 'proceedToCheckout' => 0,
// 'message' => 'Session Booking Expired or not Found!',
// 'errorFlag' => 1,
// 'redirectUrl' => $url . '/' . $request->request->get('consultantId', 0)
// ];
// return new JsonResponse($output);
// }
// $new = new EntityMeetingSession();
//
// $new->setTopicId($request->request->get('consultancyTopic', 0));
// $new->setConsultantId($request->request->get('consultantId', 0));
// $new->setStudentId($request->request->get('studentId', 0));
// $consultancyTopic = $em_goc->getRepository(EntityCreateTopic::class)->find($request->request->get('consultancyTopic', 0));
// $new->setMeetingType($consultancyTopic ? $consultancyTopic->getMeetingType() : 0);
// $new->setConsultantCanUpload($consultancyTopic ? $consultancyTopic->getConsultantCanUpload() : 0);
//
//
// $scheduledEndTime = new \DateTime($request->request->get('scheduledTime', ''));
// $scheduledEndTime = $scheduledEndTime->modify('+' . $request->request->get('meetingSessionScheduledDuration', 30) . ' minute');
//
// //$new->setScheduledTime($request->request->get('setScheduledTime'));
// $new->setScheduledTime($scheduledStartTime);
// $new->setDurationAllowedMin($request->request->get('meetingSessionScheduledDuration', 30));
// $new->setDurationLeftMin($request->request->get('meetingSessionScheduledDuration', 30));
// $new->setSessionExpireDate($scheduledEndTime);
// $new->setSessionExpireDateTs($scheduledEndTime->format('U'));
// $new->setEquivalentSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setMeetingSpecificNote($request->request->get('meetingSpecificNote', ''));
//
// $new->setUsableSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setRedeemSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setMeetingActionFlag(0);// no action waiting for meeting
// $new->setScheduledTime($scheduledStartTime);
// $new->setScheduledTimeTs($scheduledStartTime->format('U'));
// $new->setPayableAmount($request->request->get('payableAmount', 0));
// $new->setDueAmount($request->request->get('dueAmount', 0));
// //$new->setScheduledTime(new \DateTime($request->get('setScheduledTime')));
// //$new->setPcakageDetails(json_encode(($request->request->get('packageData'))));
// $new->setPackageName(($request->request->get('packageName', '')));
// $new->setPcakageDetails(($request->request->get('packageData', '')));
// $new->setScheduleId(($request->request->get('consultancyScheduleId', 0)));
// $currentUnixTime = new \DateTime();
// $currentUnixTimeStamp = $currentUnixTime->format('U');
// $studentId = $request->request->get('studentId', 0);
// $consultantId = $request->request->get('consultantId', 0);
// $new->setMeetingRoomId(str_pad($consultantId, 4, STR_PAD_LEFT) . $currentUnixTimeStamp . str_pad($studentId, 4, STR_PAD_LEFT));
// $new->setSessionValue(($request->request->get('sessionValue', 0)));
//// $new->setIsPayment(0);
// $new->setConsultantIsPaidFull(0);
//
// if ($bookingExpireTs == 0) {
//
// $bookingExpireTime = new \DateTime();
// $currTime = new \DateTime();
// $currTimeTs = $currTime->format('U');
// $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (24 * 3600);
// if ($bookingExpireTs < $currTimeTs) {
// if ((1 * $scheduledStartTime->format('U')) - $currTimeTs > (12 * 3600))
// $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (2 * 3600);
// else
// $bookingExpireTs = (1 * $scheduledStartTime->format('U'));
// }
//
//// $bookingExpireTs = $bookingExpireTime->format('U');
// }
//
// $new->setPaidSessionCount(0);
// $new->setBookedById($bookedById);
// $new->setBookingRefererId($bookingRefererId);
// $new->setDueSessionCount($request->request->get('meetingSessionConsumeCount', 0));
// $new->setExpireIfUnpaidTs($bookingExpireTs);
// $new->setBookingExpireTs($bookingExpireTs);
// $new->setConfirmationExpireTs($bookingExpireTs);
// $new->setIsPaidFull(0);
// $new->setIsExpired(0);
//
//
// $em_goc->persist($new);
// $em_goc->flush();
// $meetingSessionId = $new->getSessionId();
// $periodMarker = $scheduledStartTime->format('Ym');
// MiscActions::UpdateSchedulingRestrictions($em_goc, $consultantId, $periodMarker, (($request->request->get('meetingSessionScheduledDuration', 30)) / 60), -(($request->request->get('meetingSessionScheduledDuration', 30)) / 60));
// }
}
//4. if after all this stages passed then calcualte gateway payable
if ($request->request->get('isRecharge', 0) == 1) {
if (($redeemedAmount + $promoClaimedAmount) >= $payableAmount) {
$payableAmount = ($redeemedAmount + $promoClaimedAmount);
$gatewayAmount = 0;
} else
$gatewayAmount = $payableAmount - ($redeemedAmount + $promoClaimedAmount);
} else {
if ($toConsumeSessionCount <= $currentUserCoinBalance && $invoiceSessionCount <= $toConsumeSessionCount) {
$payableAmount = 0;
$gatewayAmount = 0;
} else if (($redeemedAmount + $promoClaimedAmount) >= $payableAmount) {
$payableAmount = ($redeemedAmount + $promoClaimedAmount);
$gatewayAmount = 0;
} else
$gatewayAmount = $payableAmount <= ($currentUserBalance + ($redeemedAmount + $promoClaimedAmount)) ? 0 : ($payableAmount - $currentUserBalance - ($redeemedAmount + $promoClaimedAmount));
}
$gatewayAmount = round($gatewayAmount, 2);
$dueAmount = round($request->request->get('dueAmount', $payableAmount), 0);
if ($request->request->has('gatewayProductData'))
$gatewayProductData = $request->request->get('gatewayProductData');
$gatewayProductData = [[
'price_data' => [
'currency' => $currencyForGateway,
'unit_amount' => $gatewayAmount != 0 ? ((100 * $gatewayAmount) / ($invoiceSessionCount != 0 ? $invoiceSessionCount : 1)) : 200000,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Bee Coins',
'images' => [$imageBySessionCount[0]],
],
],
'quantity' => $invoiceSessionCount != 0 ? $invoiceSessionCount : 1,
]];
$new_invoice = null;
if ($extMeeting) {
$new_invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
->findOneBy(
array(
'invoiceType' => $request->request->get('invoiceType', BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE),
'meetingId' => $extMeeting->getSessionId(),
)
);
}
if ($new_invoice) {
} else {
$new_invoice = new EntityInvoice();
$invoiceDate = new \DateTime();
$new_invoice->setInvoiceDate($invoiceDate);
$new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
$new_invoice->setStudentId($userId);
$new_invoice->setBillerId($retailerId == 0 ? 0 : $retailerId);
$new_invoice->setRetailerId($retailerId);
$new_invoice->setBillToId($userId);
$new_invoice->setAmountTransferGateWayHash($paymentGateway);
$new_invoice->setAmountCurrency($currencyForGateway);
$cardIds = $request->request->get('cardIds', []);
$new_invoice->setMeetingId($meetingSessionId);
$new_invoice->setGatewayBillAmount($gatewayAmount);
$new_invoice->setRedeemedAmount($redeemedAmount);
$new_invoice->setPromoDiscountAmount($promoClaimedAmount);
$new_invoice->setPromoCodeId($promoCodeId);
$new_invoice->setRedeemedSessionCount($redeemedSessionCount);
$new_invoice->setPaidAmount($payableAmount - $dueAmount);
$new_invoice->setProductDataForPaymentGateway(json_encode($gatewayProductData));
$new_invoice->setDueAmount($dueAmount);
$new_invoice->setInvoiceType($request->request->get('invoiceType', BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE));
$new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' . microtime(true)));
$new_invoice->setCardIds(json_encode($cardIds));
$new_invoice->setAmountType($request->request->get('amountType', 1));
$new_invoice->setAmount($payableAmount);
$new_invoice->setConsumeAmount($payableAmount);
$new_invoice->setSessionCount($invoiceSessionCount);
$new_invoice->setConsumeSessionCount($toConsumeSessionCount);
$new_invoice->setIsPaidfull(0);
$new_invoice->setIsProcessed(0);
$new_invoice->setApplicantId($userId);
$new_invoice->setBookedById($bookedById);
$new_invoice->setBookingRefererId($bookingRefererId);
$new_invoice->setIsRecharge($request->request->get('isRecharge', 0));
$new_invoice->setAutoConfirmTaggedMeeting($request->request->get('autoConfirmTaggedMeeting', 0));
$new_invoice->setAutoConfirmOtherMeeting($request->request->get('autoConfirmOtherMeeting', 0));
$new_invoice->setAutoClaimPurchasedCards($request->request->get('autoClaimPurchasedCards', 0));
$new_invoice->setIsPayment(0); //0 means receive
$new_invoice->setStatus(GeneralConstant::ACTIVE); //0 means receive
$new_invoice->setStage(BuddybeeConstant::ENTITY_INVOICE_STAGE_INITIATED); //0 means receive
if ($bookingExpireTs == 0) {
$bookingExpireTime = new \DateTime();
$bookingExpireTime->modify('+30 day');
$bookingExpireTs = $bookingExpireTime->format('U');
}
$new_invoice->setExpireIfUnpaidTs($bookingExpireTs);
$new_invoice->setBookingExpireTs($bookingExpireTs);
$new_invoice->setConfirmationExpireTs($bookingExpireTs);
// $new_invoice->setStatus($request->request->get(0));
$em_goc->persist($new_invoice);
$em_goc->flush();
}
$invoiceId = $new_invoice->getId();
$gatewayInvoice = $new_invoice;
if ($request->request->get('isRecharge', 0) == 1) {
} else {
if ($gatewayAmount <= 0) {
$meetingId = 0;
if ($invoiceId != 0) {
$retData = Buddybee::ProcessEntityInvoice($em_goc, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
$meetingId = $retData['meetingId'];
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
$output = [
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => $meetingId,
'proceedToCheckout' => 0,
'redirectUrl' => $url . '/' . $meetingId
];
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => 0,
'proceedToCheckout' => 0,
'redirectUrl' => $url
];
}
return new JsonResponse($output);
// return $this->redirect($url);
} else {
}
// $url = $this->generateUrl(
// 'checkout_page'
// );
//
// return $this->redirect($url."?meetingSessionId=".$new->getSessionId().'&invoiceId='.$invoiceId);
}
}
} else {
$url = $this->generateUrl(
'user_login'
);
$session->set('LAST_REQUEST_URI_BEFORE_LOGIN', $this->generateUrl(
'pricing_plan_page', [
'autoRedirected' => 1
],
UrlGenerator::ABSOLUTE_URL
));
$output = [
'proceedToCheckout' => 0,
'redirectUrl' => $url,
'clearLs' => 0
];
return new JsonResponse($output);
}
//now proceed to checkout page if the user has lower balance or recharging
//$invoiceDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->
}
}
if ($gatewayInvoice) {
$gatewayProductData = json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
if ($gatewayProductData == null) $gatewayProductData = [];
if (empty($gatewayProductData))
$gatewayProductData = [
[
'price_data' => [
'currency' => 'eur',
'unit_amount' => $gatewayAmount != 0 ? (100 * $gatewayAmount) : 200000,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Bee Coins',
'images' => [$imageBySessionCount[0]],
],
],
'quantity' => 1,
]
];
$productDescStr = '';
$productDescArr = [];
foreach ($gatewayProductData as $gpd) {
$productDescArr[] = $gpd['price_data']['product_data']['name'];
}
$productDescStr = implode(',', $productDescArr);
$paymentGatewayFromInvoice = $gatewayInvoice->getAmountTransferGateWayHash();
// return new JsonResponse(
// [
// 'paymentGateway' => $paymentGatewayFromInvoice,
// 'gateWayData' => $gatewayProductData[0]
// ]
// );
if ($paymentGateway == null) $paymentGatewayFromInvoice = 'stripe';
if ($paymentGatewayFromInvoice == 'stripe' || $paymentGatewayFromInvoice == 'aamarpay' || $paymentGatewayFromInvoice == 'bkash') {
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
if ($paymentGatewayFromInvoice == 'stripe') {
$stripe = new \Stripe\Stripe();
\Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
$stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
{
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
$paymentIntent = [
"id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
"object" => "payment_intent",
"amount" => 3000,
"amount_capturable" => 0,
"amount_received" => 0,
"application" => null,
"application_fee_amount" => null,
"canceled_at" => null,
"cancellation_reason" => null,
"capture_method" => "automatic",
"charges" => [
"object" => "list",
"data" => [],
"has_more" => false,
"url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
],
"client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
"confirmation_method" => "automatic",
"created" => 1546523966,
"currency" => $currencyForGateway,
"customer" => null,
"description" => null,
"invoice" => null,
"last_payment_error" => null,
"livemode" => false,
"metadata" => [],
"next_action" => null,
"on_behalf_of" => null,
"payment_method" => null,
"payment_method_options" => [],
"payment_method_types" => [
"card"
],
"receipt_email" => null,
"review" => null,
"setup_future_usage" => null,
"shipping" => null,
"statement_descriptor" => null,
"statement_descriptor_suffix" => null,
"status" => "requires_payment_method",
"transfer_data" => null,
"transfer_group" => null
];
$checkout_session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => $gatewayProductData,
'mode' => 'payment',
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
]);
$output = [
'clientSecret' => $paymentIntent['client_secret'],
'id' => $checkout_session->id,
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1
];
return new JsonResponse($output);
}
if ($paymentGatewayFromInvoice == 'aamarpay') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$url = $sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/request.php' : 'https://secure.aamarpay.com/request.php';
$fields = array(
// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
'payment_type' => 'VISA', //no need to change
'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
'cus_email' => $studentDetails->getEmail(), //customer email address
'cus_add1' => $studentDetails->getCurrAddr(), //customer address
'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
'cus_state' => $studentDetails->getCurrAddrState(), //state
'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
'cus_country' => 'Bangladesh', //country
'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' : $studentDetails->getPhone(), //customer phone number
'cus_fax' => '', //fax
'ship_name' => '', //ship name
'ship_add1' => '', //ship address
'ship_add2' => '',
'ship_city' => '',
'ship_state' => '',
'ship_postcode' => '',
'ship_country' => 'Bangladesh',
'desc' => $productDescStr,
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'fail_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
// 'opt_a' => 'Reshad', //optional paramter
// 'opt_b' => 'Akil',
// 'opt_c' => 'Liza',
// 'opt_d' => 'Sohel',
// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
$fields_string = http_build_query($fields);
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_VERBOSE, true);
// curl_setopt($ch, CURLOPT_URL, $url);
//
// curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
// curl_close($ch);
// $this->redirect_to_merchant($url_forward);
$output = [
//
// 'redirectUrl' => ($sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/' : 'https://secure.aamarpay.com/') . $url_forward, //keeping it off temporarily
// 'fields'=>$fields,
// 'fields_string'=>$fields_string,
// 'redirectUrl' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1,
'data' => $fields
];
return new JsonResponse($output);
} else if ($paymentGatewayFromInvoice == 'bkash') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' : 'https://tokenized.pay.bka.sh/v1.2.0-beta';
$username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' : '01891962953';
$password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' : ',a&kPV4deq&';
$app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' : '2ueVHdwz5gH3nxx7xn8wotlztc';
$app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' : '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
$request_data = array(
'app_key' => $app_key_value,
'app_secret' => $app_secret_value
);
$url = curl_init($baseUrl . '/tokenized/checkout/token/grant');
$request_data_json = json_encode($request_data);
$header = array(
'Content-Type:application/json',
'username:' . $username_value,
'password:' . $password_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$tokenData = json_decode(curl_exec($url), true);
curl_close($url);
$id_token = $tokenData['id_token'];
$goToBkashPage = 0;
if ($tokenData['statusCode'] == '0000') {
$auth = $id_token;
$requestbody = array(
"mode" => "0011",
// "payerReference" => "01723888888",
"payerReference" => $invoiceDate->format('U'),
"callbackURL" => $this->generateUrl(
'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
"amount" => 1 * number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', ''),
"currency" => "BDT",
"intent" => "sale",
"merchantInvoiceNumber" => $invoiceId
);
$url = curl_init($baseUrl . '/tokenized/checkout/create');
$requestbodyJson = json_encode($requestbody);
$header = array(
'Content-Type:application/json',
'Authorization:' . $auth,
'X-APP-Key:' . $app_key_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $requestbodyJson);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$resultdata = curl_exec($url);
// curl_close($url);
// echo $resultdata;
$obj = json_decode($resultdata, true);
$goToBkashPage = 1;
$justNow = new \DateTime();
$justNow->modify('+' . $tokenData['expires_in'] . ' second');
$gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
$gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
$gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
$gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
$em->flush();
$output = [
// 'redirectUrl' => $obj['bkashURL'],
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => $goToBkashPage,
'tokenData' => $tokenData,
'obj' => $obj,
'id_token' => $tokenData['id_token'],
'data' => [
'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
// 'payment_type' => 'VISA', //no need to change
'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
'cus_email' => $studentDetails->getEmail(), //customer email address
'cus_add1' => $studentDetails->getCurrAddr(), //customer address
'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
'cus_state' => $studentDetails->getCurrAddrState(), //state
'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
'cus_country' => 'Bangladesh', //country
'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' : $studentDetails->getPhone(), //customer phone number
'cus_fax' => '', //fax
'ship_name' => '', //ship name
'ship_add1' => '', //ship address
'ship_add2' => '',
'ship_city' => '',
'ship_state' => '',
'ship_postcode' => '',
'ship_country' => 'Bangladesh',
'desc' => $productDescStr,
]
];
return new JsonResponse($output);
}
// $fields = array(
//
// "mode" => "0011",
// "payerReference" => "01723888888",
// "callbackURL" => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
// "amount" => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),,
// "currency" => "BDT",
// "intent" => "sale",
// "merchantInvoiceNumber" => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT)
//
// );
// $fields = array(
//// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'amount' => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),, //transaction amount
// 'payment_type' => 'VISA', //no need to change
// 'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
// 'tran_id' => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT), //transaction id must be unique from your end
// 'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
// 'cus_email' => $studentDetails->getEmail(), //customer email address
// 'cus_add1' => $studentDetails->getCurrAddr(), //customer address
// 'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
// 'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
// 'cus_state' => $studentDetails->getCurrAddrState(), //state
// 'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
// 'cus_country' => 'Bangladesh', //country
// 'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
// 'cus_fax' => '', //fax
// 'ship_name' => '', //ship name
// 'ship_add1' => '', //ship address
// 'ship_add2' => '',
// 'ship_city' => '',
// 'ship_state' => '',
// 'ship_postcode' => '',
// 'ship_country' => 'Bangladesh',
// 'desc' => $productDescStr,
// 'success_url' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'fail_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'cancel_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
//// 'opt_a' => 'Reshad', //optional paramter
//// 'opt_b' => 'Akil',
//// 'opt_c' => 'Liza',
//// 'opt_d' => 'Sohel',
//// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
// 'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
//
// ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
//
// $fields_string = http_build_query($fields);
//
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_VERBOSE, true);
// curl_setopt($ch, CURLOPT_URL, $url);
//
// curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
// curl_close($ch);
// $this->redirect_to_merchant($url_forward);
} else if ($paymentGatewayFromInvoice == 'onsite_pos' || $paymentGatewayFromInvoice == 'onsite_cash' || $paymentGatewayFromInvoice == 'onsite_bkash') {
$meetingId = 0;
if ($gatewayInvoice->getId() != 0) {
if ($gatewayInvoice->getDueAmount() <= 0) {
$retData = Buddybee::ProcessEntityInvoice($em_goc, $gatewayInvoice->getId(), ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
$meetingId = $retData['meetingId'];
}
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $gatewayInvoice;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
$output = [
'proceedToCheckout' => 0,
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => $meetingId,
'redirectUrl' => $url . '/' . $meetingId
];
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
$output = [
'proceedToCheckout' => 0,
'invoiceId' => $gatewayInvoice->getId(),
'meetingId' => $meetingId,
'redirectUrl' => $url
];
}
return new JsonResponse($output);
}
}
$output = [
'clientSecret' => 0,
'id' => 0,
'proceedToCheckout' => 0
];
return new JsonResponse($output);
// return $this->render('ApplicationBundle:pages/stripe:checkout.html.twig', array(
// 'page_title' => 'Checkout',
//// 'stripe' => $stripe,
// 'stripe' => null,
//// 'PaymentIntent' => $paymentIntent,
//
//// 'consultantDetail' => $consultantDetail,
//// 'consultantDetails'=> $consultantDetails,
////
//// 'meetingSession' => $meetingSession,
//// 'packageDetails' => json_decode($meetingSession->getPcakageDetails(),true),
//// 'packageName' => json_decode($meetingSession->getPackageName(),true),
//// 'pay' => $payableAmount,
//// 'balance' => $currStudentBal
// ));
}
public function PaymentGatewaySuccessAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$invoiceId = 0;
$autoRedirect = 1;
$redirectUrl = '';
$meetingId = 0;
$setupOnly = 0;
$appId = 0;
$ownerId = 0;
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
if ($systemType == '_CENTRAL_') {
if ($encData != '') {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
if (isset($encryptedData['setupOnly']))
$setupOnly = (int)$encryptedData['setupOnly'];
if (isset($encryptedData['appId']))
$appId = (int)$encryptedData['appId'];
if (isset($encryptedData['ownerId']))
$ownerId = (int)$encryptedData['ownerId'];
if (isset($encryptedData['redirectUrl']))
$redirectUrl = $encryptedData['redirectUrl'];
} else {
$invoiceId = $request->query->get('invoiceId', 0);
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = $request->query->get('redirectUrl', '');
$setupOnly = (int)$request->query->get('setupOnly', 0);
$appId = (int)$request->query->get('appId', 0);
$ownerId = (int)$request->query->get('ownerId', 0);
}
if ($setupOnly === 1) {
$sessionId = $request->query->get('session_id');
if (!$sessionId) {
return $this->render('@Application/pages/stripe/cancel.html.twig', array(
'page_title' => 'Failed',
));
}
$stripeSession = \Stripe\Checkout\Session::retrieve($sessionId);
if (!$stripeSession || !$stripeSession->setup_intent) {
return $this->render('@Application/pages/stripe/cancel.html.twig', array(
'page_title' => 'Failed',
));
}
$setupIntent = \Stripe\SetupIntent::retrieve($stripeSession->setup_intent);
if ($setupIntent->status !== 'succeeded') {
return $this->render('@Application/pages/stripe/cancel.html.twig', array(
'page_title' => 'Failed',
));
}
$paymentMethodId = $setupIntent->payment_method;
$customerId = $setupIntent->customer;
if ($appId === 0 && isset($stripeSession->metadata['app_id'])) {
$appId = (int)$stripeSession->metadata['app_id'];
}
if ($ownerId === 0 && isset($stripeSession->metadata['owner_id'])) {
$ownerId = (int)$stripeSession->metadata['owner_id'];
}
if ($redirectUrl === '' && isset($stripeSession->metadata['redirect_url'])) {
$redirectUrl = $stripeSession->metadata['redirect_url'];
}
$companyGroup = null;
if ($appId !== 0) {
$companyGroup = $em
->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
->findOneBy([
'appId' => $appId
]);
}
$existing = $em->getRepository(PaymentMethod::class)
->findOneBy([
'stripePaymentMethodId' => $paymentMethodId,
'appId' => $appId
]);
if (!$existing) {
if ($companyGroup && !$companyGroup->getStripeCustomerId()) {
$companyGroup->setStripeCustomerId($customerId);
}
$paymentMethod = new PaymentMethod();
$paymentMethod->setAppId($appId);
$paymentMethod->setApplicantId($ownerId);
$paymentMethod->setStripeCustomerId($customerId);
$paymentMethod->setStripePaymentMethodId($paymentMethodId);
$paymentMethod->setIsDefault(1);
$em->persist($paymentMethod);
$em->flush();
}
if ($companyGroup) {
$em->flush();
}
$redirectUrl = $redirectUrl !== '' ? $redirectUrl : $this->generateUrl(
'central_landing'
);
return $this->render('@Application/pages/stripe/success.html.twig', array(
'page_title' => 'Success',
'meetingId' => 0,
'autoRedirect' => 0,
'redirectUrl' => $redirectUrl,
'initiateCompany' => 1,
'appId' => $appId,
'ownerId' => $ownerId,
'setupOnly' => 1,
));
}
if ($invoiceId != 0) {
$invoice = $em
->getRepository("CompanyGroupBundle\\Entity\\EntityInvoice")
->findOneBy([
'id' => $invoiceId
]);
if($invoice->getAmountTransferGateWayHash() == 'stripe') {
$stripeSession = \Stripe\Checkout\Session::retrieve($request->query->get('session_id'));
$paymentIntent = \Stripe\PaymentIntent::retrieve($stripeSession->payment_intent);
if ($paymentIntent->status !== 'succeeded') {
return $this->render('@Application/pages/stripe/cancel.html.twig', array(
'page_title' => 'Failed',
));
}
$paymentMethodId = $paymentIntent->payment_method;
$customerId = $paymentIntent->customer;
$companyGroup = $this->get('app.quote_company_provisioning_service')
->ensureCompanyForInvoice($invoice, $request->getSession(), $customerId);
if (!isset($companyGroup) || !$companyGroup) {
$companyGroup = $em
->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
->findOneBy([
'appId' => $invoice->getAppId()
]);
}
$existing = $em->getRepository(PaymentMethod::class)
->findOneBy([
'stripePaymentMethodId' => $paymentMethodId
]);
if (!$existing) {
if ($companyGroup) {
// save customer id (safety)
if (!$companyGroup->getStripeCustomerId()) {
$companyGroup->setStripeCustomerId($customerId);
}
// save payment method
$paymentMethod = new PaymentMethod(); // your entity
$paymentMethod->setAppId($companyGroup->getAppId());;
$paymentMethod->setApplicantId($invoice->getApplicantId());
$paymentMethod->setStripeCustomerId($customerId);
$paymentMethod->setStripePaymentMethodId($paymentMethodId);
$paymentMethod->setIsDefault(1);
$em->persist($paymentMethod);
$em->flush();
}
}
}
$retData = Buddybee::ProcessEntityInvoice($em, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED],
$this->container->getParameter('kernel.root_dir'),
false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
$this->get('app.subscription_state_sync_service')->syncFromLegacyInvoice($invoice);
if (($retData['initiateCompany'] ?? 0) == 1 && ($retData['ownerId'] ?? 0) != 0) {
$this->get('app.post_payment_company_setup_service')
->finalizeOwnerServerSync((int)$retData['ownerId']);
}
if ($retData['sendCards'] == 1) {
$cardList = array();
$cards = $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
->findBy(
array(
'id' => $retData['cardIds']
)
);
foreach ($cards as $card) {
$cardList[] = array(
'id' => $card->getId(),
'printed' => $card->getPrinted(),
'amount' => $card->getAmount(),
'coinCount' => $card->getCoinCount(),
'pin' => $card->getPin(),
'serial' => $card->getSerial(),
);
}
$receiverEmail = $retData['receiverEmail'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = '@Application/email/templates/beeCodeDigitalDelivery.html.twig';
$bodyData = array(
'cardList' => $cardList,
// 'name' => $newApplicant->getFirstname() . ' ' . $newApplicant->getLastname(),
// 'email' => $userName,
// 'password' => $newApplicant->getPassword(),
);
$attachments = [];
$forwardToMailAddress = $receiverEmail;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Digital Bee Card Delivery',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'delivery@buddybee.eu',
'userName' => 'delivery@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'encryptionMethod' => 'tls',
'encryptionMethod' => 'ssl',
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
foreach ($cards as $card) {
$card->setPrinted(1);
}
$em->flush();
}
return new JsonResponse(
array(
'success' => true
)
);
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$meetingId = $retData['meetingId'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
->findOneBy(
array(
'Id' => $invoiceId,
)
);;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
//
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url . '/' . $meetingId);
$redirectUrl = $url . '/' . $meetingId;
} else {
$url = $this->generateUrl(
'central_landing'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url);
$redirectUrl = $url;
$autoRedirect=0;
}
if (($retData['initiateCompany'] ?? 0) == 1 && ($retData['appId'] ?? 0) != 0 && ($retData['ownerId'] ?? 0) != 0) {
$companyGroup = $em->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
->findOneBy([
'appId' => (int)$retData['appId']
]);
if ($companyGroup) {
$postPaymentSetup = $this->get('app.post_payment_company_setup_service');
$authenticationStr = $this->get('url_encryptor')->encrypt(json_encode(
$postPaymentSetup->buildAuthenticationPayload((int)$retData['ownerId'], (int)$retData['appId'])
));
$redirectUrl = $postPaymentSetup->buildSwitchAppUrl(
(int)$retData['appId'],
(int)$retData['ownerId'],
(string)$companyGroup->getCompanyGroupServerAddress(),
$authenticationStr,
(string)$request->getSession()->get('csToken', '')
);
$autoRedirect = 1;
}
}
}
return $this->render('@Application/pages/stripe/success.html.twig', array(
'page_title' => 'Success',
'meetingId' => $meetingId,
'autoRedirect' => $autoRedirect,
'redirectUrl' => $redirectUrl,
'initiateCompany' => $retData['initiateCompany']??0,
'appId' => $retData['appId']??0,
'ownerId' => $retData['ownerId']??0,
));
}
else if ($systemType == '_BUDDYBEE_') {
if ($encData != '') {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
} else {
$invoiceId = $request->query->get('invoiceId', 0);
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
}
if ($invoiceId != 0) {
$retData = Buddybee::ProcessEntityInvoice($em, $invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server')
);
if ($retData['sendCards'] == 1) {
$cardList = array();
$cards = $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
->findBy(
array(
'id' => $retData['cardIds']
)
);
foreach ($cards as $card) {
$cardList[] = array(
'id' => $card->getId(),
'printed' => $card->getPrinted(),
'amount' => $card->getAmount(),
'coinCount' => $card->getCoinCount(),
'pin' => $card->getPin(),
'serial' => $card->getSerial(),
);
}
$receiverEmail = $retData['receiverEmail'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$bodyHtml = '';
$bodyTemplate = '@Application/email/templates/beeCodeDigitalDelivery.html.twig';
$bodyData = array(
'cardList' => $cardList,
// 'name' => $newApplicant->getFirstname() . ' ' . $newApplicant->getLastname(),
// 'email' => $userName,
// 'password' => $newApplicant->getPassword(),
);
$attachments = [];
$forwardToMailAddress = $receiverEmail;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'Digital Bee Card Delivery',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'delivery@buddybee.eu',
'userName' => 'delivery@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'encryptionMethod' => 'tls',
'encryptionMethod' => 'ssl',
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
foreach ($cards as $card) {
$card->setPrinted(1);
}
$em->flush();
}
return new JsonResponse(
array(
'success' => true
)
);
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
$meetingId = $retData['meetingId'];
if (GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
$invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
->findOneBy(
array(
'Id' => $invoiceId,
)
);;
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
$bodyTemplate = '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
//
if ($meetingId != 0) {
$url = $this->generateUrl(
'consultancy_session'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url . '/' . $meetingId);
$redirectUrl = $url . '/' . $meetingId;
} else {
$url = $this->generateUrl(
'buddybee_dashboard'
);
// if($request->query->get('autoRedirect',1))
// return $this->redirect($url);
$redirectUrl = $url;
}
}
return $this->render('@Application/pages/stripe/success.html.twig', array(
'page_title' => 'Success',
'meetingId' => $meetingId,
'autoRedirect' => $autoRedirect,
'redirectUrl' => $redirectUrl,
));
}
}
public function PaymentGatewayCancelAction(Request $request, $msg = 'The Payment was unsuccessful', $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
// $consultantDetail = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(array());
$session = $request->getSession();
if ($msg == '')
$msg = $request->query->get('msg', $request->request->get('msg', 'The Payment was unsuccessful'));
return $this->render('@Application/pages/stripe/cancel.html.twig', array(
'page_title' => 'Success',
'msg' => $msg,
));
}
public function BkashCallbackAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$invoiceId = 0;
$session = $request->getSession();
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$paymentId = $request->query->get('paymentID', 0);
$status = $request->query->get('status', 0);
if ($status == 'success') {
$paymentID = $paymentId;
$gatewayInvoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
array(
'gatewayPaymentId' => $paymentId,
'isProcessed' => [0, 2]
));
if ($gatewayInvoice) {
$invoiceId = $gatewayInvoice->getId();
$justNow = new \DateTime();
$baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' : 'https://tokenized.pay.bka.sh/v1.2.0-beta';
$username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' : '01891962953';
$password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' : ',a&kPV4deq&';
$app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' : '2ueVHdwz5gH3nxx7xn8wotlztc';
$app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' : '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
$justNowTs = $justNow->format('U');
if ($gatewayInvoice->getGatewayIdTokenExpireTs() <= $justNowTs) {
$refresh_token = $gatewayInvoice->getGatewayIdRefreshToken();
$request_data = array(
'app_key' => $app_key_value,
'app_secret' => $app_secret_value,
'refresh_token' => $refresh_token
);
$url = curl_init($baseUrl . '/tokenized/checkout/token/refresh');
$request_data_json = json_encode($request_data);
$header = array(
'Content-Type:application/json',
'username:' . $username_value,
'password:' . $password_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$tokenData = json_decode(curl_exec($url), true);
curl_close($url);
$justNow = new \DateTime();
$justNow->modify('+' . $tokenData['expires_in'] . ' second');
$gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
$gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
$gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
$em->flush();
}
$auth = $gatewayInvoice->getGatewayIdToken();;
$post_token = array(
'paymentID' => $paymentID
);
// $url = curl_init();
$url = curl_init($baseUrl . '/tokenized/checkout/execute');
$posttoken = json_encode($post_token);
$header = array(
'Content-Type:application/json',
'Authorization:' . $auth,
'X-APP-Key:' . $app_key_value
);
// curl_setopt_array($url, array(
// CURLOPT_HTTPHEADER => $header,
// CURLOPT_RETURNTRANSFER => 1,
// CURLOPT_URL => $baseUrl . '/tokenized/checkout/execute',
//
// CURLOPT_FOLLOWLOCATION => 1,
// CURLOPT_POST => 1,
// CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
// CURLOPT_POSTFIELDS => http_build_query($post_token)
// ));
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $posttoken);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$resultdata = curl_exec($url);
curl_close($url);
$obj = json_decode($resultdata, true);
// return new JsonResponse(array(
// 'obj' => $obj,
// 'url' => $baseUrl . '/tokenized/checkout/execute',
// 'header' => $header,
// 'paymentID' => $paymentID,
// 'posttoken' => $posttoken,
// ));
// return new JsonResponse($obj);
if (isset($obj['statusCode'])) {
if ($obj['statusCode'] == '0000') {
$gatewayInvoice->setGatewayTransId($obj['trxID']);
$em->flush();
return $this->redirectToRoute("payment_gateway_success", ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => 1
))),
'hbeeSessionToken' => $session->get('token', 0)]);
} else {
return $this->redirectToRoute("payment_gateway_cancel", [
'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'Payment Failed')
]);
}
}
} else {
return $this->redirectToRoute("payment_gateway_cancel", [
'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'Payment Failed')
]);
}
} else {
return $this->redirectToRoute("payment_gateway_cancel", [
'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'The Payment was unsuccessful')
]);
}
}
public function MakePaymentOfEntityInvoiceAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$em_goc = $em;
$invoiceId = 0;
$autoRedirect = 1;
$redirectUrl = '';
$meetingId = 0;
$triggerMiddlePage = 0;
$session = $request->getSession();
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$refundSuccess = 0;
$errorMsg = '';
$errorCode = '';
if ($encData != '') {
$invoiceId = $encData;
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['triggerMiddlePage']))
$triggerMiddlePage = $encryptedData['triggerMiddlePage'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
} else {
$invoiceId = $request->request->get('invoiceId', $request->query->get('invoiceId', 0));
$triggerMiddlePage = $request->request->get('triggerMiddlePage', $request->query->get('triggerMiddlePage', 0));
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
}
$meetingId = $request->request->get('meetingId', $request->query->get('meetingId', 0));
$actionDone = 0;
if ($meetingId != 0) {
$dt = Buddybee::ConfirmAnyMeetingSessionIfPossible($em, 0, $meetingId, false,
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'));
if ($invoiceId == 0 && $dt['success'] == true) {
$actionDone = 1;
return new JsonResponse(array(
'clientSecret' => 0,
'actionDone' => $actionDone,
'id' => 0,
'proceedToCheckout' => 0
));
}
}
// $invoiceId = $request->request->get('meetingId', $request->query->get('meetingId', 0));
$output = [
'clientSecret' => 0,
'id' => 0,
'proceedToCheckout' => 0
];
if ($invoiceId != 0) {
$gatewayInvoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
array(
'Id' => $invoiceId,
'isProcessed' => [0]
));
} else {
$gatewayInvoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
array(
'meetingId' => $meetingId,
'isProcessed' => [0]
));
}
if ($gatewayInvoice)
$invoiceId = $gatewayInvoice->getId();
$invoiceSessionCount = 0;
$payableAmount = 0;
$imageBySessionCount = [
0 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
];
if ($gatewayInvoice) {
$gatewayProductData = json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
if ($gatewayProductData == null) $gatewayProductData = [];
$gatewayAmount = 1 * number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', '');
$invoiceSessionCount = $gatewayInvoice->getSessionCount();
$currencyForGateway = $gatewayInvoice->getAmountCurrency();
$gatewayAmount = round($gatewayAmount, 2);
if (empty($gatewayProductData))
$gatewayProductData = [
[
'price_data' => [
'currency' => 'eur',
'unit_amount' => $gatewayAmount != 0 ? (100 * $gatewayAmount) : 200000,
'product_data' => [
// 'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
'name' => 'Bee Coins',
// 'images' => [$imageBySessionCount[$invoiceSessionCount]],
'images' => [$imageBySessionCount[0]],
],
],
'quantity' => 1,
]
];
$productDescStr = '';
$productDescArr = [];
foreach ($gatewayProductData as $gpd) {
$productDescArr[] = $gpd['price_data']['product_data']['name'];
}
$productDescStr = implode(',', $productDescArr);
$paymentGatewayFromInvoice = $gatewayInvoice->getAmountTransferGateWayHash();
if ($paymentGatewayFromInvoice == 'stripe') {
$stripe = new \Stripe\Stripe();
\Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
$stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
{
if ($request->query->has('meetingSessionId'))
$id = $request->query->get('meetingSessionId');
}
$paymentIntent = [
"id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
"object" => "payment_intent",
"amount" => 3000,
"amount_capturable" => 0,
"amount_received" => 0,
"application" => null,
"application_fee_amount" => null,
"canceled_at" => null,
"cancellation_reason" => null,
"capture_method" => "automatic",
"charges" => [
"object" => "list",
"data" => [],
"has_more" => false,
"url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
],
"client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
"confirmation_method" => "automatic",
"created" => 1546523966,
"currency" => $currencyForGateway,
"customer" => null,
"description" => null,
"invoice" => null,
"last_payment_error" => null,
"livemode" => false,
"metadata" => [],
"next_action" => null,
"on_behalf_of" => null,
"payment_method" => null,
"payment_method_options" => [],
"payment_method_types" => [
"card"
],
"receipt_email" => null,
"review" => null,
"setup_future_usage" => null,
"shipping" => null,
"statement_descriptor" => null,
"statement_descriptor_suffix" => null,
"status" => "requires_payment_method",
"transfer_data" => null,
"transfer_group" => null
];
$checkout_session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => $gatewayProductData,
'mode' => 'payment',
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
]);
$output = [
'clientSecret' => $paymentIntent['client_secret'],
'id' => $checkout_session->id,
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1
];
// return new JsonResponse($output);
}
if ($paymentGatewayFromInvoice == 'aamarpay') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$url = $sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/request.php' : 'https://secure.aamarpay.com/request.php';
$fields = array(
// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
'amount' => 1 * number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', ''), //transaction amount
'payment_type' => 'VISA', //no need to change
'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
'tran_id' => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT), //transaction id must be unique from your end
'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
'cus_email' => $studentDetails->getEmail(), //customer email address
'cus_add1' => $studentDetails->getCurrAddr(), //customer address
'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
'cus_state' => $studentDetails->getCurrAddrState(), //state
'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
'cus_country' => 'Bangladesh', //country
'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' : $studentDetails->getPhone(), //customer phone number
'cus_fax' => '', //fax
'ship_name' => '', //ship name
'ship_add1' => '', //ship address
'ship_add2' => '',
'ship_city' => '',
'ship_state' => '',
'ship_postcode' => '',
'ship_country' => 'Bangladesh',
'desc' => $productDescStr,
'success_url' => $this->generateUrl(
'payment_gateway_success',
['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'fail_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
'cancel_url' => $this->generateUrl(
'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
),
// 'opt_a' => 'Reshad', //optional paramter
// 'opt_b' => 'Akil',
// 'opt_c' => 'Liza',
// 'opt_d' => 'Sohel',
// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
curl_close($ch);
// $this->redirect_to_merchant($url_forward);
$output = [
// 'redirectUrl' => 'https://sandbox.aamarpay.com/'.$url_forward, //keeping it off temporarily
'redirectUrl' => ($sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/' : 'https://secure.aamarpay.com/') . $url_forward, //keeping it off temporarily
// 'fields'=>$fields,
// 'fields_string'=>$fields_string,
// 'redirectUrl' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => 1
];
// return new JsonResponse($output);
} else if ($paymentGatewayFromInvoice == 'bkash') {
$studentDetails = $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
$baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' : 'https://tokenized.pay.bka.sh/v1.2.0-beta';
$username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' : '01891962953';
$password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' : ',a&kPV4deq&';
$app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' : '2ueVHdwz5gH3nxx7xn8wotlztc';
$app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' : '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
$request_data = array(
'app_key' => $app_key_value,
'app_secret' => $app_secret_value
);
$url = curl_init($baseUrl . '/tokenized/checkout/token/grant');
$request_data_json = json_encode($request_data);
$header = array(
'Content-Type:application/json',
'username:' . $username_value,
'password:' . $password_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$tokenData = json_decode(curl_exec($url), true);
curl_close($url);
$id_token = $tokenData['id_token'];
$goToBkashPage = 0;
if ($tokenData['statusCode'] == '0000') {
$auth = $id_token;
$requestbody = array(
"mode" => "0011",
// "payerReference" => "",
"payerReference" => $gatewayInvoice->getInvoiceDateTs(),
"callbackURL" => $this->generateUrl(
'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
"amount" => number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', ''),
"currency" => "BDT",
"intent" => "sale",
"merchantInvoiceNumber" => $invoiceId
);
$url = curl_init($baseUrl . '/tokenized/checkout/create');
$requestbodyJson = json_encode($requestbody);
$header = array(
'Content-Type:application/json',
'Authorization:' . $auth,
'X-APP-Key:' . $app_key_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $requestbodyJson);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$resultdata = curl_exec($url);
curl_close($url);
// return new JsonResponse($resultdata);
$obj = json_decode($resultdata, true);
$goToBkashPage = 1;
$justNow = new \DateTime();
$justNow->modify('+' . $tokenData['expires_in'] . ' second');
$gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
$gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
$gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
$gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
$em->flush();
$output = [
'redirectUrl' => $obj['bkashURL'],
'paymentGateway' => $paymentGatewayFromInvoice,
'proceedToCheckout' => $goToBkashPage,
'tokenData' => $tokenData,
'obj' => $obj,
'id_token' => $tokenData['id_token'],
];
}
// $fields = array(
//
// "mode" => "0011",
// "payerReference" => "01723888888",
// "callbackURL" => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// "merchantAssociationInfo" => "MI05MID54RF09123456One",
// "amount" => $gatewayInvoice->getGateWayBillamount(),
// "currency" => "BDT",
// "intent" => "sale",
// "merchantInvoiceNumber" => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT)
//
// );
// $fields = array(
//// 'store_id' => 'aamarpaytest', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay, contact integration@aamarpay.com for test/live id
// 'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
// 'payment_type' => 'VISA', //no need to change
// 'currency' => strtoupper($currencyForGateway), //currenct will be USD/BDT
// 'tran_id' => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT), //transaction id must be unique from your end
// 'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(), //customer name
// 'cus_email' => $studentDetails->getEmail(), //customer email address
// 'cus_add1' => $studentDetails->getCurrAddr(), //customer address
// 'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
// 'cus_city' => $studentDetails->getCurrAddrCity(), //customer city
// 'cus_state' => $studentDetails->getCurrAddrState(), //state
// 'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
// 'cus_country' => 'Bangladesh', //country
// 'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
// 'cus_fax' => '', //fax
// 'ship_name' => '', //ship name
// 'ship_add1' => '', //ship address
// 'ship_add2' => '',
// 'ship_city' => '',
// 'ship_state' => '',
// 'ship_postcode' => '',
// 'ship_country' => 'Bangladesh',
// 'desc' => $productDescStr,
// 'success_url' => $this->generateUrl(
// 'payment_gateway_success',
// ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
// 'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
// ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'fail_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
// 'cancel_url' => $this->generateUrl(
// 'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
// ),
//// 'opt_a' => 'Reshad', //optional paramter
//// 'opt_b' => 'Akil',
//// 'opt_c' => 'Liza',
//// 'opt_d' => 'Sohel',
//// 'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183', //sandbox
// 'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524' //live
//
// ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
//
// $fields_string = http_build_query($fields);
//
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_VERBOSE, true);
// curl_setopt($ch, CURLOPT_URL, $url);
//
// curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
// curl_close($ch);
// $this->redirect_to_merchant($url_forward);
}
}
if ($triggerMiddlePage == 1) return $this->render('@Buddybee/pages/makePaymentOfEntityInvoiceLandingPage.html.twig', array(
'page_title' => 'Invoice Payment',
'data' => $output,
));
else
return new JsonResponse($output);
}
public function RefundEntityInvoiceAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$invoiceId = 0;
$currIsProcessedFlagValue = '_UNSET_';
$session = $request->getSession();
$sandBoxMode = $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
$paymentId = $request->query->get('paymentID', 0);
$status = $request->query->get('status', 0);
$refundSuccess = 0;
$errorMsg = '';
$errorCode = '';
if ($encData != '') {
$invoiceId = $encData;
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
} else {
$invoiceId = $request->request->get('invoiceId', $request->query->get('invoiceId', 0));
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
}
$gatewayInvoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
array(
'Id' => $invoiceId,
'isProcessed' => [1]
));
if ($gatewayInvoice) {
$gatewayInvoice->setIsProcessed(3); //pending settlement
$currIsProcessedFlagValue = $gatewayInvoice->getIsProcessed();
$em->flush();
if ($gatewayInvoice->getAmountTransferGateWayHash() == 'bkash') {
$invoiceId = $gatewayInvoice->getId();
$paymentID = $gatewayInvoice->getGatewayPaymentId();
$trxID = $gatewayInvoice->getGatewayTransId();
$justNow = new \DateTime();
$baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' : 'https://tokenized.pay.bka.sh/v1.2.0-beta';
$username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' : '01891962953';
$password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' : ',a&kPV4deq&';
$app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' : '2ueVHdwz5gH3nxx7xn8wotlztc';
$app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' : '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
$justNowTs = $justNow->format('U');
if ($gatewayInvoice->getGatewayIdTokenExpireTs() <= $justNowTs) {
$refresh_token = $gatewayInvoice->getGatewayIdRefreshToken();
$request_data = array(
'app_key' => $app_key_value,
'app_secret' => $app_secret_value,
'refresh_token' => $refresh_token
);
$url = curl_init($baseUrl . '/tokenized/checkout/token/refresh');
$request_data_json = json_encode($request_data);
$header = array(
'Content-Type:application/json',
'username:' . $username_value,
'password:' . $password_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $request_data_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$tokenData = json_decode(curl_exec($url), true);
curl_close($url);
$justNow = new \DateTime();
$justNow->modify('+' . $tokenData['expires_in'] . ' second');
$gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
$gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
$gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
$em->flush();
}
$auth = $gatewayInvoice->getGatewayIdToken();;
$post_token = array(
'paymentID' => $paymentID,
'trxID' => $trxID,
'reason' => 'Full Refund Policy',
'sku' => 'RSTR',
'amount' => 1 * number_format($gatewayInvoice->getGateWayBillamount(), 2, '.', ''),
);
$url = curl_init($baseUrl . '/tokenized/checkout/payment/refund');
$posttoken = json_encode($post_token);
$header = array(
'Content-Type:application/json',
'Authorization:' . $auth,
'X-APP-Key:' . $app_key_value
);
curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $posttoken);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$resultdata = curl_exec($url);
curl_close($url);
$obj = json_decode($resultdata, true);
// return new JsonResponse($obj);
if (isset($obj['completedTime']))
$refundSuccess = 1;
else if (isset($obj['errorCode'])) {
$refundSuccess = 0;
$errorCode = $obj['errorCode'];
$errorMsg = $obj['errorMessage'];
}
// $gatewayInvoice->setGatewayTransId($obj['trxID']);
$em->flush();
}
if ($refundSuccess == 1) {
Buddybee::RefundEntityInvoice($em, $invoiceId);
$currIsProcessedFlagValue = 4;
}
} else {
}
MiscActions::RefreshBuddybeeBalanceOnSession($em, $request->getSession());
return new JsonResponse(
array(
'success' => $refundSuccess,
'errorCode' => $errorCode,
'isProcessed' => $currIsProcessedFlagValue,
'errorMsg' => $errorMsg,
)
);
}
public function ViewEntityInvoiceAction(Request $request, $encData = '')
{
$em = $this->getDoctrine()->getManager('company_group');
$invoiceId = 0;
$autoRedirect = 1;
$redirectUrl = '';
$meetingId = 0;
$invoice = null;
if ($encData != '') {
$encryptedData = json_decode($this->get('url_encryptor')->decrypt($encData), true);
$invoiceId = $encData;
if (isset($encryptedData['invoiceId']))
$invoiceId = $encryptedData['invoiceId'];
if (isset($encryptedData['autoRedirect']))
$autoRedirect = $encryptedData['autoRedirect'];
} else {
$invoiceId = $request->query->get('invoiceId', 0);
$meetingId = 0;
$autoRedirect = $request->query->get('autoRedirect', 1);
$redirectUrl = '';
}
// $invoiceList = [];
$billerDetails = [];
$billToDetails = [];
if ($invoiceId != 0) {
$invoice = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
->findOneBy(
array(
'Id' => $invoiceId,
)
);
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
}
if ($request->query->get('sendMail', 0) == 1 && GeneralConstant::EMAIL_ENABLED == 1) {
$billerDetails = [];
$billToDetails = [];
if ($invoice) {
$billerDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillerId(),
)
);
$billToDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
->findOneBy(
array(
'applicantId' => $invoice->getBillToId(),
)
);
$bodyTemplate = '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
$bodyData = array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
);
$attachments = [];
$forwardToMailAddress = $billToDetails->getOAuthEmail();
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_CUSTOM_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => 'YourInvoice #' . 'D' . str_pad('BB', 5, '0', STR_PAD_LEFT) . str_pad('76', 2, '0', STR_PAD_LEFT) . str_pad($invoice->getId(), 8, "0", STR_PAD_LEFT) . ' from BuddyBee ',
// 'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
'fromAddress' => 'no-reply@buddybee.eu',
'userName' => 'no-reply@buddybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
// 'emailBody' => $bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 0,
'companyId' => 0,
'companyImagePath' => ''
// 'embedCompanyImage' => 1,
// 'companyId' => $companyId,
// 'companyImagePath' => $company_data->getImage()
));
}
}
// if ($invoice) {
//
// } else {
// return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
// 'page_title' => '404 Not Found',
//
// ));
// }
return $this->render('@HoneybeeWeb/pages/views/honeybee_ecosystem_invoice.html.twig', array(
'page_title' => 'Invoice',
// 'studentDetails' => $student,
'billerDetails' => $billerDetails,
'billToDetails' => $billToDetails,
'invoice' => $invoice,
'currencyList' => BuddybeeConstant::$currency_List,
'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
));
}
}
public function SignatureCheckFromCentralAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
if ($systemType !== '_CENTRAL_') {
return new JsonResponse(['success' => false, 'message' => 'Only allowed on CENTRAL server.'], 403);
}
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$data = json_decode($request->getContent(), true);
if (
!$data ||
!isset($data['userId']) ||
!isset($data['companyId']) ||
!isset($data['signatureData']) ||
!isset($data['approvalHash']) ||
!isset($data['applicantId'])
) {
return new JsonResponse(['success' => false, 'message' => 'Missing parameters.'], 400);
}
$userId = $data['userId'];
$companyId = $data['companyId'];
$signatureData = $data['signatureData'];
$approvalHash = $data['approvalHash'];
$applicantId = $data['applicantId'];
try {
$centralUser = $em
->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
->findOneBy(['applicantId' => $applicantId]);
if (!$centralUser) {
return new JsonResponse(['success' => false, 'message' => 'Central user not found.'], 404);
}
$userAppIds = json_decode($centralUser->getUserAppIds(), true);
if (!is_array($userAppIds)) $userAppIds = [];
$companies = $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
'appId' => $userAppIds
]);
if (count($companies) < 1) {
return new JsonResponse(['success' => false, 'message' => 'No companies found for userAppIds.'], 404);
}
$repo = $em->getRepository('CompanyGroupBundle\\Entity\\EntitySignature');
$record = $repo->findOneBy(['userId' => $userId]);
if (!$record) {
$record = new \CompanyGroupBundle\Entity\EntitySignature();
$record->setUserId($applicantId);
$record->setCreatedAt(new \DateTime());
}
$record->setCompanyId($companyId);
$record->setApplicantId($applicantId);
$record->setData($signatureData);
$record->setSigExists(0);
$record->setLastDecryptedSigId(0);
$record->setUpdatedAt(new \DateTime());
$em->persist($record);
$em->flush();
$dataByServerId = [];
$gocDataListByAppId = [];
foreach ($companies as $entry) {
$gocDataListByAppId[$entry->getAppId()] = [
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'appId' => $entry->getAppId(),
'serverId' => $entry->getCompanyGroupServerId(),
];
if (!isset($dataByServerId[$entry->getCompanyGroupServerId()]))
$dataByServerId[$entry->getCompanyGroupServerId()] = array(
'serverId' => $entry->getCompanyGroupServerId(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'payload' => array(
'globalId' => $applicantId,
'companyId' => $userAppIds,
'signatureData' => $signatureData,
// 'approvalHash' => $approvalHash
)
);
}
$urls = [];
foreach ($dataByServerId as $entry) {
$serverAddress = $entry['serverAddress'];
if (!$serverAddress) continue;
// $connector = $this->container->get('application_connector');
// $connector->resetConnection(
// 'default',
// $entry['dbName'],
// $entry['dbUser'],
// $entry['dbPass'],
// $entry['dbHost'],
// $reset = true
// );
$syncUrl = $serverAddress . '/ReceiveSignatureFromCentral';
$payload = $entry['payload'];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_URL => $syncUrl,
// CURLOPT_PORT => $entry['port'],
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode($payload)
]);
$response = curl_exec($curl);
$err = curl_error($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
// if ($err) {
// error_log("ERP Sync Error [AppID $appId]: $err");
// $urls[]=$err;
// } else {
// error_log("ERP Sync Response [AppID $appId] (HTTP $httpCode): $response");
// $res = json_decode($response, true);
// if (!isset($res['success']) || !$res['success']) {
// error_log("❗ ERP Sync error for AppID $appId: " . ($res['message'] ?? 'Unknown'));
// }
//
// $urls[]=$response;
// }
}
return new JsonResponse(['success' => true, 'message' => 'Signature synced successfully.']);
} catch (\Exception $e) {
return new JsonResponse(['success' => false, 'message' => 'DB error: ' . $e->getMessage()], 500);
}
}
//datev cntroller
public function connectDatev(Request $request)
{
$clientId = "51b09bdcf577c5b998cddce7fe7d5c92";
$redirectUri = "https://ourhoneybee.eu/datev/callback";
$state = bin2hex(random_bytes(10));
$scope = "openid profile email accounting:documents accounting:dxso-jobs accounting:clients:read datev:accounting:extf-files-import datev:accounting:clients";
$codeVerifier = bin2hex(random_bytes(32));
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
$session = $request->getSession();
$applicantId = $session->get(UserConstants::APPLICANT_ID);
$em_goc = $this->getDoctrine()->getManager('company_group');
$token = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
->findOneBy(['userId' => $applicantId]);
if (!$token) {
$token = new EntityDatevToken();
$token->setUserId($applicantId);
}
$token->setState($state);
$token->setCodeChallenge($codeChallenge);
$token->setCodeVerifier($codeVerifier);
$em_goc->persist($token);
$em_goc->flush();
$url = "https://login.datev.de/openidsandbox/authorize?"
."response_type=code"
."&client_id=".$clientId
."&state=".$state
."&scope=".urlencode($scope)
."&redirect_uri=".urlencode($redirectUri)
."&code_challenge=".$codeChallenge
."&code_challenge_method=S256"
."&prompt=login";
return $this->redirect($url);
}
public function datevCallback(Request $request)
{
$code = $request->get('code');
$state = $request->get('state');
if (!$code || !$state) {
return new Response("Invalid callback request");
}
$em_goc = $this->getDoctrine()->getManager('company_group');
$tokenEntity = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
->findOneBy(['state' => $state]);
if (!$tokenEntity) {
return new Response("Invalid or expired state");
}
$codeVerifier = $tokenEntity->getCodeVerifier();
if (!$codeVerifier) {
return new Response("Code verifier missing");
}
$clientId = "51b09bdcf577c5b998cddce7fe7d5c92";
$clientSecret = "9b1c4e72a966e9f231584393ff1d3469";
// from parameters
// $clientId= $this->getContainer()->getParameter('datev_client_id');
// $clientSecret= $this->getContainer()->getParameter('datev_client_secret');
$authString = base64_encode($clientId . ":" . $clientSecret);
$redirectUri = "https://ourhoneybee.eu/datev/callback";
$postFields = http_build_query([
"grant_type" => "authorization_code",
"code" => $code,
"redirect_uri" => $redirectUri,
"client_id" => $clientId,
"code_verifier" => $codeVerifier
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://sandbox-api.datev.de/token",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_HTTPHEADER => [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Basic " . $authString
]
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
return new Response("cURL Error: " . curl_error($ch), 500);
}
curl_close($ch);
$data = json_decode($response, true);
if (!$data) {
return new Response("Invalid token response", 500);
}
if (isset($data['access_token'])) {
$tokenEntity->setAccessToken($data['access_token']);
$session = $request->getSession(); //remove it later
$session->set('DATEV_ACCESS_TOKEN', $data['access_token']);
if (isset($data['refresh_token'])) {
$tokenEntity->setRefreshToken($data['refresh_token']);
}
if (isset($data['expires_in'])) {
$tokenEntity->setExpiresAt(time() + $data['expires_in']);
}
// $tokenEntity->setState(null);
$tokenEntity->setCode($code);
$em_goc->flush();
return $this->redirect("/datev/home");
}
return new Response(
"Token exchange failed: " . json_encode($data),
400
);
}
public function refreshToken(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$session = $request->getSession();
$applicantId = $session->get(UserConstants::APPLICANT_ID);
$token = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
->findOneBy(['userId' => $applicantId]);
if (!$token) {
return new JsonResponse([
'status' => false,
'message' => 'User token not found'
]);
}
if (!$token->getRefreshToken()) {
return new JsonResponse([
'status' => false,
'message' => 'No refresh token available'
]);
}
$clientId = "51b09bdcf577c5b998cddce7fe7d5c92";
$clientSecret = "9b1c4e72a966e9f231584393ff1d3469";
$authString = base64_encode($clientId . ":" . $clientSecret);
$postFields = http_build_query([
"grant_type" => "refresh_token",
"refresh_token" => $token->getRefreshToken(),
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://sandbox-api.datev.de/token",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_HTTPHEADER => [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Basic " . $authString
]
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
return new JsonResponse([
'status' => false,
'message' => curl_error($ch)
]);
}
curl_close($ch);
$data = json_decode($response, true);
if (!isset($data['access_token'])) {
return new JsonResponse([
'status' => false,
'message' => 'Refresh failed',
'error' => $data
]);
}
$token->setAccessToken($data['access_token']);
if (isset($data['refresh_token'])) {
$token->setRefreshToken($data['refresh_token']);
}
$token->setExpiresAt(time() + $data['expires_in']);
$em_goc->flush();
return new JsonResponse([
'status' => true,
'message' => 'Token refreshed successfully'
]);
}
public function registerDevice(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$data = json_decode($request->getContent(), true);
if (!$data) {
$data = $request->request->all();
}
$deviceSerial = $data['device_id'] ?? null;
if (!$deviceSerial) {
return new JsonResponse([
'success' => false,
'message' => 'Device serial is required',
'data' => null
], 400);
}
$device = $em_goc->getRepository('CompanyGroupBundle\\Entity\\Device')
->findOneBy(['deviceSerial' => $deviceSerial]);
if (!$device) {
$device = new Device();
$device->setDeviceSerial($deviceSerial);
$message = 'Device registered successfully';
} else {
$message = 'Device updated successfully';
}
if (isset($data['deviceName'])) {
$device->setDeviceName($data['deviceName']);
}
if (isset($data['appId'])) {
$device->setAppId($data['appId']);
}
if (isset($data['deviceType'])) {
$device->setDeviceType($data['deviceType']);
}
if (isset($data['deviceMarker'])) {
$device->setDeviceMarker($data['deviceMarker']);
}
if (isset($data['timezoneStr'])) {
$device->setTimezoneStr($data['timezoneStr']);
}
if (isset($data['hostname'])) {
$device->setHostName($data['hostname']);
}
$em_goc->persist($device);
$em_goc->flush();
return new JsonResponse([
'success' => true,
'message' => $message,
'data' => [
'id' => $device->getId(),
'deviceSerial' => $device->getDeviceSerial(),
'deviceName' => $device->getDeviceName(),
'deviceType' => $device->getDeviceType(),
'hostName' => $device->getHostName(),
]
]);
}
public function khorchapatiTermsAndConditions()
{
return $this->render('@HoneybeeWeb/pages/khorchapati_terms_and_conditions.html.twig', array(
'page_title' => 'Terms and Conditions — Khorchapati',
));
}
public function milkShareTermsAndConditions()
{
return $this->render('@HoneybeeWeb/pages/milkshare-terms-and-conditions.html.twig', array(
'page_title' => 'Terms and Conditions — Milkshare',
));
}
}