Duffer Derek

Current Path : /var/www/invoice-sync.bitkit.dk/httpdocs/app/Http/Controllers/
Upload File :
Current File : /var/www/invoice-sync.bitkit.dk/httpdocs/app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use App\Exceptions\InvoiceNotFoundException;
use App\Exceptions\PodioAttributeNotFoundException;
use App\Exceptions\PodioItemCreationFailedException;
use App\Exceptions\ProcessFailedException;
use App\Http\Modules\ApiWrapper\EconomicApi;
use App\Http\Modules\ApiWrapper\PodioApi;
use App\Http\Modules\Auth\PodioAuthentication;
use App\Http\Modules\DataFormatter\ToPodio\BookedCreditNote;
use App\Http\Modules\DataFormatter\ToPodio\BookedInvoice;
use App\Mail\ErrorMail;
use App\Models\Client;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use PodioApp;
use PodioFile;
use PodioItem;
use PodioItemDiff;
use PodioItemRevision;

class TestController
{
    private $economicApi, $podioApi;

    public function __construct()
    {
        $this->economicApi = new EconomicApi();
        $this->podioApi = new PodioApi();
    }

    public function getProductDetails()
    {
        $endPoint = 'products/9000';
        $response = $this->economicApi->callCurlApi($endPoint);
        dd($response);
    }

    public function getinvoiceDetails()
    {

        // $endPoint = '/invoices/drafts/1';
        $endPoint = '/invoices/booked/5234';
        //        $endPoint = '/accounts/5820/accounting-years/2023/periods/accountingYearPeriod/totals';
        //        $endPoint = ' /accounting-years';
        $response = $this->economicApi->callCurlApi($endPoint);
        Log::debug($response);
        dd($response);
        print_r($response);
    }

    public function getDraftNo()
    {
        $endPoint = 'invoices/drafts?filter=soap.currentInvoiceHandle.id$eq:31';
        $response = $this->economicApi->callCurlApi($endPoint);
        dd($response);
        $draftNo = null;
        foreach ($response['collection'] as $r) {
            if ($r['soap']['currentInvoiceHandle']['id'] == (int)900) {
                $draftNo = $r['draftInvoiceNumber'];
            }
        }
        dd($draftNo);
    }

