@@ -190,10 +190,10 @@ private function allowedItemType($itemType)
190190 * @param $reissue
191191 * @return array
192192 */
193- private function buildItemsToTransmit ($ items , $ invoiceId , $ userId , $ reissue = false )
193+ private function buildItemsToTransmit ($ items , $ invoiceId , $ userId , $ companyId , $ issHeldDefault , $ reissue = false )
194194 {
195195 // ISS padrão
196- $ issHeld = floatval ( $ this -> storage -> get ( ' iss_held ' )) ;
196+ $ issHeld = $ issHeldDefault ;
197197 $ result = [];
198198
199199 // percorre $items para construir os itens a serem emitidos
@@ -212,6 +212,7 @@ private function buildItemsToTransmit($items, $invoiceId, $userId, $reissue = fa
212212 'flow_status ' => 'waiting ' ,
213213 'pdf ' => 'waiting ' ,
214214 'rpsSerialNumber ' => 'waiting ' ,
215+ 'company_id ' => $ companyId ,
215216 'service_code ' => $ serviceCode ,
216217 ];
217218
@@ -228,10 +229,10 @@ private function buildItemsToTransmit($items, $invoiceId, $userId, $reissue = fa
228229 // adiciona o valor total calculado para os itens
229230 $ nfData ['services_amount ' ] = $ itemsTotal ;
230231 // gera id unico externo
231- $ nfData ['nfe_external_id ' ] = $ this ->generateUniqueExternalId ($ userId , $ invoiceId , $ itemsTotal , $ reissue );
232+ $ nfData ['nfe_external_id ' ] = $ this ->generateUniqueExternalId ($ userId , $ invoiceId , $ itemsTotal , $ companyId , $ serviceCode , $ reissue );
232233
233234 // verifica se há calculo de retenção de ISS personalizado
234- $ customIssHeld = $ this ->aliquotsRepo ->getIssHeldByServiceCode ($ serviceCode );
235+ $ customIssHeld = $ this ->aliquotsRepo ->getIssHeldByServiceCode ($ serviceCode, $ companyId );
235236
236237 /**
237238 * se não houver retenção personalizada e houver retenção global diferente de zero, usa valor global
@@ -258,19 +259,19 @@ private function buildItemsToTransmit($items, $invoiceId, $userId, $reissue = fa
258259
259260 /**
260261 * Gera um ID único para cada nota. O valor resultante é o md5 da combinação da constante inicial WHMCS
261- * seguido do ID do usuário, ID da fatura e total dos itens.
262+ * seguido do ID do usuário, ID da fatura, ID da empresa, Código do servico e total dos itens.
262263 * Nesta lógica cada conjunto de itens faturado possuirá um ID único evitando que seja inserido na fila
263264 * de emissão itens que porventura já tenham sido transmitidos ou gerados.
264- * Estrutura: WHMCS-[USER_ID]-[INVOICE_ID]-[TOTAL]
265- * Exemplo: WHMCS-13-113-131
265+ * Estrutura: WHMCS-[USER_ID]-[INVOICE_ID]-[COMPANY_ID]-[SERVICE_CODE]-[ TOTAL]
266+ * Exemplo: WHMCS-15-123-a15t...-0103-321
266267 * Resultado: número hexadecimal de 32 caracteres
267268 *
268269 * @param $userId
269270 * @param $invoiceId
270271 * @param $itemsTotal
271272 * @return string
272273 */
273- private function generateUniqueExternalId ($ userId , $ invoiceId , $ itemsTotal , $ reissue = false )
274+ private function generateUniqueExternalId ($ userId , $ invoiceId , $ itemsTotal , $ companyId , $ serviceCode , $ reissue = false )
274275 {
275276 $ separator = '- ' ;
276277 $ prefix = 'WHMCS ' ;
@@ -281,9 +282,9 @@ private function generateUniqueExternalId($userId, $invoiceId, $itemsTotal, $rei
281282 $ suffix = 'REISSUE ' ;
282283 // usa um timestamp para tornar cada reemissão unica para a criação do ID
283284 $ dateTimeNow = date ('Y-m-d H:i:s ' );
284- $ result = md5 ($ prefix . $ separator . $ userId . $ separator . $ invoiceId . $ separator . $ itemsTotal . $ separator . $ suffix . $ separator . $ dateTimeNow );
285+ $ result = md5 ($ prefix . $ separator . $ userId . $ separator . $ invoiceId . $ separator . $ companyId . $ separator . $ serviceCode . $ separator . $ itemsTotal . $ separator . $ suffix . $ separator . $ dateTimeNow );
285286 } else {
286- $ result = md5 ($ prefix . $ separator . $ userId . $ separator . $ invoiceId . $ separator . $ itemsTotal );
287+ $ result = md5 ($ prefix . $ separator . $ userId . $ separator . $ invoiceId . $ separator . $ companyId . $ separator . $ serviceCode . $ serviceCode . $ itemsTotal );
287288 }
288289
289290 return $ result ;
@@ -304,15 +305,39 @@ private function generateUniqueExternalId($userId, $invoiceId, $itemsTotal, $rei
304305 public function queue ($ invoiceId , $ reissue = false )
305306 {
306307 $ invoiceData = \WHMCS \Billing \Invoice::find ($ invoiceId );
308+ $ companyRepository = new \NFEioServiceInvoices \Models \Company \Repository ();
309+ $ clientCompanyRepository = new \NFEioServiceInvoices \Models \ClientCompany \Repository ();
310+
311+ $ defaultCompany = $ companyRepository ->getDefaultCompany ();
307312 $ invoiceItems = $ invoiceData ->items ()->get ();
308313 $ clientData = $ invoiceData ->client ()->get ();
309- $ userId = $ clientData [0 ]['id ' ];
310- $ defaultServiceCode = $ this ->storage ->get ('service_code ' );
314+
315+ $ clientId = $ clientData [0 ]['id ' ];
316+ $ clientCompanyId = $ clientCompanyRepository ->getCompanyByClientId ($ clientId );
317+
318+ // se cliente possuir empresa associada, utiliza a empresa associada, senao usa a empresa padrão
319+ // #163
320+ if ($ clientCompanyId ) {
321+ // define a empresa emissora como a empresa associada ao cliente
322+ $ companyId = $ clientCompanyId ;
323+ // recupera o codigo de servico padrao da empresa associada ao cliente
324+ $ defaultServiceCode = $ companyRepository ->getDefaultServiceCodeByCompanyId ($ clientCompanyId );
325+ // recupera o iss retencao padrao da empresa associada ao cliente
326+ $ issHeld = $ companyRepository ->getDefaultIssHeldByCompanyId ($ clientCompanyId );
327+ } else {
328+ // dados da empresa padrao
329+ $ companyId = $ defaultCompany ->company_id ;
330+ $ defaultServiceCode = $ defaultCompany ->service_code ;
331+ $ issHeld = $ defaultCompany ->iss_held ;
332+ }
333+
334+ // $defaultServiceCode = $this->storage->get('service_code');
311335 $ itemsByServiceCode = [];
312336
313337 // percorre cada item da fatura para preparar as agregações de items por tipo de serviço
314338 foreach ($ invoiceItems as $ item ) {
315- // código do serviço recebe o valor padrão
339+ // essencial que código do serviço receba o valor padrão
340+ // para cada passada do laco
316341 $ serviceCode = $ defaultServiceCode ;
317342
318343 // se o item for juros/mora automática do WHMCS, não considera para fins de cálculo de nota
@@ -322,17 +347,17 @@ public function queue($invoiceId, $reissue = false)
322347
323348 // se o item tiver um 'relid' e seu tipo for uns dos permitidos verifica se tem código personalizado
324349 if ($ item ->relid != 0 and $ this ->allowedItemType ($ item ->type )) {
325- $ customServiceCode = $ this ->productCodeRepo ->getServiceCodeByRelId ($ item ->relid );
350+ $ customServiceCode = $ this ->productCodeRepo ->getServiceCodeByRelId ($ item ->relid , $ companyId );
326351 if ($ customServiceCode ) {
327352 $ serviceCode = $ customServiceCode ;
328353 }
329354 }
330355
331356 // prepara o item e o adiciona em um array associativo com o código do serviço
332- $ itemsByServiceCode [$ serviceCode ][] = $ this ->prepareItemsToTransmit ($ userId , $ invoiceId , $ serviceCode , $ item );
357+ $ itemsByServiceCode [$ serviceCode ][] = $ this ->prepareItemsToTransmit ($ clientId , $ invoiceId , $ serviceCode , $ item );
333358 }
334359
335- $ nfToEmit = $ this ->buildItemsToTransmit ($ itemsByServiceCode , $ invoiceId , $ userId , $ reissue );
360+ $ nfToEmit = $ this ->buildItemsToTransmit ($ itemsByServiceCode , $ invoiceId , $ clientId , $ companyId , $ issHeld , $ reissue );
336361
337362 if (count ($ nfToEmit ) > 0 ) {
338363 foreach ($ nfToEmit as $ nf ) {
@@ -369,6 +394,7 @@ public function emit($data)
369394 $ amount = $ data ->services_amount ;
370395 $ serviceCode = $ data ->service_code ;
371396 $ issAmountWithheld = $ data ->iss_held ;
397+ $ companyId = $ data ->company_id ;
372398 $ description = $ data ->nfe_description ;
373399 $ environment = $ data ->environment ;
374400 $ clientData = \WHMCS \User \Client::find ($ clientId );
@@ -452,7 +478,7 @@ public function emit($data)
452478 $ postData ['issAmountWithheld ' ] = $ issAmountWithheld ;
453479 }
454480
455- $ nfeResponse = $ this ->legacyFunctions ->gnfe_issue_nfe ($ postData );
481+ $ nfeResponse = $ this ->legacyFunctions ->gnfe_issue_nfe ($ postData, $ companyId );
456482
457483 if (!$ nfeResponse ->message ) {
458484 $ this ->legacyFunctions ->gnfe_update_nfe ($ nfeResponse , $ clientId , $ invoiceId , 'n/a ' , $ nfDbId );
@@ -521,10 +547,11 @@ public function reissueNfbyId($nfId)
521547 $ environment = $ nfData ->environment ;
522548 $ issueNoteConditions = $ nfData ->issue_note_conditions ;
523549 $ serviceCode = $ nfData ->service_code ;
550+ $ companyId = $ nfData ->company_id ;
524551 $ tics = $ nfData ->tics ;
525552 $ dateNow = date ('Y-m-d H:i:s ' );
526553 // gera um novo ID externo unico para a reemissão do item/NF
527- $ externalUniqueId = $ this ->generateUniqueExternalId ($ userId , $ invoiceId , $ amount , true );
554+ $ externalUniqueId = $ this ->generateUniqueExternalId ($ userId , $ invoiceId , $ amount , $ companyId , $ serviceCode , true );
528555
529556 $ reissueNfData = [
530557 'invoice_id ' => $ invoiceId ,
@@ -543,6 +570,7 @@ public function reissueNfbyId($nfId)
543570 'created_at ' => $ dateNow ,
544571 'updated_at ' => 'waiting ' ,
545572 'service_code ' => $ serviceCode ,
573+ 'company_id ' => $ companyId ,
546574 'tics ' => ' ' ,
547575 ];
548576
@@ -655,10 +683,9 @@ public function cancelNfSeriesByInvoiceId($invoiceId)
655683 }
656684 }
657685
658- public function fetchNf ($ nfId )
686+ public function fetchNf ($ nfId, $ companyId )
659687 {
660688 $ apiKey = $ this ->storage ->get ('api_key ' );
661- $ companyId = $ this ->storage ->get ('company_id ' );
662689
663690 try {
664691 \NFe_io::setApiKey ($ apiKey );
0 commit comments