Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Reev\Rfc\Model;
- class FelRfc
- {
- const XML_PATH_FEEL_RFC_ENABLE = 'fel_rfc/general/enable';
- const XML_PATH_FEEL_RFC_ENDPOINT_URI = 'fel_rfc/general/endpoint_uri';
- const XML_PATH_FEEL_RFC_ACCOUNT = 'fel_rfc/general/account';
- const XML_PATH_FEEL_RFC_PASSWORD = 'fel_rfc/general/password';
- const XML_PATH_FEEL_RFC_USER = 'fel_rfc/general/user';
- const XML_PATH_FEEL_RFC_TEST_MODE = 'fel_rfc/general/test_mode';
- const XML_PATH_FEEL_RFC_TEST_ENDPOINT_URI = 'fel_rfc/general/test_endpoint_uri';
- const XML_PATH_FEEL_RFC_TEST_ACCOUNT = 'fel_rfc/general/test_account';
- const XML_PATH_FEEL_RFC_TEST_PASSWORD = 'fel_rfc/general/test_password';
- const XML_PATH_FEEL_RFC_TEST_USER = 'fel_rfc/general/test_user';
- const XML_PATH_FEEL_RFC_EMISOR_NAME = 'fel_rfc/emisor/issuing_name';
- const XML_PATH_FEEL_RFC_EMISOR_TAX_REGIME = 'fel_rfc/emisor/tax_regime';
- const XML_PATH_FEEL_RFC_EMISOR_CFDI_KEY = 'fel_rfc/emisor/cfdi_key';
- const XML_PATH_FEEL_RFC_EMISOR_CP_EXPEDITION = 'fel_rfc/emisor/cp_expedition';
- const XML_PATH_FEEL_RFC_TEMPLATE_NAME = 'fel_rfc/emisor/tempĺate';
- const XML_PATH_FEEL_RFC_TITLE_EMAIL = 'fel_rfc/emisor/title_email';
- const XML_PATH_FEEL_RFC_MESSAGE_EMAIL = 'fel_rfc/emisor/message_email';
- const STORE_SCOPE = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
- protected $resultPageFactory;
- protected $scopeConfig;
- protected $cfdiFactory;
- protected $rfcFactory;
- protected $pricingHelper;
- public function __construct(
- \Magento\Framework\View\Result\PageFactory $resultPageFactory,
- \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
- \Reev\Rfc\Model\RfcFactory $rfcFactory,
- \Reev\Rfc\Model\CfdiFactory $cfdiFactory,
- \Magento\Framework\Pricing\Helper\Data $pricingHelper)
- {
- $this->resultPageFactory = $resultPageFactory;
- $this->scopeConfig = $scopeConfig;
- $this->rfcFactory = $rfcFactory;
- $this->cfdiFactory = $cfdiFactory;
- $this->pricingHelper = $pricingHelper;
- }
- public function createCfdi(\Magento\Sales\Model\Order $order)
- {
- if($this->isModuleEnable() && $order->getId()) {
- if($this->isTestMode())
- $endpointUri = $this->getTestEndpointUri();
- else
- $endpointUri = $this->getEndpointUri();
- $soap = new \SoapClient($endpointUri.'?WSDL');
- $xml_request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:tes="http://schemas.datacontract.org/2004/07/TES.V33.CFDI.Negocios">
- <soapenv:Header />
- <soapenv:Body>
- <tem:GenerarCFDI>
- <tem:credenciales>
- <tes:Cuenta>'.$this->getAccount().'</tes:Cuenta>
- <tes:Password>'.$this->getPassword().'</tes:Password>
- <tes:Usuario>'.$this->getUser().'</tes:Usuario>
- </tem:credenciales>
- <tem:cfdi>
- <tes:ClaveCFDI>'.$this->getEmisorCfdiKey().'</tes:ClaveCFDI>
- <tes:Conceptos>'.$this->getConcepts($order).'</tes:Conceptos>
- <tes:Emisor>
- <tes:Nombre>'.$this->getEmisorName().'</tes:Nombre>
- <tes:RegimenFiscal>'.$this->getEmisorTaxRegime().'</tes:RegimenFiscal>
- </tes:Emisor>
- <tes:LugarExpedicion>'.$this->getEmisorCpExpedition().'</tes:LugarExpedicion>
- <tes:Moneda>MXN</tes:Moneda>
- <tes:Receptor>'.$this->getReceptor($order).'</tes:Receptor>
- <tes:SubTotal>'.$this->pricingHelper->currency($order->getBaseSubtotalInclTax(),false,false).'</tes:SubTotal>
- <tes:Total>'.$this->pricingHelper->currency($order->getBaseSubtotalInclTax(),false,false).'</tes:Total>
- </tem:cfdi>
- </tem:GenerarCFDI>
- </soapenv:Body>
- </soapenv:Envelope>';
- try {
- $soapXMLResult = $soap->__doRequest($xml_request,
- $endpointUri,
- 'http://tempuri.org/IConexionRemota/GenerarCFDI',
- '1.2');
- $soapXMLResult = $this->deleteAllBetween('<a:CBB>','</a:CBB>',$soapXMLResult);
- $obj = new \SimpleXMLElement($soapXMLResult);
- $dataArr = $this->xmlNodeToArray($obj);
- $success = filter_var($dataArr['operacionexitosa'], FILTER_VALIDATE_BOOLEAN);
- $uuid = $this->saveInDb($xml_request, $dataArr, $order, $success);
- if($success && !empty($uuid)){
- $sendToMail = $this->sendCfdiToEmail($uuid, $order->getCustomerEmail());
- if($sendToMail['success'])
- $this->saveMailSentInDb($order);
- }
- return ['success'=>$success,'message'=>$dataArr['errorgeneral']];
- }catch(Exception $e){
- return ['success'=>false,'message'=>$e->getMessage()];
- }
- }
- return ['success'=>false,'message'=>__('The module is not enabled, or there is not an order to create the cfdi')];
- }
- public function sendCfdiToEmail($uuid, $email){
- if($this->isTestMode())
- $endpointUri = $this->getTestEndpointUri();
- else
- $endpointUri = $this->getEndpointUri();
- $soap = new \SoapClient($endpointUri.'?WSDL');
- $xml_request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:tes="http://schemas.datacontract.org/2004/07/TES.V33.CFDI.Negocios">
- <soapenv:Header />
- <soapenv:Body>
- <tem:EnviarCFDI>
- <tem:credenciales>
- <tes:Cuenta>'.$this->getAccount().'</tes:Cuenta>
- <tes:Password>'.$this->getPassword().'</tes:Password>
- <tes:Usuario>'.$this->getUser().'</tes:Usuario>
- </tem:credenciales>
- <tem:uuid>'.$uuid.'</tem:uuid>
- <tem:email>'.$email.'</tem:email>
- <tem:titulo>'.$this->getTitleEmailCfdi().'</tem:titulo>
- <tem:mensaje>'.$this->getMessageEmailCfdi().'</tem:mensaje>
- <tem:nombrePlantilla>'.$this->getTemplateName().'</tem:nombrePlantilla>
- </tem:EnviarCFDI>
- </soapenv:Body>
- </soapenv:Envelope>';
- try {
- $soapXMLResult = $soap->__doRequest($xml_request,
- $endpointUri,
- 'http://tempuri.org/IConexionRemota/EnviarCFDI',
- '1.2');
- $soapXMLResult = $this->deleteAllBetween('<a:CBB>','</a:CBB>',$soapXMLResult);
- $obj = new \SimpleXMLElement($soapXMLResult);
- $dataArr = $this->xmlNodeToArray($obj);
- $success = filter_var($dataArr['operacionexitosa'], FILTER_VALIDATE_BOOLEAN);
- return ['success'=>$success,'message'=>$dataArr['errorgeneral']];
- }catch(Exception $e){
- return ['success'=>false,'message'=>$e->getMessage()];
- }
- }
- public function getPdf($uuid){
- if($this->isModuleEnable()){
- if($this->isTestMode())
- $endpointUri = $this->getTestEndpointUri();
- else
- $endpointUri = $this->getEndpointUri();
- $soap = new \SoapClient($endpointUri.'?WSDL');
- $xml_request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:tes="http://schemas.datacontract.org/2004/07/TES.V33.CFDI.Negocios">
- <soapenv:Header/>
- <soapenv:Body>
- <tem:ObtenerPDF>
- <tem:credenciales>
- <tes:Cuenta>'.$this->getAccount().'</tes:Cuenta>
- <tes:Password>'.$this->getPassword().'</tes:Password>
- <tes:Usuario>'.$this->getUser().'</tes:Usuario>
- </tem:credenciales>
- <tem:uuid>'.$uuid.'</tem:uuid>
- <tem:nombrePlantilla>'.$this->getTemplateName().'</tem:nombrePlantilla>
- </tem:ObtenerPDF>
- </soapenv:Body>
- </soapenv:Envelope>';
- try {
- $soapXMLResult = $soap->__doRequest($xml_request,
- $endpointUri,
- 'http://tempuri.org/IConexionRemota/ObtenerPDF',
- '1.2');
- $obj = new \SimpleXMLElement($soapXMLResult);
- $dataArr = $this->xmlNodeToArray($obj);
- $success = filter_var($dataArr['operacionexitosa'], FILTER_VALIDATE_BOOLEAN);
- return ['success'=>$success,'message'=>$dataArr['errorgeneral']];
- }catch(Exception $e){
- return ['success'=>false,'message'=>$e->getMessage()];
- }
- }
- return ['success'=>false,'message'=>__('The module is not enabled, or there is not an order to create the cfdi')];
- }
- public function getConcepts(\Magento\Sales\Model\Order $order){
- $str = '';
- foreach($order->getAllItems() as $item){
- $str .= '<tes:ConceptoR>
- <tes:Cantidad>'.$item->getQtyOrdered().'</tes:Cantidad>
- <tes:ClaveProdServ>'.$item->getProduct()->getSatrfcproducto().'</tes:ClaveProdServ>
- <tes:ClaveUnidad>H87</tes:ClaveUnidad>
- <tes:Descripcion>'.htmlspecialchars($item->getProduct()->getName()).'</tes:Descripcion>
- <tes:Importe>'.$this->pricingHelper->currency($item->getBaseRowTotalInclTax(),false,false).'</tes:Importe>
- <tes:NoIdentificacion>'.$item->getSku().'</tes:NoIdentificacion>
- <tes:ValorUnitario>'.$this->pricingHelper->currency($item->getBasePriceInclTax(),false,false).'</tes:ValorUnitario>
- <tes:Unidad>Pieza</tes:Unidad>
- </tes:ConceptoR>';
- }
- return $str;
- }
- public function getReceptor(\Magento\Sales\Model\Order $order){
- $rfc = $this->rfcFactory->create()->load($order->getCustomerRfcId());
- $str = '';
- if($rfc->getId()) {
- $str = '<tes:Nombre>' . $rfc->getCompany() . '</tes:Nombre>
- <tes:Rfc>' . $rfc->getRfc() . '</tes:Rfc>
- <tes:UsoCFDI>' . $rfc->getCfdiCode() . '</tes:UsoCFDI>';
- }
- return $str;
- }
- protected function xmlNodeToArray(\SimpleXMLElement $node)
- {
- $collectedKeys = [];
- $data = [];
- $namespaces = $node->getNamespaces(true);
- foreach ($node->children($namespaces['s'])->children()->children()->children($namespaces['a']) as $label => $node) {
- $key = $this->mapKey($this->snakeToCamel($label));
- $childData = $this->extractNodeInformation($node);
- if (isset($data[$key])) {
- if (!isset($collectedKeys[$key])) {
- $collectedKeys[$key] = true;
- $data[$key] = [$data[$key]];
- }
- $data[$key][] = $childData;
- } else {
- $data[$key] = $childData;
- }
- }
- return $data;
- }
- protected function mapKey(string $key)
- {
- $lcKey = str_replace('_', '', strtolower($key));
- if (isset($this->keyMap[$lcKey])) {
- return $this->keyMap[$lcKey];
- }
- return $key;
- }
- protected function snakeToCamel($snakeString): string
- {
- // This line is why Elixir > PHP
- return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($snakeString)))));
- }
- protected function extractNodeInformation(\SimpleXMLElement $node)
- {
- $attributes = (array)$node->attributes();
- $nodeData = $this->getNodeValue($node);
- if (count($attributes)) {
- $attributes = current($attributes);
- $data = ['attributes' => []];
- foreach ($attributes as $attributeKey => $attributeValue) {
- $data['attributes'][$this->snakeToCamel($attributeKey)] = (string)$attributeValue;
- }
- $data['value'] = $nodeData;
- return $data;
- }
- return $nodeData;
- }
- protected function getNodeValue(\SimpleXMLElement $node)
- {
- if ($node->count()) {
- return $this->xmlNodeToArray($node);
- }
- $stringValue = (string)$node;
- return is_numeric($stringValue) ? (float)$stringValue : $stringValue;
- }
- protected function deleteAllBetween($beginning, $end, $string) {
- $beginningPos = strpos($string, $beginning);
- $endPos = strpos($string, $end);
- if ($beginningPos === false || $endPos === false) {
- return $string;
- }
- $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);
- return str_replace($textToDelete, '', $string); // recursion to ensure all occurrences are replaced
- }
- public function isModuleEnable($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_ENABLE, $storeScope);
- }
- public function getEndpointUri($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_ENDPOINT_URI, $storeScope);
- }
- public function getAccount($storeScope = self::STORE_SCOPE){
- if($this->isTestMode())
- return $this->getTestAccount();
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_ACCOUNT, $storeScope);
- }
- public function getPassword($storeScope = self::STORE_SCOPE){
- if($this->isTestMode())
- return $this->getTestPassword();
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_PASSWORD, $storeScope);
- }
- public function getUser($storeScope = self::STORE_SCOPE){
- if($this->isTestMode())
- return $this->getTestUser();
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_USER, $storeScope);
- }
- public function isTestMode($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_TEST_MODE, $storeScope);
- }
- public function getTestEndpointUri($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_TEST_ENDPOINT_URI, $storeScope);
- }
- public function getTestAccount($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_TEST_ACCOUNT, $storeScope);
- }
- public function getTestPassword($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_TEST_PASSWORD, $storeScope);
- }
- public function getTestUser($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_TEST_USER, $storeScope);
- }
- public function getEmisorName($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_EMISOR_NAME, $storeScope);
- }
- public function getEmisorTaxRegime($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_EMISOR_TAX_REGIME, $storeScope);
- }
- public function getEmisorCfdiKey($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_EMISOR_CFDI_KEY, $storeScope);
- }
- public function getEmisorCpExpedition($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_EMISOR_CP_EXPEDITION, $storeScope);
- }
- public function getTemplateName($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_TEMPLATE_NAME, $storeScope);
- }
- public function getTitleEmailCfdi($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_TITLE_EMAIL, $storeScope);
- }
- public function getMessageEmailCfdi($storeScope = self::STORE_SCOPE){
- return $this->scopeConfig->getValue(self::XML_PATH_FEEL_RFC_MESSAGE_EMAIL, $storeScope);
- }
- protected function saveInDb($request, $response, $order, $success){
- $cfdiRequest = $this->cfdiFactory->create();
- $uuid = null;
- if($success){
- $obj = new \SimpleXMLElement($response['xml']);
- $namespaces = $obj->getNamespaces(true);
- $child = $obj->children($namespaces['cfdi']);
- foreach($child as $key=>$node){
- if($key=='Complemento'){
- $uuid = $node->children($namespaces['tfd'])->attributes()['UUID'];
- }
- }
- $order->setCfdiGenerated($success)->save();
- }
- $cfdiRequest->setRequestXml($request)
- ->setResponse(json_encode($response))
- ->setSuccess($success)
- ->setOrderId($order->getId())
- ->setUuid($uuid)
- ->save();
- return $uuid;
- }
- protected function saveMailSentInDb($order){
- $order->setCfdiSentToMail(true)->save();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement