This commit is contained in:
Michael 2024-07-22 14:17:00 +02:00
parent a15319c4d1
commit eebf859afa
39 changed files with 2742 additions and 937 deletions

View File

@ -1,14 +0,0 @@
APP_NAME=Lumen
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_TIMEZONE=UTC
APP_PASSWORD=
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=
GITEA_ORGANIZATION=
GITEA_URL=
GITEA_TOKEN=

View File

@ -9,7 +9,7 @@ class CheckSimpleAuthController extends Controller
{
public function check(Request $req) {
if (
getenv('GITEA_ORGANIZATION') === $req->input('organization')
getenv('GITEA_PARTNER_ORGANIZATION') === $req->input('organization')
&&
getenv('APP_PASSWORD') === $req->input('password')
) {

View File

@ -0,0 +1,84 @@
<?php
namespace App\Http\Controllers\CsvController;
use App\Http\Controllers\Controller;
use Error;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Writer\Ods;
use RuntimeException;
class CsvController extends Controller
{
private $csv_data_init;
private $csv_data_handling;
public function __construct()
{
$this->csv_data_init = new CsvDataInit();
$this->csv_data_handling = new CsvDataHandling();
$this->third_party_integrations_allow = env('THIRD_PARTY_INTEGRATIONS_ALLOW', false);
}
function create_columns(array $issue, array $issue_time, array $company_agents = [])
{
try {
$array = $this->csv_data_init->initialize_csv_data($issue);
$array = $this->csv_data_init->handle_labels($array, $issue['labels']);
$array = $this->csv_data_handling->handle_csv_time($array, $issue, $issue_time, $company_agents);
return $array;
} catch (Error $e) {
Log::error('E-CSV-COLUMNS - ' . $e->getMessage());
throw new RuntimeException("E-CSV-GEN");
}
}
private function create_calc_document($reader, $file_name, $is_xls = false)
{
// Determine the appropriate writer based on the file type
$file_extension = $is_xls ? '.xls' : '.csv';
$writerClass = $is_xls ? Xls::class : Csv::class;
// Create the writer instance
$writer = new $writerClass($reader);
$file_name = $file_name . $file_extension;
$file_path = storage_path() . '/app/' . $file_name;
$writer->save($file_path);
//Define header information
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: 0");
header('Content-Disposition: attachment; filename="' . basename($file_name) . '"');
header('Content-Length: ' . filesize($file_path));
header('Pragma: public');
//Terminate from the script
return ['file_name' => $file_name, 'file_path' => $file_path];
}
function create_csv(string $issues_params_state, string $from_date, string $to_date, array $data)
{
try {
$file_name = $issues_params_state . "_issues_from_" . $from_date . "_to_" . $to_date;
$reader = new Spreadsheet();
$spreadsheet = $reader->getActiveSheet();
$headers = array_keys($data[0]);
$data_new = array_unshift($data, $headers);
$spreadsheet->fromArray(
$data
);
// The code is enclosed in a function for eventual support of multiple file types as xls and ods, as of now a csv will be generated
$csv_file = $this->create_calc_document($reader, $file_name);
// $ods_file = $this->third_party_integrations_allow ? $this->create_calc_document($reader, $file_name) : null;
return $csv_file;
} catch (Error $e) {
Log::error('E-CSV-GEN - ' . $e->getMessage());
throw new RuntimeException("E-CSV-GEN");
}
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers\CsvController\CsvCostCalc;
class CsvAgentCost
{
private $internal_percentage_to_deduct;
private $CsvMinuteCostCalc;
public function __construct()
{
$this->internal_percentage_to_deduct = getenv('PRICE_INTERNAL_PERCENTAGE_TO_DEDUCT');
$this->partner_organitation = strtolower(getenv('GITEA_PARTNER_ORGANIZATION'));
$this->CsvMinuteCostCalc = new CsvMinuteCostCalc();
}
private function preapare_agents_columns(array $array, array $company_agents)
{
//Add all agents columns
foreach ($company_agents as $company_agent) {
$array[$company_agent] = '';
$array[$company_agent . ' costo'] = 0;
}
return $array;
}
private function calculate_agents_cost(array $array, array $agents_time, float $minute_cost)
{
foreach ($agents_time as $name => $agent_time) {
//Identify agents involved in the issue
$array[$name] = gmdate('H:i:s', $agent_time);
$array[$name . ' costo'] = $agent_time / 60 * $minute_cost;
}
return $array;
}
function agent_cost_calc(array $array, array $company_agents, array $agents_time)
{
$array = $this->preapare_agents_columns($array, $company_agents);
//Calculate cost, subtract a % from the minute_cost
$minute_cost = $this->CsvMinuteCostCalc->select_correct_cost($array['Request By'], $array['Priority']);
$minute_cost = $minute_cost - ($minute_cost / 100 * $this->internal_percentage_to_deduct);
$array = $this->calculate_agents_cost($array, $agents_time, $minute_cost);
return $array;
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers\CsvController\CsvCostCalc;
class CsvCostCalc
{
public function __construct()
{
$this->internal_percentage_to_deduct = getenv('PRICE_INTERNAL_PERCENTAGE_TO_DEDUCT');
$this->partner_organitation = strtolower(getenv('GITEA_PARTNER_ORGANIZATION'));
$this->CsvAgentCost = new CsvAgentCost();
$this->CsvTotalCostCalc = new CsvTotalCostCalc();
$this->CsvSumTotalsCalc = new CsvSumTotalsCalc();
}
function total_time_cost(array $array, int $total_time)
{
return $this->CsvTotalCostCalc->total_time_cost($array, $total_time);
}
function agent_cost_calc(array $array, array $company_agents, array $agents_time)
{
return $this->CsvAgentCost->agent_cost_calc($array, $company_agents, $agents_time);
}
function sum_costs(array $data, array $company_agents = [])
{
return $this->CsvSumTotalsCalc->sum_costs($data, $company_agents);
}
}

View File

@ -0,0 +1,59 @@
<?php
namespace App\Http\Controllers\CsvController\CsvCostCalc;
use Exception;
use Illuminate\Support\Facades\Log;
class CsvMinuteCostCalc
{
public function __construct()
{
$this->internal_percentage_to_deduct = getenv('PRICE_INTERNAL_PERCENTAGE_TO_DEDUCT');
$this->partner_organization = strtolower(getenv('GITEA_PARTNER_ORGANIZATION'));
$this->price_partner = [
'high' => $this->calculate_minute_cost((int)getenv('PRICE_PARTNER_HIGH')),
'normal' => $this->calculate_minute_cost((int)getenv('PRICE_PARTNER_NORMAL')),
'low' => $this->calculate_minute_cost((int)getenv('PRICE_PARTNER_LOW')),
'0'=>0,
];
$this->price_client = [
'high' => $this->calculate_minute_cost((int)getenv('PRICE_CLIENT_HIGH')),
'normal' => $this->calculate_minute_cost((int)getenv('PRICE_CLIENT_NORMAL')),
'low' => $this->calculate_minute_cost((int)getenv('PRICE_CLIENT_LOW')),
'0'=>0,
];
}
private function calculate_minute_cost(int $hourly_cost)
{
return $hourly_cost / 60;
}
private function extract_string_from_label($label)
{
return strtolower(substr($label, strpos($label, '/') + 1));
}
function select_correct_cost($requested_by, $priority)
{
$requested_by = $this->extract_string_from_label($requested_by);
$priority = $this->extract_string_from_label($priority);
$requested_by_partner = str_contains($requested_by, strtolower($this->partner_organization));
try {
$priority = match ($priority) {
'critical', 'high' => 'high',
'medium' => 'normal',
'low' => 'low',
default =>'0'
};
} catch (Exception $e) {
Log::error('E-CSV-MINUTECOSTCALC - '. $e->getMessage());
}
if ($requested_by_partner) {
return $this->price_partner[$priority];
}
return $this->price_client[$priority];
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers\CsvController\CsvCostCalc;
class CsvSumTotalsCalc
{
private $calculate_agent_cost;
public function __construct()
{
$this->calculate_agent_cost = env('GITEA_CALCULATE_AGENT_COST');
}
private function sum_total_cost(array $array)
{
(float)$total = 0;
foreach ($array as $issue_total) {
$issue_total_cost = $issue_total['Costo totale'];
$total += $issue_total_cost;
}
$totalSumCsvLine = array(
'Progetto' => '',
'#' => '',
'Titolo' => '',
'URL' => '',
'Aperto_il' => '',
'Chiuso_il' => '',
'Etichette' => '',
'Kind' => '',
'Request By' => '',
'Priority' => '',
'Tempo totale' => '',
'Costo totale' => $total,
);
array_push($array, $totalSumCsvLine);
return $array;
}
private function add_agents_csv_line($agent_struct, $last_csv_line)
{
$agents_csv_line = $last_csv_line;
foreach ($agent_struct as $agent_name => $agent_sum) {
$agents_csv_line[$agent_name] = '';
$agents_csv_line[$agent_name . ' costo'] = $agent_sum;
}
return $agents_csv_line;
}
private function init_agents_struct($company_agents){
return array_combine($company_agents, array_fill(0, count($company_agents), 0));
}
private function extract_agent_cost(array $array,array $agent_struct){
$i=0;
$issue_length = count( $array );
foreach ($array as $issue) {
if(++$i == $issue_length) break;
foreach ($agent_struct as $agent_name => $agent_sum) {
$agent_cost = $issue[$agent_name . ' costo'];
$agent_struct[$agent_name] += $agent_cost;
}
}
return $agent_struct;
}
private function sum_agents_cost($array, $company_agents)
{
$agent_struct = $this->init_agents_struct($company_agents);
$agent_struct = $this->extract_agent_cost($array, $agent_struct);
$agents_csv_line = $this->add_agents_csv_line($agent_struct, end($array));
$array[key($array)] = $agents_csv_line;
return $array;
}
function sum_costs(array $array, $company_agents = [])
{
$array = $this->sum_total_cost($array);
if ($this->calculate_agent_cost) {
$array = $this->sum_agents_cost($array, $company_agents);
}
return $array;
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Http\Controllers\CsvController\CsvCostCalc;
class CsvTotalCostCalc
{
private $CsvMinuteCostCalc;
public function __construct()
{
$this->CsvMinuteCostCalc = new CsvMinuteCostCalc();
}
function total_time_cost(array $array, int $total_time)
{
$minute_cost = $this->CsvMinuteCostCalc->select_correct_cost($array['Request By'], $array['Priority']);
$total_cost = $total_time / 60 * $minute_cost;
$array['Tempo totale'] = gmdate('H:i:s', $total_time);
$array['Costo totale'] = $total_cost;
return $array;
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace App\Http\Controllers\CsvController;
use App\Http\Controllers\CsvController\CsvCostCalc\CsvCostCalc;
class CsvDataHandling
{
private $calculate_agent_cost;
private $csv_cost_calc;
public function __construct()
{
$this->calculate_agent_cost = env('GITEA_CALCULATE_AGENT_COST');
$this->csv_cost_calc = new CsvCostCalc();
}
private function handle_agent_issue($agents_issue_time, $time)
{
$time_agent = $time['user_name'];
!array_key_exists($time_agent, $agents_issue_time) && $agents_issue_time[$time_agent] = 0;
$agents_issue_time[$time_agent] += $time['time'];
return $agents_issue_time;
}
private function get_issue_total_time(array $issue_time)
{
$total_issue_time = 0;
$agents_issue_time = [];
foreach ($issue_time as $time) {
$total_issue_time += (int)$time['time'];
$this->calculate_agent_cost && $agents_issue_time = $this->handle_agent_issue($agents_issue_time, $time);
}
return [$total_issue_time, $agents_issue_time];
}
function handle_csv_time(array $array, array $issue, array $issue_time, array $company_agents = [])
{
[$total_time, $agents_time] = $this->get_issue_total_time($issue_time);
$array = $this->csv_cost_calc->total_time_cost($array, $total_time);
if ($this->calculate_agent_cost) {
$array = $this->csv_cost_calc->agent_cost_calc($array, $company_agents, $agents_time);
}
return $array;
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers\CsvController;
class CsvDataInit
{
public function __construct()
{
}
private function get_issue_labels(array $issue)
{
$labels = '';
foreach ($issue['labels'] as $label) {
$labels .= $label['name'] . ',';
}
return $labels;
}
function handle_labels($array, $issue_labels){
foreach ($issue_labels as $key => $label) {
if (strpos($label['name'],'Kind') !== false) {
$array['Kind'] = $label['name'];
}
if (strpos($label['name'],'RequestBy') !== false) {
$array['Request By'] = $label['name'];
}
if (strpos($label['name'],'Priority') !== false) {
$array['Priority'] = $label['name'];
}
}
return $array;
}
function initialize_csv_data(array $issue){
return array(
'Progetto' => $issue['repository']['name'],
'#' => $issue['number'],
'Titolo' => $issue['title'],
'URL' => $issue['html_url'],
'Aperto_il' => $issue['created_at'],
'Chiuso_il' => $issue['closed_at'],
'Etichette' => $this->get_issue_labels($issue),
'Kind' => '',
'Request By' => '',
'Priority' => '',
);
}
}

View File

@ -1,170 +0,0 @@
<?php
namespace App\Http\Controllers;
use DateTime;
use OwenVoke\Gitea\Client;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class GiteaApiController extends Controller
{
private $giteaClient;
private $organization;
public function __construct()
{
$this->organization = getenv('GITEA_ORGANIZATION');
$this->giteaClient = new Client(null, null, getenv('GITEA_URL'));
$this->giteaClient->authenticate(getenv('GITEA_TOKEN'), null, Client::AUTH_ACCESS_TOKEN);
}
private function get_repositories()
{
$repositories = $this->giteaClient->organizations()->repositories($this->organization, 1, 9999);
return $repositories;
}
private function get_issues(string $repository, array $parameters = array())
{
return $issues = $this->giteaClient->repositories()->issues()->all($this->organization, $repository, $parameters);
}
private function get_issue_total_time(string $repository, int $id)
{
$times = $this->giteaClient->repositories()->issues()->times($this->organization, $repository, $id);
$count = 0;
foreach ($times as $time) {
$count += (int) $time['time'];
}
return $count;
}
private function get_issue_labels(array $issue)
{
$labels = '';
foreach ($issue['labels'] as $label) {
$labels .= $label['name'] . ',';
}
return $labels;
}
private function create_columns(array $issue)
{
$array = array(
'Progetto' => $issue['repository']['name'],
'#' => $issue['number'],
'Titolo' => $issue['title'],
'URL' => $issue['html_url'],
'Aperto_il' => $issue['created_at'],
'Chiuso_il' => $issue['closed_at'],
'Etichette' => $this->get_issue_labels($issue),
'Kind' => '',
'Request By' => '',
'Priority' => '',
'Tempo' => gmdate('H:i:s', $this->get_issue_total_time($issue['repository']['name'], $issue['number'])),
);
foreach ($issue['labels'] as $key => $label) {
if (strpos($label['name'],'Kind') !== false) {
$array['Kind'] = $label['name'];
}
if (strpos($label['name'],'RequestBy') !== false) {
$array['Request By'] = $label['name'];
}
if (strpos($label['name'],'Priority') !== false) {
$array['Priority'] = $label['name'];
}
}
return $array;
}
private function create_csv(string $file_name, array $data)
{
$reader = new Spreadsheet();
$spreadsheet = $reader->getActiveSheet();
$headers = array_keys($data[0]);
$data_new = array_unshift($data, $headers);
$spreadsheet->fromArray(
$data,
null,
'A1'
);
//dd($spreadsheet);
$filename = $file_name . '.xls';
$writer = new Xls($reader);
$writer->save($filename);
//Define header information
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: 0");
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Length: ' . filesize($filename));
header('Pragma: public');
//Clear system output buffer
flush();
//Read the size of the file
readfile($filename);
unlink($filename);
//Terminate from the script
die();
}
private function date_to_datetime(string $date)
{
$date = str_replace('/', '-', $date);
$datetime = new DateTime($date);
return $datetime->format('Y-m-d H:i:s');
}
private function export_issues(string $from_date, string $to_date, array $issues_params)
{
$data = array();
$repositories = $this->get_repositories();
foreach ($repositories as $repository) {
$issues = $this->get_issues($repository['name'], $issues_params);
foreach ($issues as $issue) {
$from_datetime = $this->date_to_datetime($from_date);
$to_datetime = $this->date_to_datetime($to_date);
if (substr($issue['closed_at'], 0, 19) > $from_datetime && substr($issue['closed_at'], 0, 19) <= $to_datetime) {
$data[] = $this->create_columns($issue);
}
}
}
if (count($data) > 0) {
$file_name = $issues_params['state'] . "_issues_from_" . $from_date . "_to_" . $to_date;
$this->create_csv($file_name, $data);
return true;
}
return false;
}
public function export_closed_issues(Request $req)
{
if ($req->input('token') != getenv('GITEA_TOKEN')) {
return redirect('/');
}
$from = $req->input('from_year') . '-' . $req->input('from_month') . '-01';
$to = $req->input('to_year') . '-' . $req->input('to_month') . '-31';
$res = $this->export_issues($from, $to, ['state' => $req->input('issues_type')]);
return view('backend', [
'token' => getenv('GITEA_TOKEN'),
'download' => $res
]);
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers\GiteaApiController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class GiteaApiController extends Controller
{
private $gitea_export;
public function __construct()
{
$this->gitea_export = new GiteaExport();
}
public function export_closed_issues(Request $req)
{
if ($req->input('token') != getenv('GITEA_TOKEN')) {
return redirect('/');
}
$from = $req->input('from_year') . '-' . $req->input('from_month') . '-01';
$to = $req->input('to_year') . '-' . $req->input('to_month') . '-31';
$res = $this->gitea_export->export_issues($from, $to, ['state' => $req->input('issues_type')]);
return view('backend', [
'token' => getenv('GITEA_TOKEN'),
'download' => $res
]);
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace App\Http\Controllers\GiteaApiController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CsvController\CsvController;
use App\Http\Controllers\CsvController\CsvCostCalc\CsvCostCalc;
use App\Http\Controllers\IssueValidationController;
use App\Http\Controllers\ThirdPartyServices;
use Illuminate\Support\Facades\Storage;
use OwenVoke\Gitea\Client;
class GiteaExport extends Controller
{
private $giteaClient;
private $issue_validation_controller;
private $gitea_fetch;
private $csv_controller;
private $third_party_integrations_allow;
private $calculate_agent_cost;
private $csv_cost_calc;
private $third_party_services;
private $email_send_allow;
public function __construct()
{
$this->third_party_integrations_allow = env('THIRD_PARTY_INTEGRATIONS_ALLOW', false);
$this->calculate_agent_cost = env('GITEA_CALCULATE_AGENT_COST', false);
$this->email_send_allow = env('EMAIL_SEND_ALLOW', false);
$this->email_address = env('EMAIL_ADDRESS', false);
$this->email_prefix_subject = env('EMAIL_PREFIX_SUBJECT', false);
$this->giteaClient = new Client(null, null, getenv('GITEA_URL'));
$this->giteaClient->authenticate(getenv('GITEA_TOKEN'), null, Client::AUTH_ACCESS_TOKEN);
$this->issue_validation_controller = new IssueValidationController();
$this->csv_controller = new CsvController();
$this->gitea_fetch = new GiteaFetch();
$this->csv_cost_calc = new CsvCostCalc();
$this->third_party_services = new ThirdPartyServices();
}
private function handle_repos(string $from_date, string $to_date, array $repositories, array $issues_params){
$data = [];
foreach ($repositories as $repository) {
$issues = $this->gitea_fetch->get_issues($repository['name'], $issues_params);
foreach ($issues as $issue) {
$issue_time = $this->gitea_fetch->get_issue_time($repository['name'], $issue['number']);
$issue_valid = $this->issue_validation_controller->handle_single_issue($from_date, $to_date, $issue, $issue_time);
if ($issue_valid) {
$company_agents = $this->calculate_agent_cost ? $this->gitea_fetch->get_company_agents() : [];
$data[] = $this->csv_controller->create_columns($issue, $issue_time, $company_agents);
}
}
}
return $data;
}
function export_issues(string $from_date, string $to_date, array $issues_params)
{
$repositories = $this->gitea_fetch->get_repositories();
$data = $this->handle_repos($from_date, $to_date, $repositories, $issues_params);
if (count($data) > 0) {
$company_agents = $this->calculate_agent_cost ? $this->gitea_fetch->get_company_agents() : [];
$data = $this->csv_cost_calc->sum_costs($data, $company_agents);
$csv_file = $this->csv_controller->create_csv($issues_params['state'], $from_date, $to_date, $data);
if($this->third_party_integrations_allow) {
$this->third_party_services->handle_third_party_services($csv_file['file_name'], $csv_file['file_path'], $data, $company_agents, $from_date, $to_date);
}
isset($csv_file['file_path']) ?? unlink($csv_file['file_path']);
readfile($csv_file['file_path']);
unlink($csv_file['file_path']);
return true;
}
return false;
}
}

View File

@ -0,0 +1,61 @@
<?php
namespace App\Http\Controllers\GiteaApiController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CsvController\CsvController;
use App\Http\Controllers\IssueValidationController;
use GuzzleHttp\Client as GuzzleClient;
use Illuminate\Http\Request;
use OwenVoke\Gitea\Client;
class GiteaFetch extends Controller
{
private $giteaClient;
private $partner_organization;
private $main_company_organization;
public function __construct()
{
$this->main_company_organization = getenv('GITEA_MAIN_COMPANY_ORGANIZATION');
$this->partner_organization = getenv('GITEA_PARTNER_ORGANIZATION');
$this->gitea_url = getenv('GITEA_URL');
$this->gitea_token = getenv('GITEA_TOKEN');
$this->giteaClient = new Client(null, null, $this->gitea_url);
$this->giteaClient->authenticate($this->gitea_token, null, Client::AUTH_ACCESS_TOKEN);
}
function get_repositories()
{
$repositories = $this->giteaClient->organizations()->repositories($this->partner_organization, 1, 9999);
return $repositories;
}
function get_issues(string $repository, array $parameters = array())
{
return $this->giteaClient->repositories()->issues()->all($this->partner_organization, $repository, $parameters);
}
function get_issue_time(string $repository_name, int $issue_number){
return $this->giteaClient->repositories()->issues()->times($this->partner_organization, $repository_name, $issue_number);
}
function get_company_agents()
{
$gitea_api_call_url = $this->gitea_url . '/api/v1/orgs/' . $this->main_company_organization . '/members';
$http_client = new GuzzleClient();
$res = $http_client->get($gitea_api_call_url, [
'headers' => [
'Authorization' => 'token ' . $this->gitea_token
]
]);
$responseBody = $res->getBody()->getContents();
$users = json_decode($responseBody, true);
//removes 1st user, usually it's the admin
array_shift($users);
$users = array_column($users, 'username');
return $users;
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Http\Controllers;
use DateTime;
class IssueValidationController extends Controller
{
public function __construct()
{}
private function date_to_datetime(string $date)
{
$date = str_replace('/', '-', $date);
$datetime = new DateTime($date);
return $datetime->format('Y-m-d H:i:s');
}
private function search_requested_by($issue_labels){
foreach ($issue_labels as $key => $label) {
if (strpos($label['name'],'RequestBy') !== false) {
return true;
}
}
return false;
}
private function get_issue_total_time(array $issue_time)
{
$count = 0;
foreach ($issue_time as $time) {
$count += (int) $time['time'];
}
return $count;
}
private function check_issue_is_billed(array $issue_labels, array $issue_time): bool {
$issue_time = $this->get_issue_total_time($issue_time);
$issue_time = (gmdate('H:i:s', $issue_time) !== '00:00:00');
$label_requested_by_index = $this->search_requested_by($issue_labels);
return $issue_time && $label_requested_by_index;
}
function handle_single_issue(string $from_date, string $to_date, array $issue, array $issue_time){
$from_datetime = $this->date_to_datetime($from_date);
$to_datetime = $this->date_to_datetime($to_date);
$closed_after_inital_date = substr($issue['closed_at'], 0, 19) > $from_datetime;
$closed_after_ending_date = substr($issue['closed_at'], 0, 19) <= $to_datetime;
$issue_is_billed = false;
if(isset($issue['labels']) && sizeof($issue['labels']) > 0) {
$issue_is_billed = $this->check_issue_is_billed($issue['labels'], $issue_time);
}
return $closed_after_inital_date && $closed_after_ending_date && $issue_is_billed;
}
}

View File

@ -0,0 +1,97 @@
<?php
namespace App\Http\Controllers;
use App\Mail\sendExportNotice;
use DateTime;
use Http\Discovery\Exception;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use RuntimeException;
class ThirdPartyServices extends Controller
{
private $nextcloud_url;
private $nextcloud_user;
private $nextcloud_password;
private $openproject_url;
private $openproject_user;
private $openproject_password;
private $third_party_integrations_nextcloud;
private $third_party_integrations_open_project;
public function __construct()
{
$this->third_party_integrations_nextcloud = env('THIRD_PARTY_INTEGRATIONS_NEXTCLOUD', false);
$this->third_party_integrations_open_project = env('THIRD_PARTY_INTEGRATIONS_OPEN_PROJECT', false);
$this->nextcloud_url = env('NEXTCLOUD_URL', false);
$this->nextcloud_user = env('NEXTCLOUD_USER', false);
$this->nextcloud_password = env('NEXTCLOUD_PASSWORD', false);
$this->nextcloud_upload_folder_path = env('NEXTCLOUD_UPLOAD_FOLDER_PATH', false);
$this->nextcloud_upload_folder_web_link = env('NEXTCLOUD_UPLOAD_FOLDER_WEB_LINK', false);
$this->openproject_url = env('OPENPROJECT_URL', false);
$this->openproject_token = env('OPENPROJECT_TOKEN', false);
$this->openproject_project = env('OPENPROJECT_PROJECT', false);
$this->openproject_task_name = env('OPENPROJECT_TASK_NAME', false);
$this->email_send_allow = env('EMAIL_SEND_ALLOW', false);
$this->email_address_recepient = env('EMAIL_ADDRESS_RECEPIENT', null);
$this->email_prefix_subject = env('EMAIL_PREFIX_SUBJECT', null);
}
function nextcloud_upload_csv(string $file_name, string $file_path)
{
try {
$nextcloud_url = $this->nextcloud_url . '/remote.php/dav/files/' . $this->nextcloud_user . '/' . $this->nextcloud_upload_folder_path . '/' . $file_name;
$file_contents = fopen($file_path, 'r');
try {
$res = Http::withBasicAuth($this->nextcloud_user, $this->nextcloud_password)
->attach($file_name, $file_contents)
->put($nextcloud_url);
$res->throw();
} catch (\Exception $e) {
Log::error('nextcloud_upload_csv Upload error - ' . $e->getMessage());
throw new RuntimeException("E-NEXTCLOUD-UPLOAD");
}
// Close the file handle
fclose($file_contents);
return $res;
} catch (\Exception $e) {
return false;
}
}
function openproject_add_task_to_agent(array $issues, array $company_agents)
{
$openproject_main_group_members_url = $this->openproject_url . '/api/v3/groups/' . $this->openproject_group_id;
try {
$res = Http::withToken($this->openproject_token)->get($openproject_url);
$res->throw();
} catch (\Exception $e) {
Log::error('nextcloud_upload_csv Upload error - ' . $e->getMessage());
throw new RuntimeException("E-NEXTCLOUD-UPLOAD");
}
}
function send_export_via_email(string $from_date, string $to_date, string $file_name){
$email_subject = $this->email_prefix_subject . ' '. $from_date.' - '.$to_date;
Mail::to($this->email_address_recepient)->send(new sendExportNotice(['export_date' => $email_subject, 'file_name' => $file_name, 'upload_folder_web_link' => $this->nextcloud_upload_folder_web_link], $email_subject));
return true;
}
function handle_third_party_services(string $file_name, string $file_path, array $issues, array $company_agents, string $from_date, string $to_date)
{
$nextcloud_res = $open_project_res = $email_res = false;
if ($this->third_party_integrations_nextcloud) {
$nextcloud_res = $this->nextcloud_upload_csv($file_name, $file_path);
}
if ($this->third_party_integrations_open_project) {
$open_project_res = $this->openproject_add_task_to_agent($issues, $company_agents);
}
if($this->email_send_allow) {
$email_res = $this->send_export_via_email($from_date, $to_date, $file_name);
}
return [$nextcloud_res, $open_project_res, $email_res];
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class sendExportNotice extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct(array $data, string $email_subject)
{
$this->data = $data;
$this->email_subject = $email_subject;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('sendExportNotice')->with($this->data)->subject($this->email_subject);
}
}

View File

@ -96,6 +96,17 @@ $app->configure('app');
// $app->register(App\Providers\EventServiceProvider::class);
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);
$app->register(Illuminate\Mail\MailServiceProvider::class);
$app->configure('mail');
$app->alias('mail.manager', Illuminate\Mail\MailManager::class);
$app->alias('mail.manager', Illuminate\Contracts\Mail\Factory::class);
$app->alias('mailer', Illuminate\Mail\Mailer::class);
$app->alias('mailer', Illuminate\Contracts\Mail\Mailer::class);
$app->alias('mailer', Illuminate\Contracts\Mail\MailQueue::class);
/*
|--------------------------------------------------------------------------
| Load The Application Routes

View File

@ -13,6 +13,7 @@
"flipbox/lumen-generator": "^9.2",
"guzzlehttp/guzzle": "^7.4",
"http-interop/http-factory-guzzle": "^1.2",
"illuminate/mail": "^10.48",
"laravel/lumen-framework": "^10.0",
"owenvoke/gitea": "dev-main as 0.1.6",
"phpoffice/phpspreadsheet": "^1.29"

2229
composer.lock generated

File diff suppressed because it is too large Load Diff

103
config/mail.php Normal file
View File

@ -0,0 +1,103 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "log", "array", "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN'),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
];

View File

@ -3,7 +3,7 @@
@section('title', 'Login')
@section('content')
<section class="login" style="max-width:600px;width:100%:">
<section class="login" style="max-width:600px;width:100%;">
<div class="card">
<div class="card-header">
{{__('Login')}}

View File

@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<body>
<p>{{$export_date}}</p>
<p>File name {{$file_name}}</p>
<p><a href="{{$upload_folder_web_link}}">Link to upload folder</a> [0]</p>
<p>[0] - {{$upload_folder_web_link}}</p>
</body>
</html>

View File

@ -2,9 +2,6 @@
/** @var \Laravel\Lumen\Routing\Router $router */
use App\Http\Controllers\GiteaApiController;
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| Application Routes
@ -37,7 +34,7 @@ $router->post('backend', [
$router->post('export', [
'as' => 'export',
'uses' => 'GiteaApiController@export_closed_issues'
'uses' => 'GiteaApiController\GiteaApiController@export_closed_issues'
]);
// $router->post('backend', [

View File

@ -0,0 +1,41 @@
<?php
namespace Tests;
use Tests\TestCase;
use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;
class CsvGenerationTest extends TestCase
{
public function test_export_contains_correct_data()
{
$res = $this->post('/backend', array(
'organization' => 'GruppoCO',
'password' => getenv('APP_PASSWORD')
));
$res->assertResponseOk();
$beginningDateYear = '2024' ;
$beginningDateMonth = '04';
$endDateYear = '2024';
$endDateMonth = '05';
$issueType = 'closed';
$generatedCsv = $this->post('/export', array(
'from_year' => $beginningDateYear,
'from_month' => $beginningDateMonth,
'to_year' => $endDateYear,
'to_month' => $endDateMonth,
'issues_type' => $issueType,
));
$res->assertResponseOK();
$generatedCsvHash = md5_file($generatedCsv);
$testFileHash = '07078b8e24768453b1e45236b13d347d';
assertEquals($generatedCsvHash, $testFileHash);
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace Tests\Http\Controllers\CsvController;
use App\Http\Controllers\CsvController\CsvController;
use PHPUnit\Framework\TestCase;
class CsvControllerTest extends TestCase
{
public function testCreate_csv()
{
}
public function testCreate_columns()
{
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Tests\Http\Controllers\CsvController\CsvCostCalc;
use App\Http\Controllers\CsvController\CsvCostCalc\CsvAgentCost;
use PHPUnit\Framework\TestCase;
class CsvAgentCostTest extends TestCase
{
public function testAgent_cost_calc()
{
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace Tests\Http\Controllers\CsvController\CsvCostCalc;
use App\Http\Controllers\CsvController\CsvCostCalc\CsvCostCalc;
use PHPUnit\Framework\TestCase;
class CsvCostCalcTest extends TestCase
{
public function testTotal_time_cost()
{
}
public function testAgent_cost_calc()
{
}
public function testSum_costs()
{
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace Tests\Http\Controllers\CsvController\CsvCostCalc;
use App\Http\Controllers\CsvController\CsvCostCalc\CsvMinuteCostCalc;
use PHPUnit\Framework\TestCase;
class CsvMinuteCostCalcTest extends TestCase
{
protected $CsvMinuteCostCalc;
protected function setUp(): void
{
$this->csv_minute_cost_calc = new CsvMinuteCostCalc(); // Replace CsvMinuteCostCalc with the actual class name
$this->csv_minute_cost_calc->partner_organization = 'PartnerOrg'; // Set up the partner organization
$this->csv_minute_cost_calc->price_partner = [
'high' => 100,
'normal' => 50,
'low' => 25,
'0' => 0
];
$this->csv_minute_cost_calc->price_client = [
'high' => 200,
'normal' => 100,
'low' => 50,
'0' => 0
];
}
public function testSelectCorrectCostForPartnerHighPriority()
{
$result = $this->csv_minute_cost_calc->select_correct_cost('RequestedBy/PartnerOrg', 'Priority/critical');
$this->assertEquals(100, $result);
}
public function testSelectCorrectCostForPartnerMediumPriority()
{
$result = $this->csv_minute_cost_calc->select_correct_cost('RequestedBy/PartnerOrg', 'Priority/medium');
$this->assertEquals(50, $result);
}
public function testSelectCorrectCostForClientHighPriority()
{
$result = $this->csv_minute_cost_calc->select_correct_cost('RequestedBy/Client', 'Priority/critical');
$this->assertEquals(200, $result);
}
public function testSelectCorrectCostForClientLowPriority()
{
$result = $this->csv_minute_cost_calc->select_correct_cost('RequestedBy/Client', 'Priority/low');
$this->assertEquals(50, $result);
}
public function testSelectCorrectCostWithUnknownPriority()
{
$result = $this->csv_minute_cost_calc->select_correct_cost('RequestedBy/Client', 'Priority/unknown');
$this->assertEquals(0, $result);
}
public function testSelectCorrectCostForPartnerLowPriority()
{
$result = $this->csv_minute_cost_calc->select_correct_cost('RequestedBy/PartnerOrg', 'Priority/low');
$this->assertEquals(25, $result);
}
public function testSelectCorrectCostWithExceptionHandling()
{
$result = $this->csv_minute_cost_calc->select_correct_cost('', '');
$this->assertEquals(0, $result); // Assuming default is 0
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Tests\Http\Controllers\CsvController\CsvCostCalc;
use App\Http\Controllers\CsvController\CsvCostCalc\CsvSumTotalsCalc;
use PHPUnit\Framework\TestCase;
class CsvSumTotalsCalcTest extends TestCase
{
public function testSum_costs()
{
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Tests\Http\Controllers\CsvController\CsvCostCalc;
use App\Http\Controllers\CsvController\CsvCostCalc\CsvTotalCostCalc;
use PHPUnit\Framework\TestCase;
class CsvTotalCostCalcTest extends TestCase
{
public function testTotal_time_cost()
{
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Tests\Http\Controllers\CsvController;
use App\Http\Controllers\CsvController\CsvDataHandling;
use PHPUnit\Framework\TestCase;
class CsvDataHandlingTest extends TestCase
{
public function testHandle_csv_time()
{
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace Tests\Http\Controllers\CsvController;
use App\Http\Controllers\CsvController\CsvDataInit;
use PHPUnit\Framework\TestCase;
class CsvDataInitTest extends TestCase
{
public function testInitialize_csv_data()
{
}
public function testHandle_labels()
{
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Tests\Http\Controllers\GiteaApiController;
use App\Http\Controllers\GiteaApiController\GiteaApiController;
use PHPUnit\Framework\TestCase;
class GiteaApiControllerTest extends TestCase
{
public function testExport_closed_issues()
{
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Tests\Http\Controllers\GiteaApiController;
use App\Http\Controllers\GiteaApiController\GiteaExport;
use PHPUnit\Framework\TestCase;
class GiteaExportTest extends TestCase
{
public function testExport_issues()
{
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Tests\Http\Controllers\GiteaApiController;
use App\Http\Controllers\GiteaApiController\GiteaFetch;
use PHPUnit\Framework\TestCase;
class GiteaFetchTest extends TestCase
{
public function testGet_issue_time()
{
}
public function testGet_issues()
{
}
public function testGet_repositories()
{
}
public function testGet_company_agents()
{
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Tests\Http\Controllers;
use App\Http\Controllers\IssueValidationController;
use PHPUnit\Framework\TestCase;
class IssueValidationControllerTest extends TestCase
{
public function testHandle_single_issue()
{
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace Tests\Http\Controllers;
use App\Http\Controllers\ThirdPartyServices;
use PHPUnit\Framework\TestCase;
class ThirdPartyServicesTest extends TestCase
{
public function testNextcloud_upload_csv()
{
}
public function testHandle_third_party_services()
{
}
public function testOpenproject_add_task_to_agent()
{
}
}

View File

@ -1,9 +1,6 @@
<?php
use Tests\TestCase;
use App\Http\Controllers\GiteaApiController;
use Laravel\Lumen\Testing\DatabaseMigrations;
use Laravel\Lumen\Testing\DatabaseTransactions;
class UnitTest extends TestCase
{