    public function getPdf()
    {
        try {
            $service_url = "https://restapi.e-conomic.com/invoices/drafts/4915/pdf";
            $appSecretToken = config('general.economic.appSecretToken');
            $grantToken = config('general.economic.grantToken');
            $header = [
                'X-AppSecretToken:' . $appSecretToken,
                'X-AgreementGrantToken:' . $grantToken,
                'Content-Type:application/json'
            ];

            $tempFileName = storage_path('app/' . uniqid(rand(), true) . ".pdf");
            //filehandle
            $fp = fopen($tempFileName, 'w+');

            if ($fp === false) {
                throw new Exception('Could not open: ' . $tempFileName);
            }

            $curl = curl_init($service_url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_FILE, $fp);
            curl_exec($curl);
            if (curl_errno($curl)) {
                throw new Exception(curl_error($curl));
            }
            //Get the HTTP status code.
            $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);

            fclose($fp);

            if ($statusCode == 200) {
                echo 'Downloaded!';
            } else {
                echo "Status Code: " . $statusCode;
            }
        } catch (\Exception $e) {
            Log::info($e);
        }
    }

    public function validateHook()
    {
        try {
            $podioApi = new \App\Http\Modules\Auth\PodioAuthentication();
            $podioApi->authenticatePodio();
            $res = \PodioHook::validate(22517684, array('code' => 'a1c8326b'));
            dd($res);
        } catch (\Exception $e) {
            Log::info($e);
        }
    }

    public function getVatZones()
    {
        $endPoint = '/vatZones';
        $response = $this->economicApi->callCurlApi($endPoint);
        dd($response);
    }

    //copying references from duplicate to original client
    public function cleanUpClients()
    {
        try {
            $podioAuth = new PodioAuthentication();
            $podioAuth->authenticatePodio();

            Log::info('******************************************************************************************');
            $referencedItems = \PodioItem::get_references(143285483);
            foreach ($referencedItems as $referencedItem) {
                if ($referencedItem['app']['app_id'] == 1586143) {
                    $originalClientItem = $referencedItem['items'][0]['item_id'];
                }
            }

            Log::debug('Original Client: ' . $originalClientItem);

            //Duplicate ITem
            if ($originalClientItem) {
                foreach ($referencedItems as $referencedItem) {
                    $referItems = [];
                    $appId = $referencedItem['app']['app_id'];
                    if ($appId != 1586143) {
                        $temp = [];
                        $temp['app_id'] = $appId;
                        $temp['external_id'] = $referencedItem['field']['external_id'];
                        $temp['field_id'] = $referencedItem['field']['field_id'];
                        foreach ($referencedItem['items'] as $item)
                            $temp['items'][] = $item['item_id'];

                        $referItems[] = $temp;

                        Log::info('---------------------------------------');
                        Log::info('Referenced item list in App : ' . $referItems[0]['app_id']);
                        Log::debug($referItems);

                        //fetching existing items in the referred fields
                        foreach ($referItems as $referItem) {
                            $i = 0;
                            foreach ($referItem['items'] as $item_id) {
                                $i++;
                                Log::info($i . ' ------------' . $item_id);
                                $fieldValues = \PodioItem::get_field_value($item_id, $referItem['field_id']);
                                $existingItem = [];
                                foreach ($fieldValues as $values) {
                                    $existingItem[] = $values['value']['item_id'];
                                }

                                Log::debug('existing items');
                                Log::debug($existingItem);
                                $existingItem[] = $originalClientItem;

                                //updating the original client item along with existing items in the referenced Items
                                $attributes = [
                                    'fields' => [
                                        $referItem['external_id'] => $existingItem
                                    ]
                                ];
                                Log::debug('==UPDATE==');
                                Log::debug($attributes);
                                try {
                                    \PodioItem::update($item_id, $attributes, ['silent' => true, 'hook' => false]);
                                } catch (\PodioForbiddenError $e) {
                                    Log::info($e->getMessage());
                                }
                            }
                        }
                    }
                }
            }
            exit;
            // }

        } catch (\PodioForbiddenError $e) {
            Log::info($e->getMessage());
        }
    }

    public function createTicket($itemId, $revId)
    {
        $podioAuth = new PodioAuthentication();
        $podioAuth->authenticatePodio();
        $createTicket = false;
        $continue = false;
        $registryItemPresent = false;
        $registerItems = [];

        $revMade = PodioItemDiff::get_for($itemId, $revId - 1, $revId);
        $config = [];

        foreach ($revMade as $rev) {
            if ($rev->external_id == 'automation-create-ticket' && $rev->to[0]['value']['id'] == 1)
                $continue = true;
        }

        if ($continue) {
            $sliceItemDetails = \PodioItem::get($itemId);

            $slice = [];
            foreach ($sliceItemDetails->fields as $field) {
                switch ($field->external_id) {
                    case 'project':
                    case 'client':
                        $slice[$field->external_id] = $field->values[0]->item_id;
                        break;
                    case 'link-to-client-or-support-ticket':
                        $slice[$field->external_id] = $field->values[0]->embed_id;
                        break;
                }
            }

            //if no client ticket is attached, then create new ticket
            if (!isset($slice['link-to-client-or-support-ticket'])) {
                if ($slice['project']) {
                    $projectReferences = \PodioItem::get_references($slice['project']);
                    foreach ($projectReferences as $reference) {
                        if ($reference['app']['app_id'] == 23183637) {
                            $registryItemPresent = true;
                            $registerItems = array_reverse($reference['items']);
                            $createTicket = true;
                        } else {
                            Log::info('No registry item added for the Project.');
                        }
                    }
                    if (!$createTicket) {
                        $projectDetails = PodioItem::get($slice['project']);
                        foreach ($projectDetails->fields as $field) {
                            if ($field->external_id == 'client') {
                                $client = $field->values[0]->item_id;
                                if ($client) {
                                    Log::info('Checking for Registry item related to client');
                                    $clientReference = \PodioItem::get_references($client);
                                    foreach ($clientReference as $reference) {
                                        if ($reference['app']['app_id'] == 23183637) {
                                            $registryItemPresent = true;
                                            $registerItems = array_reverse($reference['items']);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    dd($config);
                } else if (isset($slice['client'])) {
                    exit;
                } else {
                    /**
                     * add comment to add either project or client item in the slice to enable the ticket creation from the slice
                     */
                    $message = "Please add the related project item in the slice";
                    \PodioComment::create('item', $itemId, $message);
                }
            } else {
                dd('ticket is already created for this slice');
            }

            if ($registryItemPresent == true) {
                $latest = array_pop($registerItems);

                $configItemID = $latest['item_id'];
                $configItemDetails = \PodioItem::get($configItemID);

                foreach ($configItemDetails->fields as $field) {
                    switch ($field->external_id) {
                        case 'workspace-status':
                            $config[$field->external_id] = $field->values[0]['text'];
                            break;
                        case 'client-ticket-app-id':
                        case 'title-field-external-id':
                        case 'description-field-external-id':
                        case 'project-field-external-id':
                        case 'hours-usedneeded-field-external-id':
                        case 'status-field-external-id':
                        case 'responsible-field-external-id':
                            $config[$field->external_id] = $field->values;
                            break;
                    }
                }
                if (array_key_exists('workspace-status', $config)) {
                    if ($config['workspace-status'] == 'Active') {
                        $this->createTicketFromSlice($itemId, $config);
                    }
                } else
                    Log::info('Workspace Status is no updated in the registry item');
            } else
                Log::info('No related registry item is added');
        }
    }

    public function createTicketFromSlice($sliceItemID, $config)
    {
        $sliceData = \PodioItem::get($sliceItemID);
        $slice = [];
        foreach ($sliceData->fields as $field) {
            switch ($field->external_id) {
                case 'title':
                case 'coa':
                case 'quote-to-the-client': //integer_duration_in_seconds
                case 'name':
                case 'email':
                case 'ticket-id':
                    $slice[$field->external_id] = strip_tags($field->values);
                    break;
                case 'project': //app
                    $slice[$field->external_id] = $field->values[0]->item_id;
                    break;
                case 'status':
                    $slice[$field->external_id] = $field->values[0]['text'];
                    break;
                case 'ticket-created-date':
                    $fieldValue = $field->values;
                    if (isset($fieldValue['start'])) {
                        $slice[$field->external_id] = $fieldValue['start']->format('Y-m-d');
                    }
                    break;
                case 'assigned-to':
                    $responsible = [];
                    foreach ($field->values as $value) {
                        $responsible[] = $value->profile_id;
                    }
                    $slice[$field->external_id] = $responsible;
                    break;
            }
        }

        $status = [1];

        //create ticket attributes.
        $fields = [
            $config['title-field-external-id'] => $slice['title'] . ' - ' . $slice['ticket-id'] . ' - ' . $slice['ticket-created-date'],
            $config['description-field-external-id'] => $slice['coa'],
            $config['hours-usedneeded-field-external-id'] => intval($slice['quote-to-the-client']),
            $config['status-field-external-id'] => $status,
            $config['responsible-field-external-id'] => $slice['assigned-to'],
            $config['project-field-external-id'] => $slice['project'],
            'email' => $slice['email'] ?? NULL,
            'name' => $slice['name'] ?? NULL,
        ];

        $attributes = [
            'fields' => array_filter($fields)
        ];
        //        dd($attributes);
        echo ($config['client-ticket-app-id']);
        try {
            $ticket = \PodioItem::create($config['client-ticket-app-id'], $attributes, ['silent' => false, 'hook' => false]);
            Log::info('Creating New Ticket : ' . $ticket->item_id);
            $this->addFilesToTicket($sliceItemID, $ticket);
        } catch (\Exception $e) {
            Log::info($e);
        }
    }

    public function addFilesToTicket($sliceItemId, $ticket)
    {
        try {
            $sliceData = PodioItem::get($sliceItemId);
            $fileIDs = array();
            if ($sliceData->files && count($sliceData->files) > 0) {
                foreach ($sliceData->files as $file) {
                    $fileIDs[$file->file_id] = $file->name;
                }
            }

            $newFIles = array();
            if (count($fileIDs) > 0) {
                foreach ($fileIDs as $fileID => $missingFile) {
                    $file = PodioFile::get($fileID);
                    $extension_pos = strrpos($file->name, '.'); // find position of the last dot, so where the extension starts
                    $fileName = substr($file->name, 0, $extension_pos) . '_' . $file->file_id . substr($file->name, $extension_pos);
                    $destinationPath = public_path() . "/" . $fileName;
                    $fileDetails = PodioFile::get($file->file_id);
                    $fileContent = $fileDetails->get_raw();
                    file_put_contents($destinationPath, $fileContent);
                    $newFIle = PodioFile::upload($destinationPath, $fileName);
                    $fileId = $newFIle->file_id;
                    array_push($newFIles, $fileId);
                }
            }
            if (count($newFIles) > 0) {
                PodioItem::update($ticket->item_id, array("file_ids" => $newFIles));
            }
        } catch (\Exception $e) {
            dd($e);
        }
    }

    public function checkDataCopy()
    {
        $podioAuth = new PodioAuthentication();
        $podioAuth->authenticatePodio();

        $batchDetails = \PodioBatch::get_all(); // return batches in descending order
        //   $latestBatches = array_slice($batchDetails, 0, 5); // taking the latest 5 batches

        $newAppId = 1586143;
        $i = 0;
        foreach ($batchDetails as $batch) {
            //            if ($batch->app->app_id == $newAppId && $batch->status == 'completed' && $i == 0) {
            if ($batch->app->app_id == $newAppId && $batch->status == 'completed') {
                Log::info('******* Entering 1st if *******');
                if ($batch->completed >= 719) {
                    Log::info('Entering 2nd if');
                    $this->doNext();
                    //                    break;
                } else {
                    Log::info('Entering 2nd else');
                    $this->doNext();
                    //                    break;
                }
                $i++;
            } else {
                Log::info('Entering 1st else');
                $this->doNextElse();
            }
            //            if ($i == 1) {
            //                Log::info('Condition $i==1');
            //                break;
            //            }
            Log::info('Exiting for loop');
        }
        Log::info('Function exit');
    }

    public function doNext()
    {
        Log::info('Enter donext');
    }

    public function doNextElse()
    {
        Log::info('Enter doNextElse');
    }

    public function updateTotHoursNorman($configItemIdInSales)
    {

        try {
            //   Log::info('updateTotHoursUsed : ' . $configItemId);
            $configItemDetails = \PodioItem::get($configItemIdInSales);

            $ticketAppId = null;
            $totalHours = 0;

            foreach ($configItemDetails->fields as $field) {
                switch ($field->external_id) {
                    case 'client-ticket-app-id':
                        $ticketAppId = $field->values;
                        break;
                    case 'client-ticket-workspace-id':
                        $spaceId = $field->values;
                        break;
                }
            }

            Log::info('ticketApp: ' . $ticketAppId);
            $appDetails = PodioApp::get($ticketAppId);
            if ($appDetails->status == 'active') {

                $filters = $this->getConfigFilter($configItemIdInSales, $ticketAppId);
                //                Log::debug($filters);

                //Ticket WS

                $limit = 200;
                $offset = 0;
                $filtered = 0;
                $count = $offset;
                do {
                    $attrib = array(
                        'filters' => $filters,
                        'limit' => $limit,
                        'offset' => $offset
                    );
                    $itemCollection = \PodioItem::filter($ticketAppId, $attrib, $options = array());
                    Log::debug(count($itemCollection));

                    foreach ($itemCollection as $item) {

                        //ticket Details
                        $itemId = $item->item_id;
                        //                    Log::info($itemId);

                        $ticketItemDetails = \PodioItem::get($itemId);
                        $invoiceStatus = null;
                        $ticketStatus = null;
                        $title = null;

                        $ticket = [];
                        foreach ($ticketItemDetails->fields as $field) {
                            switch ($field->external_id) {
                                case 'status':
                                case 'ticket-status-2':
                                    $ticket[$field->external_id] = $field->values[0]['text'];
                                    $ticketStatus = $field->values[0]['text'];
                                    break;
                                case 'invoiced':
                                case 'invoice-status':
                                case 'invoiced-2':
                                    $ticket[$field->external_id] = $field->values[0]['text'];
                                    $invoiceStatus = $field->values[0]['text'];
                                    break;
                                case 'hours-usedneeded':
                                case 'hours-neededused':
                                case 'pm-hours':
                                case 'hours-used-within-contract':
                                case 'estimated-hours':
                                case 'estimated-effort':
                                case 'duration':
                                case 'dev-hours':
                                    $ticket[$field->external_id] = $field->values; //integer_duration_in_seconds
                                    break;
                                case 'ticket-type':
                                    $ticket[$field->external_id] = $field->values[0]['text'];
                                    break;
                            }
                        }
                        //                        Log::debug($ticket);
                        if ($ticketAppId == 24955821 && $ticket['ticket-type'] == 'Yes') {
                            if ($ticketStatus == 'Finished and approved by client' && $invoiceStatus == 'No') {

                                if (array_key_exists('hours-usedneeded', $ticket))
                                    $totalHours += $ticket['hours-usedneeded'];
                                if (array_key_exists('pm-hours', $ticket))
                                    $totalHours += $ticket['pm-hours'];
                                if (array_key_exists('hours-used-within-contract', $ticket))
                                    $totalHours += $ticket['hours-used-within-contract'];
                                if (array_key_exists('estimated-hours', $ticket))
                                    $totalHours += $ticket['estimated-hours'];
                                if (array_key_exists('estimated-effort', $ticket))
                                    $totalHours += $ticket['estimated-effort'];
                                if (array_key_exists('duration', $ticket))
                                    $totalHours += $ticket['duration'];
                                if (array_key_exists('hours-neededused', $ticket))
                                    $totalHours += $ticket['hours-neededused'];
                            }
                        }
                    }
                    if ($filtered == 0) {
                        $filtered = $itemCollection->filtered;
                    }
                    $count += count($itemCollection);
                    $offset += $limit;
                } while ($count < $filtered);
            }

            $attributes = [
                'fields' => [
                    'hours-to-invoice-2' => $totalHours
                ]
            ];
            try {
                //  \PodioItem::update($configItemIdInSales, $attributes, ['silent' => true, 'hook' => false]);
            } catch (\PodioForbiddenError $e) {
                Log::info($e->getMessage() . ' : ' . $configItemIdInSales);
            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
        }

        //
        dd($totalHours);
    }

    public function getConfigFilter($configItemId, $ticketAppId): array
    {
        $filters = [];
        switch ($configItemId) {
            case 2565425138: // DMK UK - EAGC
            case 2565425139: //DMK UK - GASTECH
            case 2565425175: //DMG Canada - New Workspace
                if ($ticketAppId == 25048789) {
                    $filters = [
                        'status-' => 4,
                        'invoiced' => 1,
                    ];
                } else {
                    $filters = [
                        'ticket-status-2' => 4,
                        'invoiced' => 1,
                    ];
                }
                break;
            case 2565425067: //Rebit
                $filters = [
                    'status-2' => 4,
                    'invoiced' => 1,
                ];
                break;
            case 2565425058: //Property Seller Solutions
            case 2565425104: //Partner WorkWays (Benedixkiel)
                $filters = [
                    'status' => 4,
                    'invoice-status' => 1,
                ];
                break;
            case 2565424981: //3dplans
            case 2565425044: //Korsager
            case 2565425080: //Sorgem
                $filters = [
                    'status' => 4,
                    'invoiced-2' => 1,
                ];
                break;
            case 2565425090: //Norman WS - invoiced=no && billable-yes
                $filters = [
                    'is-billable' => 1,
                    'invoiced' => 1,
                ];
                break;
            case 2565425163: //DMG Dubai - invoiced=no && billable-yes
                $filters = [
                    'status' => 4,
                    'invoiced' => 1,
                    'ticket-type' => 1
                ];
                break;
            default:
                $filters = [
                    'status' => 4,
                    'invoiced' => 1,
                ];
                break;
        }
        return $filters;
    }

    public function attachPDF($accessToken)
    {
        echo 'Hi';

        $service_url = "https://restapi.e-conomic.com/invoices/drafts/5/attachment/file";
        $appSecretToken = config('general.economic.appSecretToken');
        $grantToken = config('general.economic.grantToken');
        $header = [
            'X-AppSecretToken:' . $appSecretToken,
            'X-AgreementGrantToken:' . $grantToken,
            'Content-Type:multipart/form-data'
        ];


        $curl = curl_init($service_url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl, CURLOPT_POSTFIELDS, array(
            'data' =>
            curl_file_create('/home/chinnu/Documents/PHP_WORKS/Economic Integration/MK/mk-economic-integration/public/ordre-maleropgave-49-18072021.pdf')
        )); //check if it works with podio link so can avoid download
        curl_exec($curl);
        if (curl_errno($curl)) {
            throw new Exception(curl_error($curl));
        }
        //Get the HTTP status code.
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        echo ($statusCode);

        if ($statusCode == 200) {
            echo 'Downloaded!';
            //            unlink($destinationPath);
        } else {
            echo "Status Code: " . $statusCode;
        }
        //        } catch (Exception $e) {
        //            Log::info($e);
        //        }
    }


    /**
     * For syncing missed invoices boked from economic to podio
     */
    public function syncBookedInvoice($bookedInvoice): void
    {
        try {
            Log::info($bookedInvoice['bookedInvoiceNumber']);
            if (strpos($bookedInvoice['grossAmount'], '-') !== false) {  //creditNote sync

                $toPodio = new BookedCreditNote($bookedInvoice);
                $attributes = $toPodio->getData();
            } else {   // Invoice Sync
                $toPodio = new BookedInvoice($bookedInvoice);
                $attributes = $toPodio->getData();
            }
            $options = ['silent' => true, 'hook' => false];
            if (!$attributes) {
                throw new PodioAttributeNotFoundException('No attributes Provided');
            }
            Log::debug($attributes);
            // exit;
            $response = $this->podioApi->podioItemCreate(config('podio.app_auth.invoice.app_id'), $attributes, $options);
            Log::debug($response);
            if ($response == null) {
                throw new PodioItemCreationFailedException('Failed to create invoice item in podio');
            }
        } catch (Exception $e) {
            Log::info($e);
            dd($e->getMessage());
        }
    }
}

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists