diff --git a/app/Console/Commands/LegacyMigrateFilesToStorage.php b/app/Console/Commands/LegacyMigrateFilesToStorage.php index da1ccb0d..f5a47c0f 100644 --- a/app/Console/Commands/LegacyMigrateFilesToStorage.php +++ b/app/Console/Commands/LegacyMigrateFilesToStorage.php @@ -27,7 +27,7 @@ class LegacyMigrateFilesToStorage extends Command */ public function handle() { - FileInfo::lazy(20)->each(function (FileInfo $fileInfo){ + FileInfo::lazy(20)->each(function (FileInfo $fileInfo) { $data = $fileInfo->fileData; $link = $fileInfo->link; $beleg = ExpensesReceipt::find($link); @@ -35,14 +35,14 @@ public function handle() $pdfData = $data->data; $hash = $fileInfo->hashname; $path = "auslagen/$expenses_id/$hash.pdf"; - if ($pdfData !== null){ - if(empty($data->diskpath)){ + if ($pdfData !== null) { + if (empty($data->diskpath)) { $data->diskpath = $path; } - if(!\Storage::has($path)){ + if (! \Storage::has($path)) { \Storage::put($path, $pdfData); } - if ($this->argument('delete') === "true"){ + if ($this->argument('delete') === 'true') { $data->data = null; } $data->save(); diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index d8bc1d29..854bcc8a 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -10,7 +10,6 @@ class Kernel extends ConsoleKernel /** * Define the application's command schedule. * - * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) diff --git a/app/Exceptions/LegacyDieException.php b/app/Exceptions/LegacyDieException.php index f87a960d..12ef0e2f 100644 --- a/app/Exceptions/LegacyDieException.php +++ b/app/Exceptions/LegacyDieException.php @@ -1,16 +1,15 @@ debug = $debug; parent::__construct($message, $code, $previous); diff --git a/app/Exceptions/LegacyJsonException.php b/app/Exceptions/LegacyJsonException.php index 39318433..3d82e240 100644 --- a/app/Exceptions/LegacyJsonException.php +++ b/app/Exceptions/LegacyJsonException.php @@ -6,11 +6,11 @@ class LegacyJsonException extends Exception { - public mixed $content; + public function __construct(mixed $content) { $this->content = $content; - parent::__construct("", 200, null); + parent::__construct('', 200, null); } } diff --git a/app/Exceptions/LegacyRedirectException.php b/app/Exceptions/LegacyRedirectException.php index 89ca09e3..5f6e7eef 100644 --- a/app/Exceptions/LegacyRedirectException.php +++ b/app/Exceptions/LegacyRedirectException.php @@ -1,11 +1,9 @@ map(function ($row) use ($column){ + $fields = $rows->map(function ($row) use ($column) { return "$column$row"; })->join(','); - return "=SUM(" . $fields . ")"; + + return '=SUM('.$fields.')'; } public function columnWidths(): array @@ -58,5 +58,4 @@ public function columnWidths(): array 'E' => 15, ]; } - } diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 794a3d77..951682d2 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -11,10 +11,10 @@ class AuthController { + public function __construct(private readonly AuthService $authService) {} - public function __construct(private readonly AuthService $authService){} - - public function login(){ + public function login() + { return $this->authService->prepareLogin(); } @@ -27,11 +27,14 @@ public function callback(Request $request): RedirectResponse Auth::login($user); } + return redirect()->intended(RouteServiceProvider::HOME); } - public function logout() { + public function logout() + { Auth::logout(); + // call after logout routine return $this->authService->afterLogout(); } diff --git a/app/Http/Controllers/BudgetPlanController.php b/app/Http/Controllers/BudgetPlanController.php index a85a3c21..edc78eaa 100644 --- a/app/Http/Controllers/BudgetPlanController.php +++ b/app/Http/Controllers/BudgetPlanController.php @@ -6,13 +6,15 @@ class BudgetPlanController extends Controller { - - public function index(){ + public function index() + { $plans = BudgetPlan::orderByDesc('start_date')->get(); + return view('budget-plan.index', ['plans' => $plans]); } - public function show(BudgetPlan $plan){ + public function show(BudgetPlan $plan) + { return view('budget-plan.show'); } } diff --git a/app/Http/Controllers/Dev.php b/app/Http/Controllers/Dev.php index b8d43638..f5d25bff 100644 --- a/app/Http/Controllers/Dev.php +++ b/app/Http/Controllers/Dev.php @@ -2,13 +2,12 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; - class Dev extends Controller { - function groups() + public function groups() { $groups = \Auth::user()?->getGroups(); + return view('components.dump', ['dump' => $groups]); } } diff --git a/app/Http/Controllers/Legacy/DeleteExpenses.php b/app/Http/Controllers/Legacy/DeleteExpenses.php index 3aa1ea6a..4a4c0147 100644 --- a/app/Http/Controllers/Legacy/DeleteExpenses.php +++ b/app/Http/Controllers/Legacy/DeleteExpenses.php @@ -5,10 +5,7 @@ use App\Http\Controllers\Controller; use App\Models\Legacy\Expenses; use App\Models\Legacy\ExpensesReceipt; -use App\Models\Legacy\FileData; use App\Models\Legacy\FileInfo; -use App\Models\Legacy\Project; -use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class DeleteExpenses extends Controller @@ -22,18 +19,17 @@ public function __invoke(int $expense_id) $userPerm = \Auth::user()->getGroups()->contains('ref-finanzen-hv') || $project->creator->id === \Auth::user()->id - || explode(";", $expense->created)[1] === \Auth::user()->username - ; + || explode(';', $expense->created)[1] === \Auth::user()->username; // authorize state - $deletableState = !in_array(explode(";", $expense->state)[0], ['instructed','booked'], true); + $deletableState = ! in_array(explode(';', $expense->state)[0], ['instructed', 'booked'], true); - if($userPerm === false || $deletableState === false){ + if ($userPerm === false || $deletableState === false) { abort(403); } // to make sure to delete everything and not only parts \DB::beginTransaction(); $reciepts = $expense->receipts; - $reciepts->each(function (ExpensesReceipt $receipt){ + $reciepts->each(function (ExpensesReceipt $receipt) { // delete all posts $receipt->posts()->delete(); // delete all files db entries (storage later) @@ -50,7 +46,7 @@ public function __invoke(int $expense_id) $expense->delete(); // clean up storage if DB is successfully cleaned - DB::afterCommit(function () use ($expense_id){ + DB::afterCommit(function () use ($expense_id) { \Storage::deleteDirectory("auslagen/{$expense_id}/"); }); \DB::commit(); diff --git a/app/Http/Controllers/Legacy/DeleteProject.php b/app/Http/Controllers/Legacy/DeleteProject.php index c1d1b220..8a732152 100644 --- a/app/Http/Controllers/Legacy/DeleteProject.php +++ b/app/Http/Controllers/Legacy/DeleteProject.php @@ -16,7 +16,7 @@ public function __invoke(int $project_id) || $project->creator->id === \Auth::user()->id; $dataPerm = $project->expenses()->count() === 0; - if($userPerm === false || $dataPerm === false){ + if ($userPerm === false || $dataPerm === false) { abort(403); } diff --git a/app/Http/Controllers/Legacy/ExportController.php b/app/Http/Controllers/Legacy/ExportController.php index 5cd7a1cc..9d2702ec 100644 --- a/app/Http/Controllers/Legacy/ExportController.php +++ b/app/Http/Controllers/Legacy/ExportController.php @@ -12,15 +12,16 @@ class ExportController extends Controller { public function budgetPlan(int $id, string $filetype) { - $writerType = match ($filetype){ - "xlsx", "xls" => Excel::XLSX, - "ods" => Excel::ODS, + $writerType = match ($filetype) { + 'xlsx', 'xls' => Excel::XLSX, + 'ods' => Excel::ODS, }; $plan = LegacyBudgetPlan::findOrFail($id); - $today = today()->format("Y-m-d"); - $start = Carbon::make($plan->von)?->format("y-m"); - $end = Carbon::make($plan->bis)?->format("y-m"); - $fileName = "$today HHP $start" . ($end ? " bis $end" : '') . ".$filetype"; + $today = today()->format('Y-m-d'); + $start = Carbon::make($plan->von)?->format('y-m'); + $end = Carbon::make($plan->bis)?->format('y-m'); + $fileName = "$today HHP $start".($end ? " bis $end" : '').".$filetype"; + return (new LegacyBudgetExport($plan))->download($fileName, $writerType); } } diff --git a/app/Http/Controllers/Legacy/LegacyController.php b/app/Http/Controllers/Legacy/LegacyController.php index ade8d23d..9243bc99 100644 --- a/app/Http/Controllers/Legacy/LegacyController.php +++ b/app/Http/Controllers/Legacy/LegacyController.php @@ -8,16 +8,17 @@ use forms\projekte\auslagen\AuslagenHandler2; use framework\DBConnector; use Illuminate\Contracts\Filesystem\FileNotFoundException; -use Symfony\Component\HttpFoundation\StreamedResponse; use Illuminate\Http\Request; +use Symfony\Component\HttpFoundation\StreamedResponse; class LegacyController extends Controller { - public function bootstrap() : void { - if (!defined('SYSBASE')) { + public function bootstrap(): void + { + if (! defined('SYSBASE')) { define('SYSBASE', base_path('/legacy/')); } - require_once SYSBASE . '/lib/inc.all.php'; + require_once SYSBASE.'/lib/inc.all.php'; } public function render(Request $request) @@ -31,30 +32,35 @@ public function render(Request $request) // if wanted by the unit test the content is delivered without the layout return $output; } + // otherwise with return view('legacy.main', ['content' => $output]); } catch (LegacyRedirectException $e) { return $e->redirect; - }catch (LegacyJsonException $e){ + } catch (LegacyJsonException $e) { ob_get_clean(); + return response()->json($e->content); - } catch (\Exception $exception){ + } catch (\Exception $exception) { // get rid of the already printed html ob_get_clean(); throw $exception; } } - public function renderFile($auslagen_id, $hash){ + public function renderFile($auslagen_id, $hash) + { $db = DBConnector::getInstance()->dbFetchAll('fileinfo', where: ['hashname' => $hash, 'link' => $auslagen_id]); $name = $db[0]['filename'] ?? 'error'; $path = "/auslagen/$auslagen_id/$hash/$name.pdf"; + return view('components.inlineFile', ['src' => $path]); } - public function belegePdf(int $project_id, int $auslagen_id, int $version, ?string $file_name = null){ + public function belegePdf(int $project_id, int $auslagen_id, int $version, ?string $file_name = null) + { // file was generated and requested by the iframe - if (!empty($file_name)){ + if (! empty($file_name)) { return \Storage::response( "auslagen/$auslagen_id/belege-pdf-v$version.pdf", $file_name @@ -72,14 +78,16 @@ public function belegePdf(int $project_id, int $auslagen_id, int $version, ?stri 'project_id' => $project_id, 'auslagen_id' => $auslagen_id, 'version' => $version, - 'file_name' => "Belege-IP$project_id-A$auslagen_id.pdf" + 'file_name' => "Belege-IP$project_id-A$auslagen_id.pdf", ]); + return view('components.inlineFile', ['src' => $path]); } - public function zahlungsanweisungPdf(int $project_id, int $auslagen_id, int $version, ?string $file_name = null){ + public function zahlungsanweisungPdf(int $project_id, int $auslagen_id, int $version, ?string $file_name = null) + { // file was generated and requested by the iframe call - if (!empty($file_name)){ + if (! empty($file_name)) { return \Storage::response( "/auslagen/$auslagen_id/zahlungsanweisung-v$version.pdf", $file_name @@ -97,15 +105,16 @@ public function zahlungsanweisungPdf(int $project_id, int $auslagen_id, int $ver 'project_id' => $project_id, 'auslagen_id' => $auslagen_id, 'version' => $version, - 'file_name' => "Zahlungsanweisung-IP$project_id-A$auslagen_id.pdf" + 'file_name' => "Zahlungsanweisung-IP$project_id-A$auslagen_id.pdf", ]); + return view('components.inlineFile', ['src' => $path]); } - public function deliverFile($auslagen_id, $fileHash, $fileName) : StreamedResponse + public function deliverFile($auslagen_id, $fileHash, $fileName): StreamedResponse { $path = "/auslagen/$auslagen_id/$fileHash.pdf"; - if (\Storage::exists($path)){ + if (\Storage::exists($path)) { return \Storage::response($path, $fileName); } throw new FileNotFoundException("Datei $path konnte nicht gefunden werden"); diff --git a/app/Http/Middleware/LegacyMiddleware.php b/app/Http/Middleware/LegacyMiddleware.php index a6d45dd5..8789897f 100644 --- a/app/Http/Middleware/LegacyMiddleware.php +++ b/app/Http/Middleware/LegacyMiddleware.php @@ -4,7 +4,6 @@ use Closure; use Illuminate\Http\Request; -use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException; use Symfony\Component\HttpFoundation\Response; class LegacyMiddleware @@ -16,7 +15,7 @@ class LegacyMiddleware */ public function handle(Request $request, Closure $next, string $groupName): Response { - if(\Auth::user()?->getGroups()->contains($groupName)){ + if (\Auth::user()?->getGroups()->contains($groupName)) { return $next($request); } //dump($groupName); diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index a2813a06..4e7c24b7 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -12,7 +12,6 @@ class RedirectIfAuthenticated /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next * @param string|null ...$guards * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse diff --git a/app/Livewire/TransactionImportWire.php b/app/Livewire/TransactionImportWire.php index d3c2a39e..3af9c3b4 100644 --- a/app/Livewire/TransactionImportWire.php +++ b/app/Livewire/TransactionImportWire.php @@ -25,6 +25,7 @@ class TransactionImportWire extends Component public $csv; public $separator; + public $csvFileEncoding; #[Url] @@ -33,16 +34,17 @@ class TransactionImportWire extends Component public $latestTransaction; public $mapping; + public $db_col_types; /** @var Collection */ public $data; + public $header; // CSV entries in order = -1, in reverse order = 1 public $csvOrder = -1; - public function mount() { $this->authorize('cashOfficer', User::class); @@ -50,13 +52,13 @@ public function mount() $this->mapping = $this->createMapping(); $this->data = collect(); - $foo = new BankTransaction(); - foreach($this->mapping as $db_column => $csv_colum){ + $foo = new BankTransaction; + foreach ($this->mapping as $db_column => $csv_colum) { $this->db_col_types[$db_column] = DB::getSchemaBuilder()->getColumnType($foo->getTable(), $db_column); } } - public function rules() : array + public function rules(): array { // mapping has only the csv column numbers as values, so we need to work around a bit, // we only check if a matching column was given, the values of this columns only in special cases @@ -64,17 +66,17 @@ public function rules() : array 'mapping.date' => [ 'required', 'int', - new DateColumnRule($this->data->pluck($this->mapping->get('date'))) + new DateColumnRule($this->data->pluck($this->mapping->get('date'))), ], 'mapping.valuta' => [ 'required', 'int', - new DateColumnRule($this->data->pluck($this->mapping->get('valuta'))) + new DateColumnRule($this->data->pluck($this->mapping->get('valuta'))), ], 'mapping.type' => 'required|int', 'mapping.value' => [ 'required', 'int', - new MoneyRule($this->data->pluck($this->mapping->get('value'))) + new MoneyRule($this->data->pluck($this->mapping->get('value'))), ], 'mapping.saldo' => [ 'int', @@ -84,33 +86,32 @@ public function rules() : array $this->data->pluck($this->mapping->get('value')), $this->data->pluck($this->mapping->get('saldo')), $this->latestTransaction?->saldo - ) + ), ], 'mapping.empf_name' => 'required|int', 'mapping.empf_bic' => 'sometimes|int', 'mapping.empf_iban' => [ 'required', 'int', - new IbanRule($this->data->pluck($this->mapping->get('empf_iban'))) + new IbanRule($this->data->pluck($this->mapping->get('empf_iban'))), ], - 'mapping.zweck' => 'required|int' + 'mapping.zweck' => 'required|int', ]; } /** * Fills up the mapping array with missing column keys (and empty values) - * @param array $merger - * @return Collection */ - private function createMapping(array $merger = []) : Collection + private function createMapping(array $merger = []): Collection { - $foo = new BankTransaction(); + $foo = new BankTransaction; $emptyMapping = collect(array_flip(array_keys($foo->getLabels()))); - return $emptyMapping->map(function ($value, $key) use ($merger){ - return $merger[$key] ?? ""; + + return $emptyMapping->map(function ($value, $key) use ($merger) { + return $merger[$key] ?? ''; }); } - public function parseCSV() : void + public function parseCSV(): void { $this->validateOnly('csv'); // temp save uploaded file @@ -119,7 +120,7 @@ public function parseCSV() : void // check for windows excel file encoding, transform to utf-8 $winEncoding = mb_check_encoding($content, 'Windows-1252'); - if($winEncoding){ + if ($winEncoding) { $content = mb_convert_encoding($content, 'UTF-8', 'Windows-1252'); } // explode content in lines @@ -129,27 +130,28 @@ public function parseCSV() : void // guess csv separator $amountComma = $content->substrCount(','); $amountSemicolon = $content->substrCount(';'); - $this->separator = $amountSemicolon > $amountComma ? ";" : ","; + $this->separator = $amountSemicolon > $amountComma ? ';' : ','; // extract header and data, explode data with csv separator guesses above $this->header = str_getcsv($lines->first(), $this->separator); $this->data = $lines->except(0) - ->filter(function ($line){ - return !(empty($line) || Regex::match('/^(,*|;*)\r?\n?$/', $line)->hasMatch()); - })->map(function ($line){ + ->filter(function ($line) { + return ! (empty($line) || Regex::match('/^(,*|;*)\r?\n?$/', $line)->hasMatch()); + })->map(function ($line) { return str_getcsv($line, $this->separator); - })->map(function ($lineArray){ + })->map(function ($lineArray) { // normalize data - foreach ($lineArray as $key => $cell){ + foreach ($lineArray as $key => $cell) { // tests $moneyTest = Regex::match('/(\-?)([0-9]+),([0-9]{1,2})/', $cell); // conversions - if($moneyTest->hasMatch()){ + if ($moneyTest->hasMatch()) { // group 1: sign, group 2: money before delimiter, group 3: cents after delimiter - $lineArray[$key] = $moneyTest->group(1) . $moneyTest->group(2) . '.' . $moneyTest->group(3); + $lineArray[$key] = $moneyTest->group(1).$moneyTest->group(2).'.'.$moneyTest->group(3); } } + return $lineArray; }); @@ -174,8 +176,8 @@ public function save() // mapping als vorlage speichern $account = BankAccount::findOrFail($this->account_id); $account->csv_import_settings = [ - "csv_import_mapping" => $this->mapping, - "csv_order" => $this->csvOrder + 'csv_import_mapping' => $this->mapping, + 'csv_order' => $this->csvOrder, ]; $account->save(); $last_id = BankTransaction::where('konto_id', $this->account_id) @@ -187,16 +189,16 @@ public function save() // create BankTransaction with values from $data, according to the keys assigned in $mapping DB::beginTransaction(); - foreach ($this->data as $row){ - $transaction = new BankTransaction(); + foreach ($this->data as $row) { + $transaction = new BankTransaction; $transaction->id = ++$last_id; $transaction->konto_id = $this->account_id; foreach ($this->mapping as $db_col_name => $csv_col_id) { - if(!empty($this->mapping[$db_col_name])){ + if (! empty($this->mapping[$db_col_name])) { $transaction->$db_col_name = $this->formatDataDb($row[$this->mapping[$db_col_name]], $db_col_name); - }else if($db_col_name === 'saldo'){ - $currentValue = str($row[$this->mapping['value']])->replace(',','.'); + } elseif ($db_col_name === 'saldo') { + $currentValue = str($row[$this->mapping['value']])->replace(',', '.'); $currentBalance = bcadd($currentBalance, $currentValue, 2); $transaction->$db_col_name = $this->formatDataDb($currentBalance, $db_col_name); } @@ -206,9 +208,10 @@ public function save() } try { DB::commit(); - } catch (\Exception $exception){ + } catch (\Exception $exception) { DB::rollBack(); $this->addError('csv', 'Nope'); + return; } @@ -219,10 +222,11 @@ public function save() ->with(['message' => __('konto.csv-import-success-msg', ['new-saldo' => $newBalance, 'transaction-amount' => $this->data->count()])]); } - public function render() : \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application|\Illuminate\View\View + public function render(): \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application|\Illuminate\View\View { $accounts = BankAccount::all(); - $labels = (new BankTransaction())->getLabels(); + $labels = (new BankTransaction)->getLabels(); + return view('livewire.bank.csv-import', [ 'accounts' => $accounts, 'firstNewTransaction' => $this->data->first(), @@ -231,20 +235,19 @@ public function render() : \Illuminate\Contracts\Foundation\Application|\Illumin ]); } - public function updatedAccountId() : void + public function updatedAccountId(): void { $account = BankAccount::findOrFail($this->account_id); $this->latestTransaction = BankTransaction::where('konto_id', $this->account_id) ->orderBy('id', 'desc')->limit(1)->first(); - $this->mapping = $this->createMapping($account->csv_import_settings["csv_import_mapping"] ?? []); - $this->csvOrder = (int) ($account->csv_import_settings["csv_order"] ?? -1); + $this->mapping = $this->createMapping($account->csv_import_settings['csv_import_mapping'] ?? []); + $this->csvOrder = (int) ($account->csv_import_settings['csv_order'] ?? -1); } /** * is called when mapping got updated - * @return void */ - public function updatedMapping() : void + public function updatedMapping(): void { $this->validate(); // date, value, saldo @@ -253,8 +256,9 @@ public function updatedMapping() : void public function formatDataDb(string|int $value, string $db_col_name): int|string { $type = $this->db_col_types[$db_col_name]; + //if($type === 'decimal') dd([$value, (float) $value,$db_col_name]); - return match ($type){ + return match ($type) { 'integer' => (int) $value, 'date' => guessCarbon($value, 'Y-m-d'), 'decimal' => $value, // no casting needed, string is expected @@ -265,11 +269,16 @@ public function formatDataDb(string|int $value, string $db_col_name): int|string public function formatDataView(string|int $value, string $db_col_name): int|string { $type = $this->db_col_types[$db_col_name]; - if($db_col_name === "empf_iban") $type = 'iban'; - if($db_col_name === "empf_bic") $type = 'bic'; - return match ($type){ + if ($db_col_name === 'empf_iban') { + $type = 'iban'; + } + if ($db_col_name === 'empf_bic') { + $type = 'bic'; + } + + return match ($type) { 'date' => guessCarbon($value, 'd.m.Y'), - 'decimal' => number_format((float) $value, 2, ',', '.') . ' €', + 'decimal' => number_format((float) $value, 2, ',', '.').' €', 'iban' => iban_to_human_format($value), default => $value }; @@ -277,7 +286,6 @@ public function formatDataView(string|int $value, string $db_col_name): int|stri /** * Change the order of CSV entries in current upload - * @return void */ public function reverseCsvOrder(): void { @@ -286,7 +294,7 @@ public function reverseCsvOrder(): void $this->validate(); } - public function isCsvOrderReversed() : bool + public function isCsvOrderReversed(): bool { return $this->csvOrder === -1; } diff --git a/app/Models/BudgetItem.php b/app/Models/BudgetItem.php index 7b1d9d45..bac638d9 100644 --- a/app/Models/BudgetItem.php +++ b/app/Models/BudgetItem.php @@ -5,7 +5,6 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; - class BudgetItem extends Model { use HasFactory; diff --git a/app/Models/BudgetPlan.php b/app/Models/BudgetPlan.php index 2d9ae047..9b639923 100644 --- a/app/Models/BudgetPlan.php +++ b/app/Models/BudgetPlan.php @@ -22,7 +22,6 @@ */ class BudgetPlan extends Model { - use HasFactory; /** @@ -46,12 +45,8 @@ class BudgetPlan extends Model ]; - /** - * @return \Illuminate\Database\Eloquent\Relations\HasMany - */ public function budgetItems(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(BudgetItem::class); } - } diff --git a/app/Models/Enums/BudgetType.php b/app/Models/Enums/BudgetType.php index 3f2e4a49..23a0e23e 100644 --- a/app/Models/Enums/BudgetType.php +++ b/app/Models/Enums/BudgetType.php @@ -2,7 +2,8 @@ namespace App\Models\Enums; -enum BudgetType: int { +enum BudgetType: int +{ case INCOME = 1; case EXPENSE = -1; } diff --git a/app/Models/Legacy/Bank.php b/app/Models/Legacy/Bank.php index 403e79fa..be9fd4d9 100644 --- a/app/Models/Legacy/Bank.php +++ b/app/Models/Legacy/Bank.php @@ -7,13 +7,14 @@ /** * App\Models\Legacy\Bank * - * @property integer $id + * @property int $id * @property string $url - * @property integer $blz + * @property int $blz * @property string $name * @property BankAccountCredential[] $finanzformularKontoCredentials * @property-read \Illuminate\Database\Eloquent\Collection $kontoCredentials * @property-read int|null $konto_credentials_count + * * @method static \Illuminate\Database\Eloquent\Builder|Bank newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|Bank newQuery() * @method static \Illuminate\Database\Eloquent\Builder|Bank query() @@ -21,6 +22,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|Bank whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|Bank whereName($value) * @method static \Illuminate\Database\Eloquent\Builder|Bank whereUrl($value) + * * @mixin \Eloquent */ class Bank extends Model diff --git a/app/Models/Legacy/BankAccount.php b/app/Models/Legacy/BankAccount.php index 76079e2f..99a341e1 100644 --- a/app/Models/Legacy/BankAccount.php +++ b/app/Models/Legacy/BankAccount.php @@ -9,7 +9,7 @@ /** * App\Models\Legacy\Konto * - * @property integer $id + * @property int $id * @property string $name * @property string $short * @property string $sync_from @@ -20,6 +20,7 @@ * @property BankTransaction[] $kontos * @property-read \Illuminate\Database\Eloquent\Collection $kontoTransactions * @property-read int|null $konto_transactions_count + * * @method static \Illuminate\Database\Eloquent\Builder|BankAccount newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|BankAccount newQuery() * @method static \Illuminate\Database\Eloquent\Builder|BankAccount query() @@ -30,11 +31,13 @@ * @method static \Illuminate\Database\Eloquent\Builder|BankAccount whereShort($value) * @method static \Illuminate\Database\Eloquent\Builder|BankAccount whereSyncFrom($value) * @method static \Illuminate\Database\Eloquent\Builder|BankAccount whereSyncUntil($value) + * * @mixin \Eloquent */ class BankAccount extends Model { public $timestamps = false; + /** * The table associated with the model. * @@ -47,15 +50,16 @@ class BankAccount extends Model */ protected $fillable = ['name', 'short', 'sync_from', 'sync_until', 'iban', 'last_sync', 'csv_import_settings']; - public function csvImportSettings() : Attribute + public function csvImportSettings(): Attribute { return Attribute::make( - get: static function (?string $value){ - if(empty($value)){ + get: static function (?string $value) { + if (empty($value)) { return []; } + return json_decode($value, true); - } , + }, set: static fn (array|Collection $value) => json_encode($value), ); } diff --git a/app/Models/Legacy/BankAccountCredential.php b/app/Models/Legacy/BankAccountCredential.php index 16dc606d..dafd1e48 100644 --- a/app/Models/Legacy/BankAccountCredential.php +++ b/app/Models/Legacy/BankAccountCredential.php @@ -8,16 +8,17 @@ /** * App\Models\Legacy\KontoCredential * - * @property integer $id - * @property integer $bank_id - * @property integer $owner_id + * @property int $id + * @property int $bank_id + * @property int $owner_id * @property string $name * @property string $bank_username - * @property integer $tan_mode + * @property int $tan_mode * @property string $tan_medium_name * @property string $tan_mode_name * @property Bank $kontoBank * @property User $user + * * @method static \Illuminate\Database\Eloquent\Builder|BankAccountCredential newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|BankAccountCredential newQuery() * @method static \Illuminate\Database\Eloquent\Builder|BankAccountCredential query() @@ -29,6 +30,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|BankAccountCredential whereTanMediumName($value) * @method static \Illuminate\Database\Eloquent\Builder|BankAccountCredential whereTanMode($value) * @method static \Illuminate\Database\Eloquent\Builder|BankAccountCredential whereTanModeName($value) + * * @mixin \Eloquent */ class BankAccountCredential extends Model diff --git a/app/Models/Legacy/BankTransaction.php b/app/Models/Legacy/BankTransaction.php index 1ec75cb1..1e0d2b06 100644 --- a/app/Models/Legacy/BankTransaction.php +++ b/app/Models/Legacy/BankTransaction.php @@ -7,8 +7,8 @@ /** * App\Models\Legacy\KontoTransaction * - * @property integer $id - * @property integer $konto_id + * @property int $id + * @property int $konto_id * @property string $date * @property string $valuta * @property string $type @@ -23,6 +23,7 @@ * @property string $customer_ref * @property BankAccount $finanzformularKontoType * @property-read \App\Models\Legacy\BankAccount $konto + * * @method static \Illuminate\Database\Eloquent\Builder|BankTransaction newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|BankTransaction newQuery() * @method static \Illuminate\Database\Eloquent\Builder|BankTransaction query() @@ -40,6 +41,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|BankTransaction whereValue($value) * @method static \Illuminate\Database\Eloquent\Builder|BankTransaction whereValuta($value) * @method static \Illuminate\Database\Eloquent\Builder|BankTransaction whereZweck($value) + * * @mixin \Eloquent */ class BankTransaction extends Model @@ -70,8 +72,7 @@ public function getLabels() { $labels = []; - foreach($this->getFillable() as $attribute) - { + foreach ($this->getFillable() as $attribute) { $labels[$attribute] = 'konto.label.transaction.'.$attribute; } diff --git a/app/Models/Legacy/Booking.php b/app/Models/Legacy/Booking.php index b41140a6..4051b440 100644 --- a/app/Models/Legacy/Booking.php +++ b/app/Models/Legacy/Booking.php @@ -9,21 +9,22 @@ /** * App\Models\Legacy\Booking * - * @property integer $id - * @property integer $titel_id - * @property integer $user_id - * @property integer $kostenstelle - * @property integer $zahlung_id - * @property integer $zahlung_type - * @property integer $beleg_id + * @property int $id + * @property int $titel_id + * @property int $user_id + * @property int $kostenstelle + * @property int $zahlung_id + * @property int $zahlung_type + * @property int $beleg_id * @property string $beleg_type * @property string $timestamp * @property string $comment * @property float $value - * @property integer $canceled + * @property int $canceled * @property BudgetItem $haushaltstitel * @property User $user * @property-read BudgetItem $budgetItem + * * @method static \Illuminate\Database\Eloquent\Builder|Booking newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|Booking newQuery() * @method static \Illuminate\Database\Eloquent\Builder|Booking query() @@ -39,6 +40,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|Booking whereValue($value) * @method static \Illuminate\Database\Eloquent\Builder|Booking whereZahlungId($value) * @method static \Illuminate\Database\Eloquent\Builder|Booking whereZahlungType($value) + * * @mixin \Eloquent */ class Booking extends Model diff --git a/app/Models/Legacy/BookingInstruction.php b/app/Models/Legacy/BookingInstruction.php index c283ee70..47e97594 100644 --- a/app/Models/Legacy/BookingInstruction.php +++ b/app/Models/Legacy/BookingInstruction.php @@ -9,24 +9,25 @@ /** * App\Models\Legacy\BookingInstruction * - * @property integer $id - * @property integer $titel_id - * @property integer $user_id - * @property integer $kostenstelle - * @property integer $zahlung_id - * @property integer $zahlung_type - * @property integer $beleg_id + * @property int $id + * @property int $titel_id + * @property int $user_id + * @property int $kostenstelle + * @property int $zahlung_id + * @property int $zahlung_type + * @property int $beleg_id * @property string $beleg_type * @property string $timestamp * @property string $comment * @property float $value - * @property integer $canceled + * @property int $canceled * @property BudgetItem $budgetItem * @property User $user * @property int $zahlung * @property int $beleg * @property int $by_user * @property int $done + * * @method static \Illuminate\Database\Eloquent\Builder|BookingInstruction newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|BookingInstruction newQuery() * @method static \Illuminate\Database\Eloquent\Builder|BookingInstruction query() @@ -37,6 +38,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|BookingInstruction whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|BookingInstruction whereZahlung($value) * @method static \Illuminate\Database\Eloquent\Builder|BookingInstruction whereZahlungType($value) + * * @mixin \Eloquent */ class BookingInstruction extends Model diff --git a/app/Models/Legacy/ChatMessage.php b/app/Models/Legacy/ChatMessage.php index db939834..5b31604f 100644 --- a/app/Models/Legacy/ChatMessage.php +++ b/app/Models/Legacy/ChatMessage.php @@ -7,14 +7,15 @@ /** * App\Models\Legacy\ChatMessage * - * @property integer $id - * @property integer $target_id + * @property int $id + * @property int $target_id * @property string $target * @property string $timestamp * @property string $creator * @property string $creator_alias * @property string $text - * @property boolean $type + * @property bool $type + * * @method static \Illuminate\Database\Eloquent\Builder|ChatMessage newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|ChatMessage newQuery() * @method static \Illuminate\Database\Eloquent\Builder|ChatMessage query() @@ -26,6 +27,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|ChatMessage whereText($value) * @method static \Illuminate\Database\Eloquent\Builder|ChatMessage whereTimestamp($value) * @method static \Illuminate\Database\Eloquent\Builder|ChatMessage whereType($value) + * * @mixin \Eloquent */ class ChatMessage extends Model diff --git a/app/Models/Legacy/Expenses.php b/app/Models/Legacy/Expenses.php index dca0ec45..f1f70eea 100644 --- a/app/Models/Legacy/Expenses.php +++ b/app/Models/Legacy/Expenses.php @@ -7,8 +7,8 @@ /** * App\Models\Legacy\Expenses * - * @property integer $id - * @property integer $projekt_id + * @property int $id + * @property int $projekt_id * @property string $name_suffix * @property string $state * @property string $ok_belege @@ -23,7 +23,7 @@ * @property string $last_change * @property string $last_change_by * @property string $etag - * @property integer $version + * @property int $version * @property string $created * @property Project $project * @property ExpensesReceipt[] $beleges @@ -31,6 +31,7 @@ * @property-read int|null $comments_count * @property-read \Illuminate\Database\Eloquent\Collection $receipts * @property-read int|null $receipts_count + * * @method static \Illuminate\Database\Eloquent\Builder|Expenses newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|Expenses newQuery() * @method static \Illuminate\Database\Eloquent\Builder|Expenses query() @@ -52,11 +53,11 @@ * @method static \Illuminate\Database\Eloquent\Builder|Expenses whereZahlungIban($value) * @method static \Illuminate\Database\Eloquent\Builder|Expenses whereZahlungName($value) * @method static \Illuminate\Database\Eloquent\Builder|Expenses whereZahlungVwzk($value) + * * @mixin \Eloquent */ class Expenses extends Model { - /** * The table associated with the model. * diff --git a/app/Models/Legacy/ExpensesReceipt.php b/app/Models/Legacy/ExpensesReceipt.php index 8a6fdaf7..2455568d 100644 --- a/app/Models/Legacy/ExpensesReceipt.php +++ b/app/Models/Legacy/ExpensesReceipt.php @@ -2,23 +2,23 @@ namespace App\Models\Legacy; -use App\Models\BelegPosten; use Illuminate\Database\Eloquent\Model; /** * App\Models\Legacy\ExpensesReceipt * - * @property integer $id - * @property integer $auslagen_id + * @property int $id + * @property int $auslagen_id * @property string $short * @property string $created_on * @property string $datum * @property string $beschreibung - * @property integer $file_id + * @property int $file_id * @property ExpensesReceiptPost[] $posts * @property Expenses $auslagen * @property-read \App\Models\Legacy\Expenses|null $expenses * @property-read int|null $posts_count + * * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceipt newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceipt newQuery() * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceipt query() @@ -29,6 +29,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceipt whereFileId($value) * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceipt whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceipt whereShort($value) + * * @mixin \Eloquent */ class ExpensesReceipt extends Model diff --git a/app/Models/Legacy/ExpensesReceiptPost.php b/app/Models/Legacy/ExpensesReceiptPost.php index fb4ea85e..6aabadf4 100644 --- a/app/Models/Legacy/ExpensesReceiptPost.php +++ b/app/Models/Legacy/ExpensesReceiptPost.php @@ -7,13 +7,14 @@ /** * App\Models\Legacy\ExpensesReceiptPost * - * @property integer $beleg_id - * @property integer $short - * @property integer $id - * @property integer $projekt_posten_id + * @property int $beleg_id + * @property int $short + * @property int $id + * @property int $projekt_posten_id * @property float $ausgaben * @property float $einnahmen * @property ExpensesReceipt $expensesReceipt + * * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceiptPost newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceiptPost newQuery() * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceiptPost query() @@ -23,6 +24,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceiptPost whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceiptPost whereProjektPostenId($value) * @method static \Illuminate\Database\Eloquent\Builder|ExpensesReceiptPost whereShort($value) + * * @mixin \Eloquent */ class ExpensesReceiptPost extends Model diff --git a/app/Models/Legacy/FileData.php b/app/Models/Legacy/FileData.php index e0af3b14..d7f7bb0c 100644 --- a/app/Models/Legacy/FileData.php +++ b/app/Models/Legacy/FileData.php @@ -7,18 +7,20 @@ /** * App\Models\Legacy\FileData * - * @property integer $id + * @property int $id * @property string $data * @property string $diskpath * @property FileInfo[] $fileinfos * @property-read \Illuminate\Database\Eloquent\Collection $fileInfo * @property-read int|null $file_info_count + * * @method static \Illuminate\Database\Eloquent\Builder|FileData newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|FileData newQuery() * @method static \Illuminate\Database\Eloquent\Builder|FileData query() * @method static \Illuminate\Database\Eloquent\Builder|FileData whereData($value) * @method static \Illuminate\Database\Eloquent\Builder|FileData whereDiskpath($value) * @method static \Illuminate\Database\Eloquent\Builder|FileData whereId($value) + * * @mixin \Eloquent */ class FileData extends Model @@ -30,7 +32,6 @@ class FileData extends Model */ protected $table = 'filedata'; - public $timestamps = false; /** diff --git a/app/Models/Legacy/FileInfo.php b/app/Models/Legacy/FileInfo.php index a8ce2cb6..78713a5f 100644 --- a/app/Models/Legacy/FileInfo.php +++ b/app/Models/Legacy/FileInfo.php @@ -7,18 +7,19 @@ /** * App\Models\Legacy\FileInfo * - * @property integer $id - * @property integer $data + * @property int $id + * @property int $data * @property string $link * @property string $added_on * @property string $hashname * @property string $filename - * @property integer $size + * @property int $size * @property string $fileextension * @property string $mime * @property string $encoding * @property FileData $filedatum * @property-read \App\Models\Legacy\FileData|null $fileData + * * @method static \Illuminate\Database\Eloquent\Builder|FileInfo newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|FileInfo newQuery() * @method static \Illuminate\Database\Eloquent\Builder|FileInfo query() @@ -32,6 +33,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|FileInfo whereLink($value) * @method static \Illuminate\Database\Eloquent\Builder|FileInfo whereMime($value) * @method static \Illuminate\Database\Eloquent\Builder|FileInfo whereSize($value) + * * @mixin \Eloquent */ class FileInfo extends Model diff --git a/app/Models/Legacy/LegacyBudgetGroup.php b/app/Models/Legacy/LegacyBudgetGroup.php index aa3d4472..b0d724d3 100644 --- a/app/Models/Legacy/LegacyBudgetGroup.php +++ b/app/Models/Legacy/LegacyBudgetGroup.php @@ -6,7 +6,6 @@ class LegacyBudgetGroup extends Model { - /** * The table associated with the model. * @@ -19,10 +18,6 @@ class LegacyBudgetGroup extends Model */ protected $fillable = ['hhp_id', 'gruppen_name', 'type']; - - /** - * @return \Illuminate\Database\Eloquent\Relations\HasMany - */ public function budgetItems(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(LegacyBudgetItem::class, 'hhpgruppen_id'); diff --git a/app/Models/Legacy/LegacyBudgetItem.php b/app/Models/Legacy/LegacyBudgetItem.php index 0f8215cc..0f03b0b2 100644 --- a/app/Models/Legacy/LegacyBudgetItem.php +++ b/app/Models/Legacy/LegacyBudgetItem.php @@ -2,12 +2,11 @@ namespace App\Models\Legacy; -use Cknow\Money\Money; use Illuminate\Database\Eloquent\Model; /** - * @property integer $id - * @property integer $hhpgruppen_id + * @property int $id + * @property int $hhpgruppen_id * @property string $titel_name * @property string $titel_nr * @property float $value @@ -44,12 +43,12 @@ public function budgetGroup() return $this->belongsTo(LegacyBudgetGroup::class, 'hhpgruppen_id'); } - public function bookingSum() : string + public function bookingSum(): string { return $this->bookings()->sum('value'); } - public function bookingDiff() : string + public function bookingDiff(): string { return (float) bcsub($this->value, $this->bookings()->sum('value')); } diff --git a/app/Models/Legacy/LegacyBudgetPlan.php b/app/Models/Legacy/LegacyBudgetPlan.php index 3b4e3664..cb8864c3 100644 --- a/app/Models/Legacy/LegacyBudgetPlan.php +++ b/app/Models/Legacy/LegacyBudgetPlan.php @@ -5,7 +5,7 @@ use Illuminate\Database\Eloquent\Model; /** - * @property integer $id + * @property int $id * @property string $von * @property string $bis * @property string $state @@ -25,9 +25,6 @@ class LegacyBudgetPlan extends Model */ protected $fillable = ['von', 'bis', 'state']; - /** - * @return \Illuminate\Database\Eloquent\Relations\HasMany - */ public function budgetGroups(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(LegacyBudgetGroup::class, 'hhp_id'); @@ -37,5 +34,4 @@ public function budgetItems(): \Illuminate\Database\Eloquent\Relations\HasManyTh { return $this->hasManyThrough(LegacyBudgetItem::class, LegacyBudgetGroup::class); } - } diff --git a/app/Models/Legacy/Project.php b/app/Models/Legacy/Project.php index 8c92c87a..8a1506f8 100644 --- a/app/Models/Legacy/Project.php +++ b/app/Models/Legacy/Project.php @@ -8,13 +8,13 @@ /** * App\Models\Legacy\Project * - * @property integer $id - * @property integer $creator_id + * @property int $id + * @property int $creator_id * @property string $createdat * @property string $lastupdated - * @property integer $version + * @property int $version * @property string $state - * @property integer $stateCreator_id + * @property int $stateCreator_id * @property string $name * @property string $responsible * @property string $org @@ -32,6 +32,7 @@ * @property-read int|null $expenses_count * @property-read int|null $posts_count * @property-read User $stateCreator + * * @method static \Illuminate\Database\Eloquent\Builder|Project newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|Project newQuery() * @method static \Illuminate\Database\Eloquent\Builder|Project query() @@ -52,6 +53,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|Project whereState($value) * @method static \Illuminate\Database\Eloquent\Builder|Project whereStateCreatorId($value) * @method static \Illuminate\Database\Eloquent\Builder|Project whereVersion($value) + * * @mixin \Eloquent */ class Project extends Model diff --git a/app/Models/Legacy/ProjectPost.php b/app/Models/Legacy/ProjectPost.php index 3c4f6199..207f691a 100644 --- a/app/Models/Legacy/ProjectPost.php +++ b/app/Models/Legacy/ProjectPost.php @@ -7,15 +7,16 @@ /** * App\Models\Legacy\ProjectPost * - * @property integer $id - * @property integer $projekt_id - * @property integer $titel_id + * @property int $id + * @property int $projekt_id + * @property int $titel_id * @property float $einnahmen * @property float $ausgaben * @property string $name * @property string $bemerkung * @property Project $projekte * @property-read \App\Models\Legacy\Project $project + * * @method static \Illuminate\Database\Eloquent\Builder|ProjectPost newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|ProjectPost newQuery() * @method static \Illuminate\Database\Eloquent\Builder|ProjectPost query() @@ -26,6 +27,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|ProjectPost whereName($value) * @method static \Illuminate\Database\Eloquent\Builder|ProjectPost whereProjektId($value) * @method static \Illuminate\Database\Eloquent\Builder|ProjectPost whereTitelId($value) + * * @mixin \Eloquent */ class ProjectPost extends Model diff --git a/app/Models/User.php b/app/Models/User.php index c9e8258f..c79ec431 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -32,6 +32,7 @@ * @property-read int|null $notifications_count * @property-read \Illuminate\Database\Eloquent\Collection $tokens * @property-read int|null $tokens_count + * * @method static \Database\Factories\UserFactory factory($count = null, $state = []) * @method static \Illuminate\Database\Eloquent\Builder|User newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|User newQuery() @@ -52,6 +53,7 @@ * @method static \Illuminate\Database\Eloquent\Builder|User whereRememberToken($value) * @method static \Illuminate\Database\Eloquent\Builder|User whereUpdatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|User whereUsername($value) + * * @mixin \Eloquent */ class User extends Authenticatable @@ -101,12 +103,12 @@ class User extends Authenticatable 'email_verified_at' => 'datetime', ]; - public function getGroups() : Collection + public function getGroups(): Collection { return app(AuthService::class)->userGroups(); } - public function getCommittees() : Collection + public function getCommittees(): Collection { return app(AuthService::class)->userCommittees(); } diff --git a/app/Notifications/NewComment.php b/app/Notifications/NewComment.php index 088896e6..ea052159 100644 --- a/app/Notifications/NewComment.php +++ b/app/Notifications/NewComment.php @@ -3,7 +3,6 @@ namespace App\Notifications; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; @@ -38,8 +37,7 @@ public function toMail(object $notifiable): MailMessage return (new MailMessage) ->line(__('comment.notification.line1')) ->line(__('comment.notification.line2', ['type' => $notifiable, 'id' => 0])) - ->action('Notification Action', url('/')) - ; + ->action('Notification Action', url('/')); } /** diff --git a/app/Policies/UserPolicy.php b/app/Policies/UserPolicy.php index 599c7139..f78078a1 100644 --- a/app/Policies/UserPolicy.php +++ b/app/Policies/UserPolicy.php @@ -6,7 +6,7 @@ class UserPolicy { - public function before(User $user, string $ability) : bool | null + public function before(User $user, string $ability): ?bool { return $user->getGroups()->contains('admin') ? true : null; } @@ -15,24 +15,24 @@ public function login(User $user): bool { return $user->getGroups()->contains('login'); } - public function finance(User $user) : bool + + public function finance(User $user): bool { return $user->getGroups()->contains('ref-finanzen'); } - public function cashOfficer(User $user) : bool + public function cashOfficer(User $user): bool { return $user->getGroups()->contains('ref-finanzen-kv'); } - public function budgetOfficer(User $user) : bool + public function budgetOfficer(User $user): bool { return $user->getGroups()->contains('ref-finanzen-hv'); } - public function admin(User $user) : bool + public function admin(User $user): bool { return $user->getGroups()->contains('admin'); } - } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 1d8dff2d..ee8ca5bc 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -6,7 +6,6 @@ class AppServiceProvider extends ServiceProvider { - /** * Register any application services. * diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 8cd669b1..e31ecf71 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -5,11 +5,8 @@ use App\Models\User; use App\Policies\UserPolicy; use App\Services\Auth\AuthService; -use App\Services\Auth\LocalAuthService; -use App\Services\Auth\StumvAuthService; use Illuminate\Contracts\Foundation\Application; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; -use Illuminate\Support\Facades\Gate; class AuthServiceProvider extends ServiceProvider { @@ -27,12 +24,12 @@ class AuthServiceProvider extends ServiceProvider */ public function register(): void { - $this->app->singleton(AuthService::class, function (Application $application){ + $this->app->singleton(AuthService::class, function (Application $application) { $serviceName = ucfirst(strtolower(config('auth.service'))); // weird to escape, but correct $classPath = "\App\Services\Auth\\{$serviceName}AuthService"; - if(class_exists($classPath)){ - return new $classPath(); + if (class_exists($classPath)) { + return new $classPath; } abort(500, 'Config Error. Wrong Auth provider given in Environment. Fitting AuthService Class not found'); diff --git a/app/Rules/CsvTransactionImport/BalanceRule.php b/app/Rules/CsvTransactionImport/BalanceRule.php index eff70684..41c76342 100644 --- a/app/Rules/CsvTransactionImport/BalanceRule.php +++ b/app/Rules/CsvTransactionImport/BalanceRule.php @@ -8,20 +8,22 @@ class BalanceRule implements ValidationRule { - private readonly Collection $differences; + private readonly Collection $balances; + private readonly ?string $initalBalance; - public function __construct(Collection $differences,Collection $balances,?string $initalBalance){ + public function __construct(Collection $differences, Collection $balances, ?string $initalBalance) + { // make sure all given Money strings have the same format: XXXX.XX (2 decimals, with . as separator) - $this->differences = $differences->map(function ($item){ - return number_format((float) str_replace(',','.', $item ?? ''), 2, '.', ''); + $this->differences = $differences->map(function ($item) { + return number_format((float) str_replace(',', '.', $item ?? ''), 2, '.', ''); }); - $this->balances = $balances->map(function ($item){ - return number_format((float) str_replace(',','.', $item ?? ''), 2, '.', ''); + $this->balances = $balances->map(function ($item) { + return number_format((float) str_replace(',', '.', $item ?? ''), 2, '.', ''); }); - $this->initalBalance = is_null($initalBalance) ? null : number_format((float) str_replace(',','.', $initalBalance), 2, '.', ''); + $this->initalBalance = is_null($initalBalance) ? null : number_format((float) str_replace(',', '.', $initalBalance), 2, '.', ''); } /** @@ -33,11 +35,11 @@ public function validate(string $attribute, mixed $value, Closure $fail): void { try { // if there is no initial balance (no prior transaction) then make sure the first csv entry as correct - $currentBalance = $this->initalBalance ?? bcsub($this->balances[0], $this->differences[0],2); - foreach ($this->differences as $id => $currentValue){ + $currentBalance = $this->initalBalance ?? bcsub($this->balances[0], $this->differences[0], 2); + foreach ($this->differences as $id => $currentValue) { $currentBalance = bcadd($currentBalance, $currentValue, 2); $csvBalance = $this->balances->get($id); - if($currentBalance !== $csvBalance){ + if ($currentBalance !== $csvBalance) { $fail(__('konto.csv-verify-balance-error', [ 'error-in-row' => $id + 1, 'calc-saldo' => $currentBalance, @@ -45,7 +47,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void ])); } } - }catch (\ValueError $error){ + } catch (\ValueError $error) { // thrown by bcsub and bc add $fail(__('konto.csv-verify-balance-error-wrong-datatype')); } diff --git a/app/Rules/CsvTransactionImport/BicRule.php b/app/Rules/CsvTransactionImport/BicRule.php index 565858c4..53ab5a60 100644 --- a/app/Rules/CsvTransactionImport/BicRule.php +++ b/app/Rules/CsvTransactionImport/BicRule.php @@ -8,7 +8,7 @@ class BicRule implements ValidationRule { - public function __construct(public Collection $bics){} + public function __construct(public Collection $bics) {} /** * Run the validation rule. @@ -17,10 +17,12 @@ public function __construct(public Collection $bics){} */ public function validate(string $attribute, mixed $value, Closure $fail): void { - foreach ($this->bics as $bic){ - if(empty($bic)) continue; - if(!verify_iban($bic)){ - $fail( __('konto.csv-verify-iban-error')); + foreach ($this->bics as $bic) { + if (empty($bic)) { + continue; + } + if (! verify_iban($bic)) { + $fail(__('konto.csv-verify-iban-error')); } } } diff --git a/app/Rules/CsvTransactionImport/DateColumnRule.php b/app/Rules/CsvTransactionImport/DateColumnRule.php index dd96cdb1..baf579d7 100644 --- a/app/Rules/CsvTransactionImport/DateColumnRule.php +++ b/app/Rules/CsvTransactionImport/DateColumnRule.php @@ -9,7 +9,8 @@ class DateColumnRule implements ValidationRule { - public function __construct(private Collection $column){} + public function __construct(private Collection $column) {} + /** * Run the validation rule. * @@ -20,10 +21,10 @@ public function validate(string $attribute, mixed $value, Closure $fail): void try { $firstDate = guessCarbon($this->column->first()); $lastDate = guessCarbon($this->column->last()); - if(!$firstDate->lessThanOrEqualTo($lastDate)){ + if (! $firstDate->lessThanOrEqualTo($lastDate)) { $fail(__('konto.csv-verify-date-order-error')); } - }catch (InvalidFormatException $exception){ + } catch (InvalidFormatException $exception) { $fail(__('konto.csv-verify-date-error')); } } diff --git a/app/Rules/CsvTransactionImport/IbanRule.php b/app/Rules/CsvTransactionImport/IbanRule.php index 5bdafe80..6f70f6b5 100644 --- a/app/Rules/CsvTransactionImport/IbanRule.php +++ b/app/Rules/CsvTransactionImport/IbanRule.php @@ -8,7 +8,7 @@ class IbanRule implements ValidationRule { - public function __construct(public Collection $ibans){} + public function __construct(public Collection $ibans) {} /** * Run the validation rule. @@ -17,10 +17,12 @@ public function __construct(public Collection $ibans){} */ public function validate(string $attribute, mixed $value, Closure $fail): void { - foreach ($this->ibans as $iban){ - if(empty($iban)) continue; - if(!verify_iban($iban)){ - $fail( __('konto.csv-verify-iban-error')); + foreach ($this->ibans as $iban) { + if (empty($iban)) { + continue; + } + if (! verify_iban($iban)) { + $fail(__('konto.csv-verify-iban-error')); } } } diff --git a/app/Rules/CsvTransactionImport/MoneyRule.php b/app/Rules/CsvTransactionImport/MoneyRule.php index bfcd2584..2b5d846c 100644 --- a/app/Rules/CsvTransactionImport/MoneyRule.php +++ b/app/Rules/CsvTransactionImport/MoneyRule.php @@ -8,8 +8,8 @@ class MoneyRule implements ValidationRule { + public function __construct(private Collection $column) {} - public function __construct(private Collection $column){} /** * Run the validation rule. * @@ -18,9 +18,9 @@ public function __construct(private Collection $column){} public function validate(string $attribute, mixed $value, Closure $fail): void { - foreach ($this->column as $entry){ + foreach ($this->column as $entry) { - if(!is_numeric(str_replace(',','.', $entry))){ + if (! is_numeric(str_replace(',', '.', $entry))) { $fail(__('konto.csv-verify-money-error')); } } diff --git a/app/Services/Auth/AuthService.php b/app/Services/Auth/AuthService.php index 065ef8b5..038157ed 100644 --- a/app/Services/Auth/AuthService.php +++ b/app/Services/Auth/AuthService.php @@ -9,16 +9,20 @@ abstract class AuthService { - abstract public function prepareLogin() : Response|RedirectResponse; - abstract public function userFromCallback(Request $request) : array; + abstract public function prepareLogin(): Response|RedirectResponse; - abstract public function userCommittees() : Collection; - abstract public function allCommittees() : Collection; - abstract public function userGroupsRaw() : Collection; - public function userGroups() : Collection { + abstract public function userFromCallback(Request $request): array; + + abstract public function userCommittees(): Collection; + + abstract public function allCommittees(): Collection; + + abstract public function userGroupsRaw(): Collection; + + public function userGroups(): Collection + { return $this->userGroupsRaw(); } abstract public function afterLogout(); - } diff --git a/app/Services/Auth/LocalAuthService.php b/app/Services/Auth/LocalAuthService.php index b4d5af10..b13cb922 100644 --- a/app/Services/Auth/LocalAuthService.php +++ b/app/Services/Auth/LocalAuthService.php @@ -9,8 +9,8 @@ class LocalAuthService extends AuthService { - private string $username; + public function __construct() { $this->username = config('local.auth.username'); @@ -25,13 +25,13 @@ public function userFromCallback(Request $request): array { return [ ['username' => $this->username], - [] + [], ]; } public function userCommittees(): Collection { - return match ($this->username){ + return match ($this->username) { 'user' => collect(['Students Council']), 'hhv' => collect(['Financial Department']), 'kv' => collect(['Financial Department']), @@ -51,7 +51,7 @@ public function allCommittees(): Collection public function userGroupsRaw(): Collection { - return match ($this->username){ + return match ($this->username) { 'user' => collect(['login']), 'hhv' => collect(['login', 'ref-finanzen', 'ref-finanzen-hv', 'ref-finanzen-belege']), 'kv' => collect(['login', 'ref-finanzen', 'ref-finanzen-kv', 'ref-finanzen-belege']), @@ -61,7 +61,5 @@ public function userGroupsRaw(): Collection }; } - public function afterLogout(){} - - + public function afterLogout() {} } diff --git a/app/Services/Auth/StumvAuthService.php b/app/Services/Auth/StumvAuthService.php index 5902a3de..95d005fd 100644 --- a/app/Services/Auth/StumvAuthService.php +++ b/app/Services/Auth/StumvAuthService.php @@ -23,6 +23,7 @@ public function prepareLogin(): Response|RedirectResponse { $driver = Socialite::driver('laravelpassport') ->scopes(['profile', 'committees', 'groups']); + return $driver->redirect(); } @@ -30,7 +31,7 @@ public function userFromCallback(Request $request): array { $driver = Socialite::driver('laravelpassport'); // if we have a local dev instance of stumv there is no need to verify ssl certs - if (\App::isLocal()){ + if (\App::isLocal()) { $driver = $driver->setHttpClient(new \GuzzleHttp\Client(['verify' => false])); } $user = $driver->user(); @@ -60,6 +61,7 @@ public function userFromCallback(Request $request): array 'iban' => $attributes['iban'] ?? '', 'address' => $attributes['address'] ?? '', ]; + return [$identifiers, $userAttributes]; } @@ -77,26 +79,27 @@ public function userGroupsRaw(): Collection }); } - public function userGroups() : Collection + public function userGroups(): Collection { $rawGroups = $this->userGroupsRaw(); $mapping = collect(config('services.laravelpassport.mapping', [])); - if($mapping->isEmpty()){ + if ($mapping->isEmpty()) { return $this->userGroupsRaw(); } + // permissions to obtain are the keys of the $mapping - return $mapping->filter(function ($value) use ($rawGroups){ + return $mapping->filter(function ($value) use ($rawGroups) { // filter permissions, that are not given by provider // prevent permission escalation by ignoring empty mappings - return $rawGroups->contains($value) && !empty($value); + return $rawGroups->contains($value) && ! empty($value); })->keys(); } public function afterLogout() { \Session::flush(); - return redirect(to: - config('services.laravelpassport.host') . + + return redirect(to: config('services.laravelpassport.host'). config('services.laravelpassport.logout_path') ); } @@ -104,6 +107,7 @@ public function afterLogout() public function allCommittees(): Collection { $community_uid = config('stufis.community_uid'); + return $this->api()->get("/api/committees/$community_uid")->collect(); } } diff --git a/app/Support/helpers.php b/app/Support/helpers.php index c2eccc16..62a3272f 100644 --- a/app/Support/helpers.php +++ b/app/Support/helpers.php @@ -7,19 +7,20 @@ /** * Guess the format of the input date because banks do not like standards :( */ - function guessCarbon(string $dateString, string $newFormat = null) : Carbon|string + function guessCarbon(string $dateString, ?string $newFormat = null): Carbon|string { $formats = ['d.m.y', 'd.m.Y', 'y-m-d', 'Y-m-d', 'jmy', 'jmY', 'dmy', 'dmY']; - foreach ($formats as $format){ + foreach ($formats as $format) { try { $ret = Carbon::rawCreateFromFormat($format, $dateString); - } catch (InvalidFormatException $e){ + } catch (InvalidFormatException $e) { continue; } // if successfully parsed - if($newFormat){ + if ($newFormat) { return $ret->format($newFormat); } + return $ret; } throw new InvalidFormatException("$dateString is not a valid date"); diff --git a/app/View/Components/Layout.php b/app/View/Components/Layout.php index 21eb7e8c..ece22623 100644 --- a/app/View/Components/Layout.php +++ b/app/View/Components/Layout.php @@ -6,7 +6,7 @@ class Layout extends Component { - public string $title = "StuFiS - Finanzen"; + public string $title = 'StuFiS - Finanzen'; public string $version; @@ -18,7 +18,7 @@ class Layout extends Component public array $profileSkeleton = [ [ 'text' => 'Mein Profil', - 'link' => '' + 'link' => '', ], [ 'text' => 'Logout', @@ -45,7 +45,7 @@ public function __construct($legacyContent = '') public function render() { return view('components.layouts.index', [ - 'version' => config('app.version') + 'version' => config('app.version'), ]); } } diff --git a/app/View/Components/Logo.php b/app/View/Components/Logo.php index b2ff5c9e..d9d85f2f 100644 --- a/app/View/Components/Logo.php +++ b/app/View/Components/Logo.php @@ -6,7 +6,6 @@ class Logo extends Component { - public $idPrefix; /** @@ -14,7 +13,7 @@ class Logo extends Component * * @return void */ - public function __construct(public $col1 = "#00c9ab", public $col2 = "#007f8b") + public function __construct(public $col1 = '#00c9ab', public $col2 = '#007f8b') { $this->idPrefix = \Str::random(10); } diff --git a/config/app.php b/config/app.php index eeee5149..c0bdbb07 100644 --- a/config/app.php +++ b/config/app.php @@ -236,6 +236,6 @@ 'chat' => [ 'public_key' => env('CHAT_PUBLIC_KEY'), 'private_key' => env('CHAT_PRIVATE_KEY'), - ] + ], ]; diff --git a/config/backup.php b/config/backup.php index 20efb12f..5882df85 100644 --- a/config/backup.php +++ b/config/backup.php @@ -8,7 +8,7 @@ * The name of this application. You can use this name to monitor * the backups. */ - 'name' => env('APP_NAME', 'laravel-backup') . '-' . config('app.version'), + 'name' => env('APP_NAME', 'laravel-backup').'-'.config('app.version'), 'source' => [ @@ -141,7 +141,7 @@ /* * The filename prefix used for the backup zip file. */ - 'filename_prefix' => env('AUTH_REALM') . '-', + 'filename_prefix' => env('AUTH_REALM').'-', /* * The disk names on which the backups will be stored. @@ -237,13 +237,13 @@ */ 'monitor_backups' => [ [ - 'name' => env('APP_NAME') . '-' . config('app.version'), + 'name' => env('APP_NAME').'-'.config('app.version'), 'disks' => ['backups'], 'health_checks' => [ \Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumAgeInDays::class => 1, \Spatie\Backup\Tasks\Monitor\HealthChecks\MaximumStorageInMegabytes::class => 5000, ], ], - ] - // a bit of config was deleted here because unused (notifications) + ], + // a bit of config was deleted here because unused (notifications) ]; diff --git a/config/excel.php b/config/excel.php index 16828e75..8d5d271c 100644 --- a/config/excel.php +++ b/config/excel.php @@ -14,7 +14,7 @@ | Here you can specify how big the chunk should be. | */ - 'chunk_size' => 1000, + 'chunk_size' => 1000, /* |-------------------------------------------------------------------------- @@ -41,15 +41,15 @@ | Configure e.g. delimiter, enclosure and line ending for CSV exports. | */ - 'csv' => [ - 'delimiter' => ',', - 'enclosure' => '"', - 'line_ending' => PHP_EOL, - 'use_bom' => false, + 'csv' => [ + 'delimiter' => ',', + 'enclosure' => '"', + 'line_ending' => PHP_EOL, + 'use_bom' => false, 'include_separator_line' => false, - 'excel_compatibility' => false, - 'output_encoding' => '', - 'test_auto_detect' => true, + 'excel_compatibility' => false, + 'output_encoding' => '', + 'test_auto_detect' => true, ], /* @@ -60,20 +60,20 @@ | Configure e.g. default title, creator, subject,... | */ - 'properties' => [ - 'creator' => '', + 'properties' => [ + 'creator' => '', 'lastModifiedBy' => '', - 'title' => '', - 'description' => '', - 'subject' => '', - 'keywords' => '', - 'category' => '', - 'manager' => '', - 'company' => '', + 'title' => '', + 'description' => '', + 'subject' => '', + 'keywords' => '', + 'category' => '', + 'manager' => '', + 'company' => '', ], ], - 'imports' => [ + 'imports' => [ /* |-------------------------------------------------------------------------- @@ -86,7 +86,7 @@ | you can enable it by setting read_only to false. | */ - 'read_only' => true, + 'read_only' => true, /* |-------------------------------------------------------------------------- @@ -110,7 +110,7 @@ | Available options: none|slug|custom | */ - 'heading_row' => [ + 'heading_row' => [ 'formatter' => 'slug', ], @@ -122,12 +122,12 @@ | Configure e.g. delimiter, enclosure and line ending for CSV imports. | */ - 'csv' => [ - 'delimiter' => null, - 'enclosure' => '"', + 'csv' => [ + 'delimiter' => null, + 'enclosure' => '"', 'escape_character' => '\\', - 'contiguous' => false, - 'input_encoding' => 'UTF-8', + 'contiguous' => false, + 'input_encoding' => 'UTF-8', ], /* @@ -138,16 +138,16 @@ | Configure e.g. default title, creator, subject,... | */ - 'properties' => [ - 'creator' => '', + 'properties' => [ + 'creator' => '', 'lastModifiedBy' => '', - 'title' => '', - 'description' => '', - 'subject' => '', - 'keywords' => '', - 'category' => '', - 'manager' => '', - 'company' => '', + 'title' => '', + 'description' => '', + 'subject' => '', + 'keywords' => '', + 'category' => '', + 'manager' => '', + 'company' => '', ], /* @@ -158,7 +158,7 @@ | Configure middleware that is executed on getting a cell value | */ - 'cells' => [ + 'cells' => [ 'middleware' => [ //\Maatwebsite\Excel\Middleware\TrimCellValue::class, //\Maatwebsite\Excel\Middleware\ConvertEmptyCellValuesToNull::class, @@ -177,21 +177,21 @@ | */ 'extension_detector' => [ - 'xlsx' => Excel::XLSX, - 'xlsm' => Excel::XLSX, - 'xltx' => Excel::XLSX, - 'xltm' => Excel::XLSX, - 'xls' => Excel::XLS, - 'xlt' => Excel::XLS, - 'ods' => Excel::ODS, - 'ots' => Excel::ODS, - 'slk' => Excel::SLK, - 'xml' => Excel::XML, + 'xlsx' => Excel::XLSX, + 'xlsm' => Excel::XLSX, + 'xltx' => Excel::XLSX, + 'xltm' => Excel::XLSX, + 'xls' => Excel::XLS, + 'xlt' => Excel::XLS, + 'ods' => Excel::ODS, + 'ots' => Excel::ODS, + 'slk' => Excel::SLK, + 'xml' => Excel::XML, 'gnumeric' => Excel::GNUMERIC, - 'htm' => Excel::HTML, - 'html' => Excel::HTML, - 'csv' => Excel::CSV, - 'tsv' => Excel::TSV, + 'htm' => Excel::HTML, + 'html' => Excel::HTML, + 'csv' => Excel::CSV, + 'tsv' => Excel::TSV, /* |-------------------------------------------------------------------------- @@ -202,7 +202,7 @@ | Available options: Excel::MPDF | Excel::TCPDF | Excel::DOMPDF | */ - 'pdf' => Excel::DOMPDF, + 'pdf' => Excel::DOMPDF, ], /* @@ -222,11 +222,11 @@ | [x] PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder::class | */ - 'value_binder' => [ + 'value_binder' => [ 'default' => Maatwebsite\Excel\DefaultValueBinder::class, ], - 'cache' => [ + 'cache' => [ /* |-------------------------------------------------------------------------- | Default cell caching driver @@ -243,7 +243,7 @@ | Drivers: memory|illuminate|batch | */ - 'driver' => 'memory', + 'driver' => 'memory', /* |-------------------------------------------------------------------------- @@ -255,7 +255,7 @@ | Here you can tweak the memory limit to your liking. | */ - 'batch' => [ + 'batch' => [ 'memory_limit' => 60000, ], @@ -271,7 +271,7 @@ | at "null" it will use the default store. | */ - 'illuminate' => [ + 'illuminate' => [ 'store' => null, ], @@ -307,7 +307,7 @@ */ 'transactions' => [ 'handler' => 'db', - 'db' => [ + 'db' => [ 'connection' => null, ], ], @@ -325,7 +325,7 @@ | and the create file (file). | */ - 'local_path' => storage_path('framework/cache/laravel-excel'), + 'local_path' => storage_path('framework/cache/laravel-excel'), /* |-------------------------------------------------------------------------- @@ -337,7 +337,7 @@ | If omitted the default permissions of the filesystem will be used. | */ - 'local_permissions' => [ + 'local_permissions' => [ // 'dir' => 0755, // 'file' => 0644, ], @@ -356,8 +356,8 @@ | in conjunction with queued imports and exports. | */ - 'remote_disk' => null, - 'remote_prefix' => null, + 'remote_disk' => null, + 'remote_prefix' => null, /* |-------------------------------------------------------------------------- diff --git a/config/services.php b/config/services.php index 290d5eed..bcf20847 100644 --- a/config/services.php +++ b/config/services.php @@ -36,7 +36,7 @@ 'client_secret' => env('KEYCLOAK_CLIENT_SECRET'), 'redirect' => env('KEYCLOAK_REDIRECT_URI'), 'base_url' => env('KEYCLOAK_BASE_URL'), // Specify your keycloak server URL here - 'realms' => env('KEYCLOAK_REALM') // Specify your keycloak realm + 'realms' => env('KEYCLOAK_REALM'), // Specify your keycloak realm ], 'laravelpassport' => [ @@ -55,6 +55,4 @@ ], ], - - ]; diff --git a/database/factories/BudgetPlanFactory.php b/database/factories/BudgetPlanFactory.php index 214d916b..cd22b915 100644 --- a/database/factories/BudgetPlanFactory.php +++ b/database/factories/BudgetPlanFactory.php @@ -2,13 +2,11 @@ namespace Database\Factories; -use App\Models\BudgetGroup; use App\Models\BudgetItem; use App\Models\BudgetPlan; use App\Models\Enums\BudgetPlanState; use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Database\Eloquent\Factories\Sequence; class BudgetPlanFactory extends Factory { @@ -17,6 +15,7 @@ class BudgetPlanFactory extends Factory public function definition(): array { $year = Carbon::create(fake()->unique()->year()); + return [ 'state' => BudgetPlanState::FINAL, 'start_date' => $year->dayOfYear(1)->format('Y-m-d'), @@ -27,7 +26,8 @@ public function definition(): array ]; } - public function populate(){ + public function populate() + { return $this->has( BudgetItem::factory(5) ); diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index 7e3d148d..65df6680 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -3,7 +3,6 @@ namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Support\Str; /** @@ -25,5 +24,4 @@ public function definition() 'remember_token' => Str::random(10), ]; } - } diff --git a/database/migrations/2022_12_05_193814_create_legacy_tables.php b/database/migrations/2022_12_05_193814_create_legacy_tables.php index 2a7759e8..a44eeb8f 100644 --- a/database/migrations/2022_12_05_193814_create_legacy_tables.php +++ b/database/migrations/2022_12_05_193814_create_legacy_tables.php @@ -9,8 +9,6 @@ { /** * Run the migrations. - * - * @return void */ public function up(): void { @@ -20,16 +18,16 @@ public function up(): void Schema::dropIfExists('extern_data'); Schema::dropIfExists('extern_meta'); - if(!Schema::hasTable('user')){ + if (! Schema::hasTable('user')) { Schema::create('user', static function (Blueprint $table) { $table->integer('id', true); $table->string('fullname', 255); $table->string('username', 32); $table->string('email', 128); - $table->string('iban', 32)->default(""); + $table->string('iban', 32)->default(''); }); } - if(!Schema::hasTable('auslagen')) { + if (! Schema::hasTable('auslagen')) { Schema::create('auslagen', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -52,7 +50,7 @@ public function up(): void $table->string('created')->default(''); }); } - if(!Schema::hasTable('belege')) { + if (! Schema::hasTable('belege')) { Schema::create('belege', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -64,7 +62,7 @@ public function up(): void $table->integer('file_id')->nullable(); }); } - if(!Schema::hasTable('beleg_posten')) { + if (! Schema::hasTable('beleg_posten')) { Schema::create('beleg_posten', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -78,7 +76,7 @@ public function up(): void }); } - if(!Schema::hasTable('booking')) { + if (! Schema::hasTable('booking')) { Schema::create('booking', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -98,7 +96,7 @@ public function up(): void }); } - if(!Schema::hasTable('booking_instruction')) { + if (! Schema::hasTable('booking_instruction')) { Schema::create('booking_instruction', static function (Blueprint $table) { $table->comment(''); $table->integer('id'); @@ -111,7 +109,7 @@ public function up(): void }); } - if(!Schema::hasTable('comments')) { + if (! Schema::hasTable('comments')) { Schema::create('comments', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -125,7 +123,7 @@ public function up(): void }); } - if(!Schema::hasTable('filedata')) { + if (! Schema::hasTable('filedata')) { Schema::create('filedata', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -134,7 +132,7 @@ public function up(): void }); } - if(!Schema::hasTable('fileinfo')) { + if (! Schema::hasTable('fileinfo')) { Schema::create('fileinfo', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -150,7 +148,7 @@ public function up(): void }); } - if(!Schema::hasTable('haushaltsgruppen')) { + if (! Schema::hasTable('haushaltsgruppen')) { Schema::create('haushaltsgruppen', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -160,7 +158,7 @@ public function up(): void }); } - if(!Schema::hasTable('haushaltsplan')) { + if (! Schema::hasTable('haushaltsplan')) { Schema::create('haushaltsplan', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -170,7 +168,7 @@ public function up(): void }); } - if(!Schema::hasTable('haushaltstitel')) { + if (! Schema::hasTable('haushaltstitel')) { Schema::create('haushaltstitel', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -181,7 +179,7 @@ public function up(): void }); } - if(!Schema::hasTable('konto')) { + if (! Schema::hasTable('konto')) { Schema::create('konto', static function (Blueprint $table) { $table->comment(''); $table->integer('id'); @@ -204,7 +202,7 @@ public function up(): void }); } - if(!Schema::hasTable('konto_bank')) { + if (! Schema::hasTable('konto_bank')) { Schema::create('konto_bank', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -214,7 +212,7 @@ public function up(): void }); } - if(!Schema::hasTable('konto_credentials')) { + if (! Schema::hasTable('konto_credentials')) { Schema::create('konto_credentials', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -228,7 +226,7 @@ public function up(): void }); } - if(!Schema::hasTable('konto_type')) { + if (! Schema::hasTable('konto_type')) { Schema::create('konto_type', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -241,7 +239,7 @@ public function up(): void }); } - if(!Schema::hasTable('projekte')) { + if (! Schema::hasTable('projekte')) { Schema::create('projekte', static function (Blueprint $table) { $table->comment(''); $table->integer('id', true); @@ -263,7 +261,7 @@ public function up(): void $table->text('beschreibung')->nullable(); }); } - if(!Schema::hasTable('projektposten')) { + if (! Schema::hasTable('projektposten')) { Schema::create('projektposten', static function (Blueprint $table) { $table->comment(''); $table->integer('id'); diff --git a/database/migrations/2023_05_14_145739_change_float2decimal.php b/database/migrations/2023_05_14_145739_change_float2decimal.php index ebc1c5f5..68166b4b 100644 --- a/database/migrations/2023_05_14_145739_change_float2decimal.php +++ b/database/migrations/2023_05_14_145739_change_float2decimal.php @@ -11,28 +11,28 @@ */ public function up(): void { - Schema::table('projektposten', static function (Blueprint $table){ + Schema::table('projektposten', static function (Blueprint $table) { $table->decimal('einnahmen', 12, 2)->change(); $table->decimal('ausgaben', 12, 2)->change(); }); - Schema::table('konto', static function (Blueprint $table){ + Schema::table('konto', static function (Blueprint $table) { $table->decimal('value', 12, 2)->change(); }); - Schema::table('konto', static function (Blueprint $table){ + Schema::table('konto', static function (Blueprint $table) { $table->decimal('value', 12, 2)->change(); }); - Schema::table('haushaltstitel', static function (Blueprint $table){ + Schema::table('haushaltstitel', static function (Blueprint $table) { $table->decimal('value', 12, 2)->change(); }); - Schema::table('booking', static function (Blueprint $table){ + Schema::table('booking', static function (Blueprint $table) { $table->decimal('value', 12, 2)->change(); }); - Schema::table('beleg_posten', static function (Blueprint $table){ + Schema::table('beleg_posten', static function (Blueprint $table) { $table->decimal('einnahmen', 12, 2)->default(0)->change(); $table->decimal('ausgaben', 12, 2)->default(0)->change(); }); diff --git a/database/migrations/2024_04_23_125054_bank_transaction_csv.php b/database/migrations/2024_04_23_125054_bank_transaction_csv.php index 8a149167..54a3abfe 100644 --- a/database/migrations/2024_04_23_125054_bank_transaction_csv.php +++ b/database/migrations/2024_04_23_125054_bank_transaction_csv.php @@ -10,11 +10,11 @@ */ public function up(): void { - Schema::table('konto_type', function($table) { + Schema::table('konto_type', function ($table) { $table->json('csv_import_settings')->default('{}'); }); - Schema::table('konto', function($table) { + Schema::table('konto', function ($table) { $table->dropColumn('gvcode'); }); } @@ -24,10 +24,10 @@ public function up(): void */ public function down(): void { - Schema::table('konto_type', function($table) { + Schema::table('konto_type', function ($table) { $table->dropColumn('csv_import_settings'); }); - Schema::table('konto', function($table) { + Schema::table('konto', function ($table) { $table->integer('gvcode')->default(0); }); } diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index c2cb3ba7..3d889698 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -21,7 +21,7 @@ public function run() $this->call(LegacySeeder::class); - if(\App::isLocal()){ + if (\App::isLocal()) { $this->call(LocalSeeder::class); } } diff --git a/database/seeders/LegacySeeder.php b/database/seeders/LegacySeeder.php index fb59bbe8..093ae3db 100644 --- a/database/seeders/LegacySeeder.php +++ b/database/seeders/LegacySeeder.php @@ -20,7 +20,7 @@ public function run() 'gruppen_name' => 'Testgruppe Einnahmen', 'hhp_id' => 1, 'type' => 0, - ],[ + ], [ 'id' => 2, 'gruppen_name' => 'Testgruppe Einnahmen 2', 'hhp_id' => 1, @@ -43,42 +43,42 @@ public function run() [ 'titel_name' => 'Einnahme 1', 'hhpgruppen_id' => 1, - 'titel_nr' => "E1.1", + 'titel_nr' => 'E1.1', 'value' => 1000, ], [ 'titel_name' => 'Einnahme 2', 'hhpgruppen_id' => 1, - 'titel_nr' => "E1.2", + 'titel_nr' => 'E1.2', 'value' => 2000, - ],[ + ], [ 'titel_name' => 'Einnahme 3', 'hhpgruppen_id' => 2, - 'titel_nr' => "E2.1", + 'titel_nr' => 'E2.1', 'value' => 3000, ], [ 'titel_name' => 'Einnahme 4', 'hhpgruppen_id' => 2, - 'titel_nr' => "E2.2", + 'titel_nr' => 'E2.2', 'value' => 4000, ], [ 'titel_name' => 'Ausgabe 1', 'hhpgruppen_id' => 3, - 'titel_nr' => "A1.1", + 'titel_nr' => 'A1.1', 'value' => 10000, ], [ 'titel_name' => 'Ausgabe 2', 'hhpgruppen_id' => 3, - 'titel_nr' => "A1.2", + 'titel_nr' => 'A1.2', 'value' => 20000, ], [ 'titel_name' => 'Ausgabe 3', 'hhpgruppen_id' => 4, - 'titel_nr' => "A2.1", + 'titel_nr' => 'A2.1', 'value' => 10000, ], [ 'titel_name' => 'Ausgabe 4', 'hhpgruppen_id' => 4, - 'titel_nr' => "A2.2", + 'titel_nr' => 'A2.2', 'value' => 20000, ], ]); diff --git a/database/seeders/LocalSeeder.php b/database/seeders/LocalSeeder.php index 2f0f13c9..939590ef 100644 --- a/database/seeders/LocalSeeder.php +++ b/database/seeders/LocalSeeder.php @@ -30,6 +30,5 @@ public function run(): void 'provider_uid' => 'hhv', ]); - } } diff --git a/lang/de/konto.php b/lang/de/konto.php index ccf2722f..d6a44878 100644 --- a/lang/de/konto.php +++ b/lang/de/konto.php @@ -1,52 +1,52 @@ "Manueller Konto Import", - "manual-headline-sub" => "Hier können die Banktransaktionen für ein Konto manuell hochgeladen werden. Dafür musst du dich bei deiner Bank anmelden und den Kontoauszug als .csv Datei herunterladen. Eine .csv Datei ist eine Art einfaches Tabellenblatt und kann hier direkt hochgeladen werden.", - "csv-label-choose-konto" => "Wähle hier das Konto aus, für welches du den Kontoauszug hochladen willst.", - "csv-upload-headline" => "CSV-Upload", - "csv-upload-headline-sub" => "Lade hier die .csv Datei durch Auswählen oder Hineinziehen hoch. Die Inhalte werden noch nicht gespeichert, sondern zunächst nur als Vorschau angezeigt. Es kann zu Fehlern kommen, wenn die Datei nicht im richtigen Format gespeichert wurde.", - "csv-draganddrop-fat-text" => "Füge hier die .csv Datei hinzu!", - "csv-draganddrop-light-text" => "", - "csv-draganddrop-sub-text" => "Ziehe die Datei hier in das Feld oder wähle sie über den Knopf aus. Es kann einen Moment dauern, bis die Informationen geladen werden.", - "manual-button-reverse-csv-order" => "Reihenfolge der Einträge umkehren", - "manual-button-reverse-csv-order-sub" => "Einige Banken exportieren Transaktionsdaten chronologisch aufsteigend, andere absteigend. StuFiS hätte gern den ältesten Eintrag zuerst. Falls die Tabelle falsch herum sortiert ist oder z. B. die Saldo-Validierung fehlschlägt, kannst du hier über den Knopf die Reihenfolge ändern.", - "manual-button-submit" => "Vorschau anzeigen", - "manual-button-assign" => "Importieren", - "csv-button-new-konto" => "Neues Konto anlegen", - "csv-preview-first" => "Erster Eintrag (csv)", - "csv-preview-last" => "Letzter Eintrag (csv)", - "csv-no-transaction" => "Es gibt auf diesem Konto bisher keine Transaktionen", - "csv-latest-saldo" => "aktueller Saldo", - "csv-latest-date" => "Datum der letzten Kontobuchung", - "csv-latest-zweck" => "letzter Verwendungszweck", - "csv-import-success-msg" => ":transaction-amount Kontoauszüge erfolgreich importiert. Neuer Saldo ist: :new-saldo €", - "transaction.headline" => "Zuordnung der Tabellenspalten", - "transaction.headline-sub" => "Ordne hier den vorgegebenen Feldern die korrekte Tabellenüberschrift aus deiner .csv Datei hinzu. Du hast immer einen Beispielwert stehen, an dem du dich orientieren kannst. Wenn du eine Zuordnung getroffen hast, wird dir darunter der erste und letzte Zeileneintrag der .csv Datei in der jeweiligen Spalte angezeigt. Bitte überprüfe die Zuordnung genau. Nach dem Drücken des Importieren-Knopfes werden die Daten so gespeichert und können nicht mehr angepasst werden. Das StuFiS wird sich in Zukunft die Zuordnung merken und dir diese direkt vorschlagen. Einzelne Felder wie Primanota müssen nicht zwingend gefüllt werden. ACHTUNG: wir raten dringend davon ab, die .csv Datei nach dem Download bei der Bank noch einmal in Excel zu öffnen und neu abzuspeichern. Das kann u. a. zu Fehlern bei den Umlauten führen.", - "label.transaction.date" => "Ausführungsdatum", - "hint.transaction.date" => "z. B. 13.08.2021", - "label.transaction.valuta" => "Valuta-/Wertstellungsdatum", - "hint.transaction.valuta" => "z. B. 14.08.2021", - "label.transaction.type" => "Transaktionstyp", - "hint.transaction.type" => "z. B. Dauerauftrag, Bareinzahlung, ...", - "label.transaction.empf_iban" => "Zahlungsbeteiligte:r IBAN", - "hint.transaction.empf_iban" => "z. B. DE02120300000000202051", - "label.transaction.empf_bic" => "Zahlungsbeteiligte:r BIC", - "hint.transaction.empf_bic" => "z. B. BYLADEM1001", - "label.transaction.empf_name" => "Zahlungsbeteiligte:r Name", - "hint.transaction.empf_name" => "z. B. Maxi Musterstudi", - "label.transaction.primanota" => "Primanota", - "hint.transaction.primanota" => "z. B. 420", - "label.transaction.value" => "Wert", - "hint.transaction.value" => "z. B. 42,69", - "label.transaction.saldo" => "Saldo", - "hint.transaction.saldo" => "z. B. 42.690,00", - "label.transaction.zweck" => "Verwendungszweck", - "hint.transaction.zweck" => "z. B. Gute Lehre Abo", - "label.transaction.comment" => "Kommentar", - "hint.transaction.comment" => " ", - "label.transaction.customer_ref" => "Kundenreferenz", - "hint.transaction.customer_ref" => "ggfs. weitere Angaben zum Auftrag", + 'manual-headline' => 'Manueller Konto Import', + 'manual-headline-sub' => 'Hier können die Banktransaktionen für ein Konto manuell hochgeladen werden. Dafür musst du dich bei deiner Bank anmelden und den Kontoauszug als .csv Datei herunterladen. Eine .csv Datei ist eine Art einfaches Tabellenblatt und kann hier direkt hochgeladen werden.', + 'csv-label-choose-konto' => 'Wähle hier das Konto aus, für welches du den Kontoauszug hochladen willst.', + 'csv-upload-headline' => 'CSV-Upload', + 'csv-upload-headline-sub' => 'Lade hier die .csv Datei durch Auswählen oder Hineinziehen hoch. Die Inhalte werden noch nicht gespeichert, sondern zunächst nur als Vorschau angezeigt. Es kann zu Fehlern kommen, wenn die Datei nicht im richtigen Format gespeichert wurde.', + 'csv-draganddrop-fat-text' => 'Füge hier die .csv Datei hinzu!', + 'csv-draganddrop-light-text' => '', + 'csv-draganddrop-sub-text' => 'Ziehe die Datei hier in das Feld oder wähle sie über den Knopf aus. Es kann einen Moment dauern, bis die Informationen geladen werden.', + 'manual-button-reverse-csv-order' => 'Reihenfolge der Einträge umkehren', + 'manual-button-reverse-csv-order-sub' => 'Einige Banken exportieren Transaktionsdaten chronologisch aufsteigend, andere absteigend. StuFiS hätte gern den ältesten Eintrag zuerst. Falls die Tabelle falsch herum sortiert ist oder z. B. die Saldo-Validierung fehlschlägt, kannst du hier über den Knopf die Reihenfolge ändern.', + 'manual-button-submit' => 'Vorschau anzeigen', + 'manual-button-assign' => 'Importieren', + 'csv-button-new-konto' => 'Neues Konto anlegen', + 'csv-preview-first' => 'Erster Eintrag (csv)', + 'csv-preview-last' => 'Letzter Eintrag (csv)', + 'csv-no-transaction' => 'Es gibt auf diesem Konto bisher keine Transaktionen', + 'csv-latest-saldo' => 'aktueller Saldo', + 'csv-latest-date' => 'Datum der letzten Kontobuchung', + 'csv-latest-zweck' => 'letzter Verwendungszweck', + 'csv-import-success-msg' => ':transaction-amount Kontoauszüge erfolgreich importiert. Neuer Saldo ist: :new-saldo €', + 'transaction.headline' => 'Zuordnung der Tabellenspalten', + 'transaction.headline-sub' => 'Ordne hier den vorgegebenen Feldern die korrekte Tabellenüberschrift aus deiner .csv Datei hinzu. Du hast immer einen Beispielwert stehen, an dem du dich orientieren kannst. Wenn du eine Zuordnung getroffen hast, wird dir darunter der erste und letzte Zeileneintrag der .csv Datei in der jeweiligen Spalte angezeigt. Bitte überprüfe die Zuordnung genau. Nach dem Drücken des Importieren-Knopfes werden die Daten so gespeichert und können nicht mehr angepasst werden. Das StuFiS wird sich in Zukunft die Zuordnung merken und dir diese direkt vorschlagen. Einzelne Felder wie Primanota müssen nicht zwingend gefüllt werden. ACHTUNG: wir raten dringend davon ab, die .csv Datei nach dem Download bei der Bank noch einmal in Excel zu öffnen und neu abzuspeichern. Das kann u. a. zu Fehlern bei den Umlauten führen.', + 'label.transaction.date' => 'Ausführungsdatum', + 'hint.transaction.date' => 'z. B. 13.08.2021', + 'label.transaction.valuta' => 'Valuta-/Wertstellungsdatum', + 'hint.transaction.valuta' => 'z. B. 14.08.2021', + 'label.transaction.type' => 'Transaktionstyp', + 'hint.transaction.type' => 'z. B. Dauerauftrag, Bareinzahlung, ...', + 'label.transaction.empf_iban' => 'Zahlungsbeteiligte:r IBAN', + 'hint.transaction.empf_iban' => 'z. B. DE02120300000000202051', + 'label.transaction.empf_bic' => 'Zahlungsbeteiligte:r BIC', + 'hint.transaction.empf_bic' => 'z. B. BYLADEM1001', + 'label.transaction.empf_name' => 'Zahlungsbeteiligte:r Name', + 'hint.transaction.empf_name' => 'z. B. Maxi Musterstudi', + 'label.transaction.primanota' => 'Primanota', + 'hint.transaction.primanota' => 'z. B. 420', + 'label.transaction.value' => 'Wert', + 'hint.transaction.value' => 'z. B. 42,69', + 'label.transaction.saldo' => 'Saldo', + 'hint.transaction.saldo' => 'z. B. 42.690,00', + 'label.transaction.zweck' => 'Verwendungszweck', + 'hint.transaction.zweck' => 'z. B. Gute Lehre Abo', + 'label.transaction.comment' => 'Kommentar', + 'hint.transaction.comment' => ' ', + 'label.transaction.customer_ref' => 'Kundenreferenz', + 'hint.transaction.customer_ref' => 'ggfs. weitere Angaben zum Auftrag', 'csv-verify-iban-error' => 'Validierungsfehler: Enthält ungültige IBANs', 'csv-verify-money-error' => 'Validierungsfehler: Enthält nicht-numerische Daten', 'csv-verify-balance-error-wrong-datatype' => 'Validierungsfehler: Falscher Datentyp', diff --git a/lang/de/validation.php b/lang/de/validation.php index 4a9a69af..0d006e7c 100644 --- a/lang/de/validation.php +++ b/lang/de/validation.php @@ -177,17 +177,17 @@ 'decision_date' => 'Beschluss Datum', 'username' => 'Nutzer:innenname', 'mapping.date' => 'Ausführungsdatum', - "mapping.valuta" => "Valuta-/Wertstellungsdatum", - "mapping.type" => "Transaktionstyp", - "mapping.empf_iban" => "Empfänger IBAN", - "mapping.empf_bic" => "Empfänger BIC", - "mapping.empf_name" => "Empfänger Name", - "mapping.primanota" => "Primanota", - "mapping.value" => "Wert", - "mapping.saldo" => "Saldo", - "mapping.zweck" => "Verwendungszweck", - "mapping.comment" => "Kommentar", - "mapping.customer_ref" => "Kundenreferenz", + 'mapping.valuta' => 'Valuta-/Wertstellungsdatum', + 'mapping.type' => 'Transaktionstyp', + 'mapping.empf_iban' => 'Empfänger IBAN', + 'mapping.empf_bic' => 'Empfänger BIC', + 'mapping.empf_name' => 'Empfänger Name', + 'mapping.primanota' => 'Primanota', + 'mapping.value' => 'Wert', + 'mapping.saldo' => 'Saldo', + 'mapping.zweck' => 'Verwendungszweck', + 'mapping.comment' => 'Kommentar', + 'mapping.customer_ref' => 'Kundenreferenz', ], ]; diff --git a/legacy/config/config.routing.php b/legacy/config/config.routing.php index 6fc06f6e..4fbdbed7 100644 --- a/legacy/config/config.routing.php +++ b/legacy/config/config.routing.php @@ -231,7 +231,7 @@ 'path' => 'exportBank', 'type' => 'path', 'action' => 'exportBank', - 'groups' => 'ref-finanzen-kv' + 'groups' => 'ref-finanzen-kv', ], ], ], diff --git a/legacy/lib/booking/BookingHandler.php b/legacy/lib/booking/BookingHandler.php index c66d396a..64f4a36b 100644 --- a/legacy/lib/booking/BookingHandler.php +++ b/legacy/lib/booking/BookingHandler.php @@ -26,33 +26,33 @@ public function render(): void switch ($this->routeInfo['action']) { case 'instruct': $this->renderBooking('instruct'); - break; + break; case 'confirm-instruct': $this->setBookingTabs('text', $this->routeInfo['hhp-id']); $this->renderBookingText(); - break; + break; case 'konto': $kontoId = $this->routeInfo['konto-id'] ?? 0; $this->renderKonto($kontoId); - break; + break; case 'history': $this->renderBookingHistory('history'); - break; + break; case 'export-csv': $this->renderCSV(); - break; + break; case 'export-zip': $this->renderFullBookingZip(); - break; + break; default: throw new LegacyDieException(400, "Action: {$this->routeInfo['action']} kann nicht interpretiert werden"); - break; + break; } } private function setBookingTabs($active, $active_hhp_id): void { - $linkbase = URIBASE . "booking/$active_hhp_id/"; + $linkbase = URIBASE."booking/$active_hhp_id/"; $tabs = [ 'instruct' => " Anweisen", 'text' => " Durchführen", @@ -63,7 +63,7 @@ private function setBookingTabs($active, $active_hhp_id): void private function renderCSV(): void { - if (!isset($this->routeInfo['hhp-id'])) { + if (! isset($this->routeInfo['hhp-id'])) { throw new LegacyDieException(400, 'hhp-id nicht gesetzt'); } [$kontoTypes, $data] = $this->fetchBookingHistoryDataFromDB($this->routeInfo['hhp-id']); @@ -80,19 +80,19 @@ private function renderCSV(): void 'comment' => 'Buchungstext', ]; foreach ($data as $lfdNr => $row) { - $userStr = isset($row['fullname']) ? $row['fullname'] . ' (' . $row['username'] . ')' : $row['username']; + $userStr = isset($row['fullname']) ? $row['fullname'].' ('.$row['username'].')' : $row['username']; $belegStr = ''; switch ($row['beleg_type']) { case 'belegposten': - $belegStr = "IP{$row['projekt_id']} A{$row['auslagen_id']} - " . $row['short']; - break; + $belegStr = "IP{$row['projekt_id']} A{$row['auslagen_id']} - ".$row['short']; + break; case 'extern': $belegStr = "E{$row['extern_id']} - V n.a."; - break; + break; default: - throw new LegacyDieException(400, 'Unknown beleg_type: ' . $row['beleg_type']); - break; + throw new LegacyDieException(400, 'Unknown beleg_type: '.$row['beleg_type']); + break; } $csvData[] = [ @@ -102,7 +102,7 @@ private function renderCSV(): void 'beleg_name' => $belegStr, 'datum' => $row['timestamp'], 'user' => $userStr, - 'zahlung-name' => $kontoTypes[$row['zahlung_type']]['short'] . $row['zahlung_id'], + 'zahlung-name' => $kontoTypes[$row['zahlung_type']]['short'].$row['zahlung_id'], 'zahlung-datum' => $row['zahlung_date'], 'comment' => $row['comment'], ]; @@ -112,21 +112,21 @@ private function renderCSV(): void $hhp = $hhps[$this->routeInfo['hhp-id']]; $von = date_create($hhp['von'])->format('Y-m'); $bis = date_create($hhp['bis'])->format('Y-m'); - $csvBuilder->echoCSV(date_create()->format('Y-m-d') . "-Buchungsliste-$von-bis-$bis"); + $csvBuilder->echoCSV(date_create()->format('Y-m-d')."-Buchungsliste-$von-bis-$bis"); } private function renderFullBookingZip(): void { - if (!isset($this->routeInfo['hhp-id'])) { + if (! isset($this->routeInfo['hhp-id'])) { throw new LegacyDieException(400, 'hhp-id nicht gesetzt'); } - $zip = new ZipArchive(); + $zip = new ZipArchive; $zipFileName = 'HHA.zip'; $zipFilePath = tempnam(sys_get_temp_dir(), 'HHA'); if (($ret = $zip->open($zipFilePath, ZipArchive::OVERWRITE)) !== true) { - throw new LegacyDieException(500, 'Zip kann nicht erstellt werden.', 'ErrorCode: ' . $ret); + throw new LegacyDieException(500, 'Zip kann nicht erstellt werden.', 'ErrorCode: '.$ret); } [$kontoTypes, $data] = $this->fetchBookingHistoryDataFromDB( @@ -156,40 +156,40 @@ private function renderFullBookingZip(): void foreach ($dataByTitel as $titel_nr => $items) { foreach ($items as $key => $row) { - $items[$key]['zahlung'] = $kontoTypes[$row['zahlung_type']]['short'] . $row['zahlung_id']; + $items[$key]['zahlung'] = $kontoTypes[$row['zahlung_type']]['short'].$row['zahlung_id']; $items[$key]['einnahmen'] = ($row['zahlung_value'] > 0) ? (float) $row['zahlung_value'] : '0.00'; $items[$key]['ausgaben'] = ($row['zahlung_value'] < 0) ? -(float) $row['zahlung_value'] : '0.00'; switch ($row['beleg_type']) { case 'belegposten': $items[$key]['beleg_type'] = 'Intern'; - break; + break; case 'extern': $items[$key]['beleg_type'] = 'Extern'; - break; + break; default: - throw new LegacyDieException(400, $row['beleg_type'] . 'kann nicht interpretiert werden'); - break; + throw new LegacyDieException(400, $row['beleg_type'].'kann nicht interpretiert werden'); + break; } } $items[] = [ 'id' => '', 'zahlung_date' => 'Summe', - 'value' => '=SUM(C2:C' . (count($items) + 1) . ')', + 'value' => '=SUM(C2:C'.(count($items) + 1).')', 'zahlung' => '', - 'einnahmen' => '=SUM(E2:E' . (count($items) + 1) . ')', - 'ausgaben' => '=SUM(F2:F' . (count($items) + 1) . ')', + 'einnahmen' => '=SUM(E2:E'.(count($items) + 1).')', + 'ausgaben' => '=SUM(F2:F'.(count($items) + 1).')', 'beleg_type' => '', 'comment' => '', ]; $csvHandler = new CSVBuilder($items, $header); $csvString = $csvHandler->getCSV(); - $zip->addFromString($titel_nr . '.csv', $csvString); + $zip->addFromString($titel_nr.'.csv', $csvString); } if ($zip->close() === true && ($content = file_get_contents($zipFilePath)) !== false) { header('Content-Type: application/zip'); - header('Content-disposition: attachment; filename=' . $zipFileName); - header('Content-Length: ' . filesize($zipFileName)); + header('Content-disposition: attachment; filename='.$zipFileName); + header('Content-Length: '.filesize($zipFileName)); echo $content; unlink($zipFilePath); } else { @@ -265,12 +265,12 @@ private function fetchBookingHistoryDataFromDB($hhp_id, $sortBy = ['timestamp' = private function renderBookingHistory($active): void { - [$hhps, $hhp_id] = $this->renderHHPSelector($this->routeInfo, URIBASE . 'booking/', '/history'); + [$hhps, $hhp_id] = $this->renderHHPSelector($this->routeInfo, URIBASE.'booking/', '/history'); $this->setBookingTabs($active, $hhp_id); [$kontoTypes, $ret] = $this->fetchBookingHistoryDataFromDB($hhp_id); - if (!empty($ret)) { + if (! empty($ret)) { // var_dump(reset($ret));?> @@ -288,7 +288,7 @@ private function renderBookingHistory($active): void $row) { - $userStr = isset($row['fullname']) ? $row['fullname'] . ' (' . $row['username'] . ')' : $row['username']; ?> + $userStr = isset($row['fullname']) ? $row['fullname'].' ('.$row['username'].')' : $row['username']; ?> - " . generateLinkFromID( - "A$auslagenId - B" . $row['short'], - "projekt/$projektId/auslagen/$auslagenId", - TextStyle::BLACK - ) . ''; - break; + echo "'; + break; case 'extern': $eId = $row['extern_id']; - $vId = "n.a."; + $vId = 'n.a.'; /*generateLinkFromID( "E$eId - V" . $vId, "rest/extern/$eId/$vId", @@ -322,9 +322,9 @@ private function renderBookingHistory($active): void ?> + $row['comment'] + ); ?> @@ -399,7 +399,7 @@ private function setKontoTabs(int $active, int $selected_hhp_id, array $kontos): { // TODO: filter kontos? $kontos = array_map(fn ($item) => $item['name'], $kontos); - $linkbase = URIBASE . "konto/$selected_hhp_id/"; + $linkbase = URIBASE."konto/$selected_hhp_id/"; $tabs = []; foreach ($kontos as $id => $kontoName) { $icon = $id > 0 ? 'fa-credit-card' : 'fa-money'; @@ -410,7 +410,7 @@ private function setKontoTabs(int $active, int $selected_hhp_id, array $kontos): private function renderKonto(int $kontoId = 0): void { - [$hhps, $selected_id] = $this->renderHHPSelector($this->routeInfo, URIBASE . 'konto/', '/' . $kontoId); + [$hhps, $selected_id] = $this->renderHHPSelector($this->routeInfo, URIBASE.'konto/', '/'.$kontoId); $startDate = $hhps[$selected_id]['von']; $endDate = $hhps[$selected_id]['bis']; $where = ['konto_id' => $kontoId]; @@ -486,16 +486,16 @@ private function renderKontoKasse(int $kontoId, array $alZahlung, array $kontos) $prefix = $kontos[$row['konto_id']]['short']; echo ''; echo ""; - echo ''; + echo ''; echo ""; - echo "'; - echo "'; + echo "'; + echo "'; echo ''; echo ''; } ?> @@ -521,15 +521,15 @@ private function renderKontoBank(array $alZahlung, array $kontos) + $prefix = $kontos[$zahlung['konto_id']]['short']; + $vzweck = explode('DATUM', $zahlung['zweck'])[0]; + if (empty($vzweck)) { + $vzweck = $zahlung['type']; + } ?> - + @@ -543,7 +543,7 @@ private function renderKontoBank(array $alZahlung, array $kontos) + } ?>
@@ -297,7 +297,7 @@ private function renderBookingHistory($active): void convertDBValueToUserValue($row['value'], 'money'); ?> + ".generateLinkFromID( + "A$auslagenId - B".$row['short'], + "projekt/$projektId/auslagen/$auslagenId", + TextStyle::BLACK + ).'
- + renderNonce() ?> @@ -333,21 +333,21 @@ class="ajax-form">
- + title=""> + $kontoTypes[$row['zahlung_type']]['short'].$row['zahlung_id'], + '', + TextStyle::BLACK + ); ?> @@ -369,8 +369,8 @@ class='submit-form '> Durch '>B-Nr:
{$prefix}{$row['id']}' . date_create($row['date'])->format('d.m.Y') . ''.date_create($row['date'])->format('d.m.Y').'{$row['type']} - {$row['zweck']}" . DBConnector::getInstance()->convertDBValueToUserValue( - $row['value'], - 'money' - ) . '" . DBConnector::getInstance()->convertDBValueToUserValue( - $row['saldo'], - 'money' - ) . '".DBConnector::getInstance()->convertDBValueToUserValue( + $row['value'], + 'money' + ).'".DBConnector::getInstance()->convertDBValueToUserValue( + $row['saldo'], + 'money' + ).'FIXME
hasGroup('ref-finanzen'); - echo "Kontoauszüge importieren: "; + echo 'Kontoauszüge importieren: '; echo HtmlButton::make() - ->asLink(URIBASE . 'konto/credentials') + ->asLink(URIBASE.'konto/credentials') ->style('primary') ->icon('refresh') - ->disable(!$isKv) - ->title(!$isKv ? 'Nur durch Kassenverantwortliche möglich' : '') + ->disable(! $isKv) + ->title(! $isKv ? 'Nur durch Kassenverantwortliche möglich' : '') ->body('mit Bankzugang'); - echo " "; + echo ' '; echo HtmlButton::make() - ->asLink(URIBASE . 'konto/import/manual') + ->asLink(URIBASE.'konto/import/manual') ->style('primary') ->icon('upload') - ->disable(!$isKv) - ->title(!$isKv ? 'Nur durch Kassenverantwortliche möglich' : '') + ->disable(! $isKv) + ->title(! $isKv ? 'Nur durch Kassenverantwortliche möglich' : '') ->body('mit CSV'); } private function renderBookingText(): void { - $btm = new BookingTableManager(); + $btm = new BookingTableManager; $btm->render(); } private function renderBooking(string $active): void { - [$hhps, $hhp_id] = $this->renderHHPSelector($this->routeInfo, URIBASE . 'booking/', '/instruct'); + [$hhps, $hhp_id] = $this->renderHHPSelector($this->routeInfo, URIBASE.'booking/', '/instruct'); $this->setBookingTabs($active, $hhp_id); $startDate = $hhps[$hhp_id]['von']; $endDate = $hhps[$hhp_id]['bis']; - if (!isset($endDate) || empty($endDate)) { + if (! isset($endDate) || empty($endDate)) { $fixedWhere = [ 'date' => ['>=', $startDate], ]; @@ -710,89 +710,89 @@ static function ($e1, $e2) { '; - if (isset($alZahlung[$idxZahlung])) { - if (isset($alGrund[$idxGrund])) { - $value = min( - [(float) $alZahlung[$idxZahlung]['value'], $alGrund[$idxGrund]['value']] - ); - } else { - // var_dump($alZahlung[$idxZahlung]); - $value = (float) $alZahlung[$idxZahlung]['value']; - } + $idxGrund = 0; + while ($idxZahlung < count($alZahlung) || $idxGrund < count($alGrund)) { + echo ''; + if (isset($alZahlung[$idxZahlung])) { + if (isset($alGrund[$idxGrund])) { + $value = min( + [(float) $alZahlung[$idxZahlung]['value'], $alGrund[$idxGrund]['value']] + ); } else { - $value = $alGrund[$idxGrund]['value']; + // var_dump($alZahlung[$idxZahlung]); + $value = (float) $alZahlung[$idxZahlung]['value']; } - echo ''; - - while (isset($alZahlung[$idxZahlung]) && (float) $alZahlung[$idxZahlung]['value'] === $value) { - echo ""; - - // print_r($alZahlung[$idxZahlung]); - if ((int) $alZahlung[$idxZahlung]['konto_id'] === 0) { - $caption = "K{$alZahlung[$idxZahlung]['id']} - {$alZahlung[$idxZahlung]['type']} - {$alZahlung[$idxZahlung]['zweck']}"; - $title = "BELEG: {$alZahlung[$idxZahlung]['comment']}" . PHP_EOL . "DATUM: {$alZahlung[$idxZahlung]['date']}"; - } else { - $title = 'VALUTA: ' . $alZahlung[$idxZahlung]['valuta'] . PHP_EOL . 'IBAN: ' . $alZahlung[$idxZahlung]['empf_iban'] . PHP_EOL . 'BIC: ' . $alZahlung[$idxZahlung]['empf_bic']; - $caption = $konto_types[$alZahlung[$idxZahlung]['konto_id']]['short']; - $caption .= $alZahlung[$idxZahlung]['id'] . ' - '; - // shorten and simplify some types - $caption .= match ($alZahlung[$idxZahlung]['type']) { - 'FOLGELASTSCHRIFT' => 'LASTSCHRIFT', - 'ONLINE-UEBERWEISUNG' => 'ÜBERWEISUNG', - 'UEBERWEISUNGSGUTSCHRIFT' => 'GUTSCHRIFT', - default => $alZahlung[$idxZahlung]['type'], - }; - $caption .= $value < 0 ? ' an ' : ' von '; - $caption .= $alZahlung[$idxZahlung]['empf_name'] . ' - ' . - explode('DATUM', $alZahlung[$idxZahlung]['zweck'])[0]; - } - - $url = str_replace('//', '/', URIBASE . '/zahlung/' . $alZahlung[$idxZahlung]['id']); - echo "" . htmlspecialchars($caption) . ''; - ++$idxZahlung; - echo '
'; + } else { + $value = $alGrund[$idxGrund]['value']; + } + echo ''; + + while (isset($alZahlung[$idxZahlung]) && (float) $alZahlung[$idxZahlung]['value'] === $value) { + echo ""; + + // print_r($alZahlung[$idxZahlung]); + if ((int) $alZahlung[$idxZahlung]['konto_id'] === 0) { + $caption = "K{$alZahlung[$idxZahlung]['id']} - {$alZahlung[$idxZahlung]['type']} - {$alZahlung[$idxZahlung]['zweck']}"; + $title = "BELEG: {$alZahlung[$idxZahlung]['comment']}".PHP_EOL."DATUM: {$alZahlung[$idxZahlung]['date']}"; + } else { + $title = 'VALUTA: '.$alZahlung[$idxZahlung]['valuta'].PHP_EOL.'IBAN: '.$alZahlung[$idxZahlung]['empf_iban'].PHP_EOL.'BIC: '.$alZahlung[$idxZahlung]['empf_bic']; + $caption = $konto_types[$alZahlung[$idxZahlung]['konto_id']]['short']; + $caption .= $alZahlung[$idxZahlung]['id'].' - '; + // shorten and simplify some types + $caption .= match ($alZahlung[$idxZahlung]['type']) { + 'FOLGELASTSCHRIFT' => 'LASTSCHRIFT', + 'ONLINE-UEBERWEISUNG' => 'ÜBERWEISUNG', + 'UEBERWEISUNGSGUTSCHRIFT' => 'GUTSCHRIFT', + default => $alZahlung[$idxZahlung]['type'], + }; + $caption .= $value < 0 ? ' an ' : ' von '; + $caption .= $alZahlung[$idxZahlung]['empf_name'].' - '. + explode('DATUM', $alZahlung[$idxZahlung]['zweck'])[0]; } - echo ""; - echo DBConnector::getInstance()->convertDBValueToUserValue($value, 'money'); - echo ''; - while (isset($alGrund[$idxGrund]) && $alGrund[$idxGrund]['value'] === $value) { - switch ($alGrund[$idxGrund]['type']) { - case 'auslage': - echo ""; - $caption = 'A' . $alGrund[$idxGrund]['id'] . ' - ' . $alGrund[$idxGrund]['name'] . ' - ' . $alGrund[$idxGrund]['name_suffix']; - $url = str_replace( - '//', - '/', - URIBASE . "/projekt/{$alGrund[$idxGrund]['projekt_id']}/auslagen/" . $alGrund[$idxGrund]['id'] - ); - break; - /*case 'extern': - echo ""; - $caption = 'E' . $alGrund[$idxGrund]['extern_id'] . '-V' . $alGrund[$idxGrund]['vorgang_id'] . - ' - ' . $alGrund[$idxGrund]['projekt_name'] . ' - ' . $alGrund[$idxGrund]['org_name']; - $url = str_replace( - '//', - '/', - URIBASE . '/extern/' . $alGrund[$idxGrund]['extern_id'] - ); - break;*/ - default: - throw new LegacyDieException(400, 'Type ' . $alGrund[$idxGrund]['type'] . ' not known'); - break; - } - echo "" . $caption . ''; - ++$idxGrund; - echo '
'; + $url = str_replace('//', '/', URIBASE.'/zahlung/'.$alZahlung[$idxZahlung]['id']); + echo "".htmlspecialchars($caption).''; + $idxZahlung++; + echo '
'; + } + echo ""; + echo DBConnector::getInstance()->convertDBValueToUserValue($value, 'money'); + echo ''; + while (isset($alGrund[$idxGrund]) && $alGrund[$idxGrund]['value'] === $value) { + switch ($alGrund[$idxGrund]['type']) { + case 'auslage': + echo ""; + $caption = 'A'.$alGrund[$idxGrund]['id'].' - '.$alGrund[$idxGrund]['name'].' - '.$alGrund[$idxGrund]['name_suffix']; + $url = str_replace( + '//', + '/', + URIBASE."/projekt/{$alGrund[$idxGrund]['projekt_id']}/auslagen/".$alGrund[$idxGrund]['id'] + ); + break; + /*case 'extern': + echo ""; + $caption = 'E' . $alGrund[$idxGrund]['extern_id'] . '-V' . $alGrund[$idxGrund]['vorgang_id'] . + ' - ' . $alGrund[$idxGrund]['projekt_name'] . ' - ' . $alGrund[$idxGrund]['org_name']; + $url = str_replace( + '//', + '/', + URIBASE . '/extern/' . $alGrund[$idxGrund]['extern_id'] + ); + break;*/ + default: + throw new LegacyDieException(400, 'Type '.$alGrund[$idxGrund]['type'].' not known'); + break; } - echo ''; - echo ''; - } ?> + + echo "".$caption.''; + $idxGrund++; + echo '
'; + } + echo ''; + echo ''; + } ?> "; + $out .= "
"; if ($daterange) { $out .= "
von
"; $out .= "
"; @@ -601,6 +611,7 @@ public function getDatePickerForm($names, $value = '', $width = 12, $placeholder } } $out .= '
'; + return $this->getOutputWrapped($out, $width, $editable, $names[0], $unique_id0, $label_text, $validator); } diff --git a/legacy/lib/forms/RestHandler.php b/legacy/lib/forms/RestHandler.php index 33de4d16..c4df4e70 100644 --- a/legacy/lib/forms/RestHandler.php +++ b/legacy/lib/forms/RestHandler.php @@ -3,11 +3,16 @@ * FRAMEWORK JsonHandler * * @category framework + * * @author michael g * @author Stura - Referat IT + * * @since 17.02.2018 + * * @copyright Copyright (C) 2018 - All rights reserved + * * @platform PHP + * * @requirements PHP 7.0 or higher */ @@ -41,10 +46,10 @@ class RestHandler extends EscFunc { // ================================================================================================ - public function handlePost(array $routeInfo = null): void + public function handlePost(?array $routeInfo = null): void { - if(!\App::runningUnitTests()){ - if (!isset($_POST['nonce']) || $_POST['nonce'] !== csrf_token() || isset($_POST['nononce'])) { + if (! \App::runningUnitTests()) { + if (! isset($_POST['nonce']) || $_POST['nonce'] !== csrf_token() || isset($_POST['nononce'])) { throw new LegacyDieException(400, 'Das Formular ist nicht gültig, bitte lade die Seite neu'); } } @@ -90,9 +95,9 @@ public function handlePost(array $routeInfo = null): void case 'save-default-tan-mode': $this->saveDefaultTanMode($routeInfo); break; - /*case "login-credentials": - $this->loginCredentials($routeInfo); - break;*/ + /*case "login-credentials": + $this->loginCredentials($routeInfo); + break;*/ case 'lock-credentials': $this->lockCredentials($routeInfo); break; @@ -119,8 +124,8 @@ public function handlePost(array $routeInfo = null): void break; case 'nononce': default: - throw new LegacyDieException(400, 'Unknown Action: ' . $routeInfo['action']); - break; + throw new LegacyDieException(400, 'Unknown Action: '.$routeInfo['action']); + break; } } @@ -178,7 +183,7 @@ public function saveNewKasseEntry(): void ] ); } - $fields['type'] = 'BAR-' . ($fields['value'] > 0 ? 'EIN' : 'AUS'); + $fields['type'] = 'BAR-'.($fields['value'] > 0 ? 'EIN' : 'AUS'); if ($fields['id'] === '1') { DBConnector::getInstance()->dbInsert('konto', $fields); } else { @@ -227,7 +232,7 @@ public function handleProjekt($routeInfo = null): void try { - if (!isset($_POST['action'])) { + if (! isset($_POST['action'])) { throw new ActionNotSetException('Es wurde keine Aktion übertragen'); } @@ -243,14 +248,14 @@ public function handleProjekt($routeInfo = null): void } break; case 'changeState': - if (!isset($_POST['id']) || !is_numeric($_POST['id'])) { + if (! isset($_POST['id']) || ! is_numeric($_POST['id'])) { throw new IdNotSetException('ID nicht gesetzt.'); } $projektHandler = new ProjektHandler(['pid' => $_POST['id'], 'action' => 'none']); $ret = $projektHandler->setState($_POST['newState']); break; case 'update': - if (!isset($_POST['id']) || !is_numeric($_POST['id'])) { + if (! isset($_POST['id']) || ! is_numeric($_POST['id'])) { throw new IdNotSetException('ID nicht gesetzt.'); } $projektHandler = new ProjektHandler(['pid' => $_POST['id'], 'action' => 'edit']); @@ -262,26 +267,26 @@ public function handleProjekt($routeInfo = null): void } } catch (ActionNotSetException|IdNotSetException|WrongVersionException| InvalidDataException|PDOException|IllegalTransitionException $exception) { - $ret = false; - $msgs[] = 'Ein Fehler ist aufgetreten'; - $msgs[] = $exception->getMessage(); - } catch (IllegalStateException $exception) { - $ret = false; - $msgs[] = 'In diesen Status darf nicht gewechselt werden!'; - $msgs[] = $exception->getMessage(); - } finally { - if ($ret) { - $dbret = DBConnector::getInstance()->dbCommit(); - } - if ($ret === false || $dbret === false) { - DBConnector::getInstance()->dbRollBack(); - $msgs[] = 'Deine Änderungen wurden nicht gespeichert (DB Rollback)'; - } else { - $msgs[] = 'Daten erfolgreich gespeichert!'; - $target = URIBASE . 'projekt/' . $projektHandler->getID(); - } + $ret = false; + $msgs[] = 'Ein Fehler ist aufgetreten'; + $msgs[] = $exception->getMessage(); + } catch (IllegalStateException $exception) { + $ret = false; + $msgs[] = 'In diesen Status darf nicht gewechselt werden!'; + $msgs[] = $exception->getMessage(); + } finally { + if ($ret) { + $dbret = DBConnector::getInstance()->dbCommit(); + } + if ($ret === false || $dbret === false) { + DBConnector::getInstance()->dbRollBack(); + $msgs[] = 'Deine Änderungen wurden nicht gespeichert (DB Rollback)'; + } else { + $msgs[] = 'Daten erfolgreich gespeichert!'; + $target = URIBASE.'projekt/'.$projektHandler->getID(); + } - } + } $json = [ 'success' => ($ret !== false), @@ -307,7 +312,7 @@ public function handleProjekt($routeInfo = null): void */ public function handleAuslagen(array $routeInfo = []): void { - if (!isset($routeInfo['mfunction'])) { + if (! isset($routeInfo['mfunction'])) { if (isset($_POST['action'])) { $routeInfo['mfunction'] = $_POST['action']; } else { @@ -316,7 +321,7 @@ public function handleAuslagen(array $routeInfo = []): void } // validate - $vali = new Validator(); + $vali = new Validator; $validator_map = []; switch ($routeInfo['mfunction']) { case 'updatecreate': @@ -508,7 +513,7 @@ public function handleAuslagen(array $routeInfo = []): void break; default: throw new LegacyDieException(400, 'Unknown Action.'); - break; + break; } $vali->validateMap($_POST, $validator_map); // return error if validation failed @@ -528,11 +533,11 @@ public function handleAuslagen(array $routeInfo = []): void if ($routeInfo['mfunction'] === 'updatecreate') { // may add nonexisting arrays - if (!isset($validated['belege'])) { + if (! isset($validated['belege'])) { $validated['belege'] = []; } foreach ($validated['belege'] as $k => $v) { - if (!isset($v['posten'])) { + if (! isset($v['posten'])) { $validated['belege'][$k]['posten'] = []; } } @@ -577,7 +582,7 @@ public function handleAuslagen(array $routeInfo = []): void } // check file non empty - $fileIdx = 'beleg_' . $kb; + $fileIdx = 'beleg_'.$kb; if (isset($_FILES[$fileIdx]['error']) && $_FILES[$fileIdx]['error'] === 0) { $empty = false; break; @@ -647,10 +652,10 @@ private function handleChat($routeInfo): void ErrorHandler::handleException($e); break; } - if (!$r || count($r) === 0) { + if (! $r || count($r) === 0) { break; } - $pdate = date_create(substr($r[0]['createdat'], 0, 4) . '-01-01 00:00:00'); + $pdate = date_create(substr($r[0]['createdat'], 0, 4).'-01-01 00:00:00'); $pdate->modify('+1 year'); $now = date_create(); // info mail @@ -679,7 +684,7 @@ private function handleChat($routeInfo): void } // new message - info mail $tMail = []; - if (!preg_match( + if (! preg_match( '/^(draft|wip|revoked|ok-by-hv|need-stura|done-hv|done-other|ok-by-stura)/', $r[0]['state'] )) { @@ -688,30 +693,30 @@ private function handleChat($routeInfo): void // switch type switch ($valid['type']) { case '-1': - if (!$auth->hasGroup('ref-finanzen') - && (!isset($r[0]['username']) || $r[0]['username'] !== $auth->getUsername())) { + if (! $auth->hasGroup('ref-finanzen') + && (! isset($r[0]['username']) || $r[0]['username'] !== $auth->getUsername())) { break 3; } - if (!$auth->hasGroup('ref-finanzen')) { + if (! $auth->hasGroup('ref-finanzen')) { $tMail['to'][] = 'ref-finanzen@tu-ilmenau.de'; } else { $tMail['to'][] = $r[0]['email']; } break; case '0': - if (!$auth->hasGroup('ref-finanzen')) { + if (! $auth->hasGroup('ref-finanzen')) { $tMail['to'][] = 'ref-finanzen@tu-ilmenau.de'; } else { $tMail['to'][] = $r[0]['responsible']; } break; case '2': - if (!$auth->hasGroup('admin')) { + if (! $auth->hasGroup('admin')) { break 3; } break; case '3': - if (!$auth->hasGroup('ref-finanzen')) { + if (! $auth->hasGroup('ref-finanzen')) { break 3; } $tMail['to'][] = 'ref-finanzen@tu-ilmenau.de'; @@ -720,10 +725,10 @@ private function handleChat($routeInfo): void break 3; } if (count($tMail) > 0) { - $tMail['param']['msg'][] = 'Im %Projekt% #' . $r[0]['id'] . ' gibt es eine neue Nachricht.'; - $tMail['param']['link']['Projekt'] = BASE_URL . URIBASE . 'projekt/' . $r[0]['id'] . '#projektchat'; + $tMail['param']['msg'][] = 'Im %Projekt% #'.$r[0]['id'].' gibt es eine neue Nachricht.'; + $tMail['param']['link']['Projekt'] = BASE_URL.URIBASE.'projekt/'.$r[0]['id'].'#projektchat'; $tMail['param']['headline'] = 'Projekt - Neue Nachricht'; - $tMail['subject'] = 'Stura-Finanzen: Neue Nachricht in Projekt #' . $r[0]['id']; + $tMail['subject'] = 'Stura-Finanzen: Neue Nachricht in Projekt #'.$r[0]['id']; $tMail['template'] = 'projekt_default'; $mail[] = $tMail; } @@ -740,6 +745,7 @@ private function handleChat($routeInfo): void // $mail_result = $mh->easyMail($m); } } + return; break; @@ -757,10 +763,10 @@ private function handleChat($routeInfo): void ErrorHandler::handleException($e); break; } - if (!$r || count($r) === 0) { + if (! $r || count($r) === 0) { break; } - $pdate = date_create(substr($r[0]['created'], 0, 4) . '-01-01 00:00:00'); + $pdate = date_create(substr($r[0]['created'], 0, 4).'-01-01 00:00:00'); $pdate->modify('+1 year'); $now = date_create(); // info mail @@ -789,11 +795,11 @@ private function handleChat($routeInfo): void // switch type switch ($valid['type']) { case '-1': - if (!$auth->hasGroup('ref-finanzen') && - $auth->getUsername() !== AuslagenHandler2::state2stateInfo('wip;' . $r[0]['created'])['user']) { + if (! $auth->hasGroup('ref-finanzen') && + $auth->getUsername() !== AuslagenHandler2::state2stateInfo('wip;'.$r[0]['created'])['user']) { break 3; } - if (!$auth->hasGroup('ref-finanzen')) { + if (! $auth->hasGroup('ref-finanzen')) { $tMail['to'][] = 'ref-finanzen@tu-ilmenau.de'; } else { $u = $db->dbFetchAll( @@ -802,7 +808,7 @@ private function handleChat($routeInfo): void ['email', 'id'], [ 'username' => AuslagenHandler2::state2stateInfo( - 'wip;' . $r[0]['created'] + 'wip;'.$r[0]['created'] )['user'], ] ); @@ -812,7 +818,7 @@ private function handleChat($routeInfo): void } break; case '3': - if (!$auth->hasGroup('ref-finanzen')) { + if (! $auth->hasGroup('ref-finanzen')) { break 3; } $tMail['to'][] = 'ref-finanzen@tu-ilmenau.de'; @@ -821,10 +827,10 @@ private function handleChat($routeInfo): void break 3; } if (count($tMail) > 0) { - $tMail['param']['msg'][] = 'In der %Abrechnung% #' . $r[0]['id'] . ' gibt es eine neue Nachricht.'; - $tMail['param']['link']['Abrechnung'] = BASE_URL . URIBASE . 'projekt/' . $r[0]['projekt_id'] . '/auslagen/' . $r[0]['id'] . '#auslagenchat'; + $tMail['param']['msg'][] = 'In der %Abrechnung% #'.$r[0]['id'].' gibt es eine neue Nachricht.'; + $tMail['param']['link']['Abrechnung'] = BASE_URL.URIBASE.'projekt/'.$r[0]['projekt_id'].'/auslagen/'.$r[0]['id'].'#auslagenchat'; $tMail['param']['headline'] = 'Auslagen - Neue Nachricht'; - $tMail['subject'] = 'Stura-Finanzen: Neue Nachricht in Abrechnung #' . $r[0]['id']; + $tMail['subject'] = 'Stura-Finanzen: Neue Nachricht in Abrechnung #'.$r[0]['id']; $tMail['template'] = 'projekt_default'; $mail[] = $tMail; } @@ -850,7 +856,7 @@ private function handleChat($routeInfo): void } $chat->setErrorMessage('Access Denied.'); $chat->answerError(); - return; + } private function updateKonto($routeInfo): void @@ -861,7 +867,7 @@ private function updateKonto($routeInfo): void $auth->requireGroup('ref-finanzen-kv'); $ret = true; - if (!DBConnector::getInstance()->dbBegin()) { + if (! DBConnector::getInstance()->dbBegin()) { throw new LegacyDieException(500, 'Kann keine Verbindung zur SQL-Datenbank aufbauen. Bitte versuche es später erneut!' ); @@ -909,7 +915,7 @@ private function updateKonto($routeInfo): void // $msgs[]= print_r($zahlung,true); DBConnector::getInstance()->dbInsert('konto', $fields); if (isset($inserted[$zahlung['konto_id']])) { - ++$inserted[$zahlung['konto_id']]; + $inserted[$zahlung['konto_id']]++; } else { $inserted[$zahlung['konto_id']] = 1; } @@ -940,24 +946,24 @@ private function updateKonto($routeInfo): void foreach ($ahs as $ah) { $ret = $ah->state_change('payed', $ah->getAuslagenEtag()); if ($ret !== true) { - $msg[] = 'Konnte IP' . $ah->getProjektID() . '-A' . $ah->getID() . - " nicht in den Status 'gezahlt' überführen. " . - 'Bitte ändere das noch (per Hand) nachträglich!' . + $msg[] = 'Konnte IP'.$ah->getProjektID().'-A'.$ah->getID(). + " nicht in den Status 'gezahlt' überführen. ". + 'Bitte ändere das noch (per Hand) nachträglich!'. $fields['date']; } } } else { - $msg[] = 'In Zahlung ' . $zahlung['id'] . ' wurden folgende Projekte/Auslagen im Verwendungszweck gefunden: ' . implode( + $msg[] = 'In Zahlung '.$zahlung['id'].' wurden folgende Projekte/Auslagen im Verwendungszweck gefunden: '.implode( ' & ', $matches - ) . '. Dort stimmt die Summe der Belegposten (' . $beleg_sum . ') nicht mit der Summe der Zahlung (' . $fields['value'] . ') überein. Bitte prüfe das noch per Hand, und setze ggf. die passenden Projekte auf bezahlt, so das es später keine Probleme beim Buchen gibt (nur gezahlte Auslagen können gebucht werden)'; + ).'. Dort stimmt die Summe der Belegposten ('.$beleg_sum.') nicht mit der Summe der Zahlung ('.$fields['value'].') überein. Bitte prüfe das noch per Hand, und setze ggf. die passenden Projekte auf bezahlt, so das es später keine Probleme beim Buchen gibt (nur gezahlte Auslagen können gebucht werden)'; } } } $ret = DBConnector::getInstance()->dbCommit(); - if (!$ret) { + if (! $ret) { DBConnector::getInstance()->dbRollBack(); JsonController::print_json( [ @@ -969,7 +975,7 @@ private function updateKonto($routeInfo): void 'headline' => 'Ein Datenbank Fehler ist aufgetreten! (Rollback)', ] ); - } elseif (!empty($inserted)) { + } elseif (! empty($inserted)) { $type = (count($msg_xmlrpc) + count($msg)) > 1 ? 'warning' : 'success'; foreach ($inserted as $konto_id => $number) { @@ -982,7 +988,7 @@ private function updateKonto($routeInfo): void 'status' => '200', 'msg' => array_merge($msg_xmlrpc, $msg), 'type' => 'modal', - 'subtype' => 'server-' . $type, + 'subtype' => 'server-'.$type, ] ); } else { @@ -1087,13 +1093,13 @@ private function newBookingInstruct($routeInfo): void ); if (count($bookingDBbelege) + count($bookingDBzahlung) > 0) { - $errorMsg[] = 'Beleg oder Zahlung bereits verknüpft - ' . print_r( + $errorMsg[] = 'Beleg oder Zahlung bereits verknüpft - '.print_r( array_merge($bookingDBzahlung, $bookingDBbelege), true ); } - if (!empty($errorMsg)) { + if (! empty($errorMsg)) { JsonController::print_json( [ 'success' => false, @@ -1111,7 +1117,7 @@ private function newBookingInstruct($routeInfo): void [DBConnector::FETCH_NUMERIC], [['id', DBConnector::GROUP_MAX]] ); - if (is_array($lastEntry) && !empty($lastEntry)) { + if (is_array($lastEntry) && ! empty($lastEntry)) { $nextId = $lastEntry[0][0] + 1; } else { $nextId = 1; @@ -1214,34 +1220,34 @@ private function saveConfirmedBookingInstruction(): void 'action' => 'none', ] ); - if (!in_array('A' . $beleg['auslagen_id'], $doneAuslage, true)) { + if (! in_array('A'.$beleg['auslagen_id'], $doneAuslage, true)) { if ($ah->state_change_possible('booked') !== true) { - $stateChangeNotOk[] = 'IP-' . date_create($beleg['projekt_createdate'])->format('y') . '-' . - $beleg['projekt_id'] . '-A' . $beleg['auslagen_id'] . ' (' . $ah->getStateString() . ')'; + $stateChangeNotOk[] = 'IP-'.date_create($beleg['projekt_createdate'])->format('y').'-'. + $beleg['projekt_id'].'-A'.$beleg['auslagen_id'].' ('.$ah->getStateString().')'; } else { $ah->state_change('booked', $beleg['etag']); - $doneAuslage[] = 'A' . $beleg['auslagen_id']; + $doneAuslage[] = 'A'.$beleg['auslagen_id']; } } break; case 'extern': $evh = new ExternVorgangHandler($beleg['id']); - if (!in_array('E' . $beleg['id'], $doneAuslage, true) + if (! in_array('E'.$beleg['id'], $doneAuslage, true) && $evh->state_change_possible('booked') !== true) { - $stateChangeNotOk[] = 'EP-' . - $beleg['extern_id'] . '-V' . $beleg['vorgang_id'] . ' (' . $evh->getStateString() . + $stateChangeNotOk[] = 'EP-'. + $beleg['extern_id'].'-V'.$beleg['vorgang_id'].' ('.$evh->getStateString(). ')'; } else { $evh->state_change('booked', $beleg['etag']); - $doneAuslage[] = 'E' . $beleg['id']; + $doneAuslage[] = 'E'.$beleg['id']; } break; } } } // transferred states to booked - otherwise throw error - if (!empty($stateChangeNotOk)) { + if (! empty($stateChangeNotOk)) { DBConnector::getInstance()->dbRollBack(); JsonController::print_json( [ @@ -1359,7 +1365,7 @@ private function saveConfirmedBookingInstruction(): void 'type' => 'modal', 'subtype' => 'server-success', 'reload' => 2000, - 'headline' => count($confirmedInstructions) . (count($confirmedInstructions) >= 1 ? ' Vorgänge ' : ' Vorgang ') . ' erfolgreich gespeichert', + 'headline' => count($confirmedInstructions).(count($confirmedInstructions) >= 1 ? ' Vorgänge ' : ' Vorgang ').' erfolgreich gespeichert', ] ); } @@ -1367,8 +1373,9 @@ private function saveConfirmedBookingInstruction(): void private function cancelBooking($routeInfo): void { (AUTH_HANDLER)::getInstance()->requireGroup('ref-finanzen-hv'); - if (!isset($_REQUEST['booking_id'])) { + if (! isset($_REQUEST['booking_id'])) { $msgs[] = 'Daten wurden nicht korrekt übermittelt'; + return; } $booking_id = $_REQUEST['booking_id']; @@ -1379,7 +1386,7 @@ private function cancelBooking($routeInfo): void [['id', DBConnector::GROUP_MAX]], ['id' => $booking_id] )[0]; - if ($ret !== false && !empty($ret)) { + if ($ret !== false && ! empty($ret)) { $ret = $ret[0]; if ($ret['canceled'] !== 0) { DBConnector::getInstance()->dbBegin(); @@ -1388,7 +1395,7 @@ private function cancelBooking($routeInfo): void 'booking', [ 'id' => $maxBookingId + 1, - 'comment' => 'Rotbuchung zu B-Nr: ' . $booking_id, + 'comment' => 'Rotbuchung zu B-Nr: '.$booking_id, 'titel_id' => $ret['titel_id'], 'belegposten_id' => $ret['belegposten_id'], 'zahlung_id' => $ret['zahlung_id'], @@ -1403,7 +1410,7 @@ private function cancelBooking($routeInfo): void ['id' => $booking_id], ['canceled' => $maxBookingId + 1] ); - if (!DBConnector::getInstance()->dbCommit()) { + if (! DBConnector::getInstance()->dbCommit()) { DBConnector::getInstance()->dbRollBack(); JsonController::print_json( [ @@ -1452,7 +1459,7 @@ private function saveHhpImport($routeInfo): void 'subtype' => 'server-success', 'reload' => 1000, 'headline' => 'Daten gespeichert', - 'redirect' => URIBASE . 'hhp', + 'redirect' => URIBASE.'hhp', ] ); } else { @@ -1471,7 +1478,7 @@ private function saveHhpImport($routeInfo): void private function saveDefaultTanMode($routeInfo): void { - if (!isset($_POST['tan-mode-id'])) { + if (! isset($_POST['tan-mode-id'])) { JsonController::print_json( [ 'success' => false, @@ -1494,12 +1501,12 @@ private function saveDefaultTanMode($routeInfo): void if ($tanClosed = $fHandler->hasTanSessionInformation()) { $fHandler->deleteTanSessionInformation(); } - $redirectUrl = $tanMediumName === null ? URIBASE . "konto/credentials/$credId/tan-mode/$tanMode/medium" : URIBASE . 'konto/credentials/'; + $redirectUrl = $tanMediumName === null ? URIBASE."konto/credentials/$credId/tan-mode/$tanMode/medium" : URIBASE.'konto/credentials/'; JsonController::print_json( [ 'success' => true, 'status' => '200', - 'msg' => "Tan $tanMode für Zugangsdaten $credId gespeichert". ($tanClosed ? ' - offene Tans wurden abgebrochen' : ''), + 'msg' => "Tan $tanMode für Zugangsdaten $credId gespeichert".($tanClosed ? ' - offene Tans wurden abgebrochen' : ''), 'type' => 'modal', 'subtype' => 'server-success', 'reload' => 1000, @@ -1593,7 +1600,7 @@ private function importKonto(array $routeInfo): void 'subtype' => 'server-success', 'reload' => 1000, 'headline' => 'Daten gespeichert', - 'redirect' => URIBASE . "konto/credentials/$credId/sepa", + 'redirect' => URIBASE."konto/credentials/$credId/sepa", ] ); } else { @@ -1671,7 +1678,7 @@ private function abortTan(array $routeInfo): void 'type' => 'modal', 'subtype' => 'server-success', 'reload' => 1000, - 'redirect' => URIBASE . 'konto/credentials/' . $credId . '/sepa', + 'redirect' => URIBASE.'konto/credentials/'.$credId.'/sepa', 'headline' => 'Tan Verfahren abgebrochen', ] ); diff --git a/legacy/lib/forms/chat/ChatHandler.php b/legacy/lib/forms/chat/ChatHandler.php index 43d02965..41571077 100644 --- a/legacy/lib/forms/chat/ChatHandler.php +++ b/legacy/lib/forms/chat/ChatHandler.php @@ -15,24 +15,28 @@ class ChatHandler // MEMBER ========================================================= /** * last lead comments + * * @var array */ private $comments; /** * maximum comments id + * * @var int */ private $max_comment_id = 0; /** * maximum comments id - posted + * * @var int */ private $post_last_id = 0; /** * keep this values in filter + * * @var array */ private $keep = ['0', '1']; @@ -44,36 +48,42 @@ class ChatHandler /** * access group + * * @var string */ private $group; /** * access group_id + * * @var string */ private $group_id; /** * username + * * @var string */ private $user; /** * userfullname + * * @var string */ private $userfullname; /** * is error + * * @var array */ private $error = null; /** * array map + * * @var array */ private $colors = [ @@ -156,10 +166,6 @@ class ChatHandler /** * class constructor - * @param ?string $group - * @param ?int $group_id - * @param ?string $userName - * @param ?string $userfullname */ public function __construct(?string $group, ?int $group_id, ?string $userName = null, ?string $userfullname = null) { @@ -176,14 +182,15 @@ public function __construct(?string $group, ?int $group_id, ?string $userName = /** * TODO admin comment button - * @param string $group group - * @param int $group_id group identifier - * @param string $user user name + identifier - * @param \string[][] $buttons + * + * @param string $group group + * @param int $group_id group identifier + * @param string $user user name + identifier + * @param \string[][] $buttons */ public static function renderChatPanel($group, $group_id, $user, $buttons = [['label' => 'Senden', 'color' => 'success', 'type' => '0']]): void { - if (!$group_id) { + if (! $group_id) { return; } ?>
@@ -191,24 +198,25 @@ public static function renderChatPanel($group, $group_id, $user, $buttons = [['l
Kommentare/Nachrichten
0) { ?>
Jetzt gerade -
@@ -229,9 +237,9 @@ class="btn btn- pull-right chat-submit">colors[$colorKey][($map[$colorKey]['color-position'] % $map[$colorKey]['color-count'])]; - ++$map[$colorKey]['color-position']; + $map[$colorKey]['color-position']++; } $this->comments[$k]['color'] = $map[$colorKey]['user'][$cc]; //extra class @@ -315,7 +325,8 @@ public function commentStyle(): void /** * unset not required comment information - * @param array $keep unset types not in this array + * + * @param array $keep unset types not in this array */ public function filterComments($keep = null): void { @@ -323,14 +334,14 @@ public function filterComments($keep = null): void $this->max_comment_id = 0; $count = 0; foreach ($this->comments as $k => $c) { - if (!in_array((string) $c['type'], $kp, true)) { - ++$count; + if (! in_array((string) $c['type'], $kp, true)) { + $count++; unset($this->comments[$k]); } else { if (((int) $this->comments[$k]['type']) === -1 || str_starts_with($this->comments[$k]['text'], '$enc$')) { $this->comments[$k]['text'] = $this->decryptMessage($this->comments[$k]['text']); } - ++$count; + $count++; $this->max_comment_id = max($this->max_comment_id, $c['id'], $this->post_last_id); unset($this->comments[$k]['id']); unset($this->comments[$k]['target']); @@ -374,10 +385,11 @@ public function getMaxCommentId(): int /** * create chat entry - * @param int $type 1: state change, -1: deprecated private msg, 2: admin, 3: ref-finanzen + * + * @param int $type 1: state change, -1: deprecated private msg, 2: admin, 3: ref-finanzen */ public function _createComment(string $group, int $group_id, string $timestamp, - string $creator, string $creator_alias, string $text, int $type): void + string $creator, string $creator_alias, string $text, int $type): void { try { $this->db->dbInsert('comments', [ @@ -397,10 +409,11 @@ public function _createComment(string $group, int $group_id, string $timestamp, /** * create chat entry - * @param string $text - * @param int $type - * @param string $group - * @param int $group_id + * + * @param string $text + * @param int $type + * @param string $group + * @param int $group_id */ public function createComment($text, $type, $group = null, $group_id = null): void { @@ -412,11 +425,11 @@ public function createComment($text, $type, $group = null, $group_id = null): vo /** * set error message -> may use this for ACL * - * @param mixed $msg + * @param mixed $msg */ public function setErrorMessage($msg): void { - if (!$this->error && is_string($msg) && $msg) { + if (! $this->error && is_string($msg) && $msg) { $this->error = $msg; } } @@ -431,6 +444,7 @@ public function isError(): bool /** * return error message + * * @return string|array */ public function getError() @@ -452,21 +466,25 @@ public function resetError(): void /** * validate post data + * * @param array string */ public function validatePost($post) { - $vali = new Validator(); + $vali = new Validator; $vali->validateMap($post, self::$validateMap['action'], true); if ($vali->getIsError()) { $this->error = $vali->getLastErrorMsg(); + return null; } $vali->validateMap($post, self::$validateMap[$vali->getFiltered('action')], true); if ($vali->getIsError()) { $this->error = $vali->getLastErrorMsg(); + return null; } + return $vali->getFiltered(); } @@ -506,14 +524,16 @@ public function answerError(): void */ public function answerAll($post): void { - if (!$post || !is_array($post) || !isset($post['action'])) { + if (! $post || ! is_array($post) || ! isset($post['action'])) { $this->error = 'Action Denied.'; $this->answerError(); + return; } $post = $this->validatePost($post); if ($this->error) { $this->answerError(); + return; } switch ($post['action']) { @@ -524,7 +544,7 @@ public function answerAll($post): void 'code' => 200, 'msg' => 'created', ]); - break; + break; case 'gethistory': $this->post_last_id = $post['last']; $this->loadComments(true, $post['last'], $post['target'], $post['target_id']); @@ -536,10 +556,10 @@ public function answerAll($post): void 'data' => $this->comments, 'last' => $this->max_comment_id, ]); - break; + break; default: throw new LegacyDieException(400, 'Chat: Error: Unhandles Action passed Validation: '.$post['action']); - break; + break; } } @@ -551,7 +571,7 @@ public function answerAll($post): void */ private function createKeys(): void { - if (!config('app.chat.private_key') && !config('app.chat.public_key')) { + if (! config('app.chat.private_key') && ! config('app.chat.public_key')) { $config = [ 'digest_alg' => 'sha512', 'private_key_bits' => 4096, @@ -591,7 +611,8 @@ private function encryptMessage(string $text): string return ''; } $this->createKeys(); - return '$enc$' . $this->_encryptMessage($text, $this->getKey('public')); + + return '$enc$'.$this->_encryptMessage($text, $this->getKey('public')); } /** @@ -606,6 +627,7 @@ private function decryptMessage(string $text): string if (str_starts_with($text, '$enc$')) { $text = substr($text, 5); } + return $this->_decryptMessage($text, $this->getKey('private')); } @@ -615,6 +637,7 @@ private function decryptMessage(string $text): string private function _encryptMessage(string $text, string $key): string { openssl_public_encrypt($text, $encrypted, $key); + return base64_encode($encrypted); } @@ -624,6 +647,7 @@ private function _encryptMessage(string $text, string $key): string private function _decryptMessage(string $encrypted, string $key): string { openssl_private_decrypt(base64_decode($encrypted), $decrypted, $key); + return $decrypted ?? '! Corrupted message. !'; } } diff --git a/legacy/lib/forms/projekte/PermissionHandler.php b/legacy/lib/forms/projekte/PermissionHandler.php index 49a7877e..fb2c5982 100644 --- a/legacy/lib/forms/projekte/PermissionHandler.php +++ b/legacy/lib/forms/projekte/PermissionHandler.php @@ -10,33 +10,36 @@ class PermissionHandler * @var array */ protected $dataFields; + /** * @var StateHandler */ protected $stateHandler; + /** * @var array ["stateName" => ["groups => [...], "persons" => [...], "gremium" => [...]],...] - * Any match with group, gremium or person will grant write Permission! + * Any match with group, gremium or person will grant write Permission! */ protected $writePermissionAll; /** * @var array [ "stateName1" => - * [ "fieldName1" => - * [ "groups => [...], "persons" => [...], "gremien" => [...], ] - * ,...] - * ,...] - * Any match with group, gremium or person will grant write Permission! - * If fieldName array is just true than value can be edited from anyone in this - * state + * [ "fieldName1" => + * [ "groups => [...], "persons" => [...], "gremien" => [...], ] + * ,...] + * ,...] + * Any match with group, gremium or person will grant write Permission! + * If fieldName array is just true than value can be edited from anyone in this + * state */ protected $writePermissionField; /** * @var array [ "fieldname1" => [ "state1", "state2", ...],... ] - * Any Match with any State will grant visibility + * Any Match with any State will grant visibility */ protected $visibleFields; + protected $editMode; /** @@ -46,35 +49,35 @@ public function __construct(array $dataFields, StateHandler $stateHandler, array { $states = $stateHandler->getStates(); foreach ($states as $stateName => $desc) { - if (!isset($writePermissionAll[$stateName])) { + if (! isset($writePermissionAll[$stateName])) { exit("Status $stateName is not defined in \$writePermissionAll"); } if ($writePermissionAll[$stateName] !== true) { //could be explicit true or false - if (!isset($writePermissionAll[$stateName]['groups'])) { + if (! isset($writePermissionAll[$stateName]['groups'])) { $writePermissionAll[$stateName]['groups'] = []; } - if (!isset($writePermissionAll[$stateName]['persons'])) { + if (! isset($writePermissionAll[$stateName]['persons'])) { $writePermissionAll[$stateName]['persons'] = []; } - if (!isset($writePermissionAll[$stateName]['gremien'])) { + if (! isset($writePermissionAll[$stateName]['gremien'])) { $writePermissionAll[$stateName]['gremien'] = []; } } foreach ($dataFields as $dataFieldName => $content) { - if (!isset($writePermissionField[$stateName][$dataFieldName]['groups'])) { + if (! isset($writePermissionField[$stateName][$dataFieldName]['groups'])) { $writePermissionField[$stateName][$dataFieldName]['groups'] = []; } - if (!isset($writePermissionField[$stateName][$dataFieldName]['persons'])) { + if (! isset($writePermissionField[$stateName][$dataFieldName]['persons'])) { $writePermissionField[$stateName][$dataFieldName]['persons'] = []; } - if (!isset($writePermissionField[$stateName][$dataFieldName]['gremien'])) { + if (! isset($writePermissionField[$stateName][$dataFieldName]['gremien'])) { $writePermissionField[$stateName][$dataFieldName]['gremien'] = []; } } } foreach ($dataFields as $dataFieldName => $content) { - if (!isset($visibleFields[$dataFieldName])) { + if (! isset($visibleFields[$dataFieldName])) { $visibleFields[$dataFieldName] = true; } } @@ -93,6 +96,7 @@ public function isVisibleField($fieldname): bool if ($this->visibleFields[$fieldname] === true) { return true; } + return in_array($this->stateHandler->getActualState(), $this->visibleFields[$fieldname], true); } @@ -115,6 +119,7 @@ public function isAnyDataEditable($couldBe = false): bool if ($couldBe === true) { $this->editMode = $oldEditMode; } + //var_dump(["edit" =>$ret]); return $ret; } @@ -126,6 +131,7 @@ public function checkWritePermission(): bool } // https://stackoverflow.com/questions/2715026/are-php5-objects-passed-by-reference -> yes $state = $this->stateHandler->getActualState(); + return $this->checkPermissionArray($this->writePermissionAll[$state]); } @@ -146,6 +152,7 @@ private function checkPermissionArray($permArray): bool $ret |= in_array(AuthHandler::getInstance()->getUsername(), $permArray['persons'], true); $ret |= in_array(AuthHandler::getInstance()->getUserFullName(), $permArray['persons'], true); } + //var_dump($ret); return (bool) $ret; } @@ -158,6 +165,7 @@ public function checkWritePermissionField($fieldname): bool // https://stackoverflow.com/questions/2715026/are-php5-objects-passed-by-reference -> yes $fieldname = $this->cleanFieldNameFromArrayTags($fieldname); $state = $this->stateHandler->getActualState(); + /*var_dump([ "name" => $fieldname, "rules" => $this->writePermissionField[$state][$fieldname], @@ -188,12 +196,14 @@ public function isEditable($names, $conjunctureWith = '') if (strtolower($conjunctureWith) === 'and') { return $ret_and; } + return null; } if ($this->checkWritePermission() === true) { return true; } + return $this->checkWritePermissionField($names); } } diff --git a/legacy/lib/forms/projekte/ProjektHandler.php b/legacy/lib/forms/projekte/ProjektHandler.php index fc20e77c..a8a0c984 100644 --- a/legacy/lib/forms/projekte/ProjektHandler.php +++ b/legacy/lib/forms/projekte/ProjektHandler.php @@ -19,32 +19,43 @@ class ProjektHandler extends FormHandlerInterface { private static $emptyData; + private static $states; + private static $stateChanges; + private static $printModes; + private static $visibleFields; + private static $writePermissionAll; + private static $writePermissionFields; private $templater; + private $stateHandler; + /** * @var PermissionHandler */ private $permissionHandler; + private $id; + private $action; + private $data; public function __construct($pathInfo) { //print_r($pathInfo); self::initStaticVars(); - if (!isset($pathInfo['action'])) { + if (! isset($pathInfo['action'])) { throw new LegacyDieException(400, 'Aktion nicht gesetzt'); } $this->action = $pathInfo['action']; - if ($this->action === 'create' || !isset($pathInfo['pid'])) { + if ($this->action === 'create' || ! isset($pathInfo['pid'])) { $this->data = self::$emptyData; $stateNow = 'draft'; } else { @@ -59,7 +70,7 @@ public function __construct($pathInfo) ], ['version' => true] ); - if (!empty($res)) { + if (! empty($res)) { $this->data = $res[0]; } else { abort(404); @@ -84,7 +95,7 @@ public function __construct($pathInfo) $editMode = $this->action === 'create' || $this->action === 'edit'; $owners = [ 'gremien' => $this->data['org'], - 'mail' => $this->data['responsible'] . '@' .ORG_DATA['mail-domain'], + 'mail' => $this->data['responsible'].'@'.ORG_DATA['mail-domain'], ]; $this->stateHandler = new StateHandler('projekte', self::$states, self::$stateChanges, [], [], $stateNow, $owners); $this->permissionHandler = new PermissionHandler( @@ -235,12 +246,11 @@ public static function initStaticVars(): bool 'recht-additional' => ['groups' => ['ref-finanzen-hv']], ], ]; + return true; } /** - * @param $data - * * @throws InvalidDataException * @throws PDOException */ @@ -284,7 +294,7 @@ public static function createNewProjekt($data): ProjektHandler ] ); - for ($i = 0; $i < $minRows - 1; ++$i) { + for ($i = 0; $i < $minRows - 1; $i++) { if ((float) $data['posten-ausgaben'][$i] > 0 && (float) $data['posten-einnahmen'][$i] > 0) { throw new InvalidDataException( 'Projektposten dürfen nicht gleichzeitig Einnahmen und Ausgaben enthalten.' @@ -315,12 +325,11 @@ public static function createNewProjekt($data): ProjektHandler public static function getStateStringFromName($statename) { self::initStaticVars(); + return self::$states[$statename][0]; } /** - * @param $data - * * @throws PDOException * @throws WrongVersionException * @throws InvalidDataException @@ -351,7 +360,7 @@ public function updateSavedData($data): bool ); } //wenn posten-titel nicht mit übertragen setze dummy an seine stelle - if (!isset($data['posten-titel'])) { + if (! isset($data['posten-titel'])) { $data['posten-titel'] = array_fill(0, $maxRows, null); } @@ -371,11 +380,11 @@ public function updateSavedData($data): bool $data = array_diff_key($data, $generatedFields, $extractFields); $recht_unset = false; if (isset($data['recht-additional'])) { - if (!isset($data['recht']) && isset($this->data['recht'])) { + if (! isset($data['recht']) && isset($this->data['recht'])) { $data['recht'] = $this->data['recht']; $recht_unset = true; } - if (!isset($data['recht'])) { + if (! isset($data['recht'])) { $data['recht-additional'] = ''; } elseif (isset($data['recht-additional'][$data['recht']])) { $data['recht-additional'] = $data['recht-additional'][$data['recht']]; @@ -392,7 +401,7 @@ public function updateSavedData($data): bool $fields = $generatedFields; foreach ($data as $name => $content) { if ($this->permissionHandler->isEditable($name) && $this->permissionHandler->isVisibleField($name)) { - if (!empty($content)) { + if (! empty($content)) { $fields[$name] = $content; } else { $fields[$name] = null; @@ -402,10 +411,10 @@ public function updateSavedData($data): bool } } $retMetaUpdate = DBConnector::getInstance()->dbUpdate( - 'projekte', - ['id' => $this->id, 'version' => $version], - $fields - ) === 1; + 'projekte', + ['id' => $this->id, 'version' => $version], + $fields + ) === 1; if ($this->permissionHandler->isEditable( ['posten-name', 'posten-bemerkung', 'posten-einnahmen', 'posten-ausgaben'], @@ -416,7 +425,7 @@ public function updateSavedData($data): bool // update old posten (last minrow is empty all the time $retUpdate = true; - for ($i = 0; $i < $minRows - 1 && $i < $oldRows; ++$i) { + for ($i = 0; $i < $minRows - 1 && $i < $oldRows; $i++) { //would throw exception if not working $rowsUpdated = DBConnector::getInstance()->dbUpdate( 'projektposten', @@ -444,25 +453,25 @@ public function updateSavedData($data): bool // add new posten $retInsert = true; - for ($i = $oldRows; $i < $minRows - 1; ++$i) { + for ($i = $oldRows; $i < $minRows - 1; $i++) { $retInsert = $retInsert && (DBConnector::getInstance()->dbInsert( - 'projektposten', - [ - 'id' => $i + 1, - 'projekt_id' => $this->id, - 'titel_id' => $extractFields['posten-titel'][$i] === '' ? null : $extractFields['posten-titel'][$i], - 'einnahmen' => DBConnector::getInstance()->convertUserValueToDBValue( - $extractFields['posten-einnahmen'][$i], - 'money' - ), - 'ausgaben' => DBConnector::getInstance()->convertUserValueToDBValue( - $extractFields['posten-ausgaben'][$i], - 'money' - ), - 'name' => $extractFields['posten-name'][$i], - 'bemerkung' => $extractFields['posten-bemerkung'][$i], - ] - )) === '0'; // lastInsertedId returns "0" due to auto increment is not used (multikey) + 'projektposten', + [ + 'id' => $i + 1, + 'projekt_id' => $this->id, + 'titel_id' => $extractFields['posten-titel'][$i] === '' ? null : $extractFields['posten-titel'][$i], + 'einnahmen' => DBConnector::getInstance()->convertUserValueToDBValue( + $extractFields['posten-einnahmen'][$i], + 'money' + ), + 'ausgaben' => DBConnector::getInstance()->convertUserValueToDBValue( + $extractFields['posten-ausgaben'][$i], + 'money' + ), + 'name' => $extractFields['posten-name'][$i], + 'bemerkung' => $extractFields['posten-bemerkung'][$i], + ] + )) === '0'; // lastInsertedId returns "0" due to auto increment is not used (multikey) } // delete old ones $retDelete = true; @@ -476,19 +485,19 @@ public function updateSavedData($data): bool ); $retDelete = $retDelete > 0; } + return $retMetaUpdate && $retDelete && $retInsert && $retUpdate; } + return $retMetaUpdate; } /** - * @param $stateName - * * @throws IllegalStateException */ public function setState($stateName): bool { - if (!in_array($stateName, $this->getNextPossibleStates(), true)) { + if (! in_array($stateName, $this->getNextPossibleStates(), true)) { throw new IllegalStateException("In den Status $stateName kann nicht gewechselt werden"); } @@ -510,10 +519,11 @@ public function setState($stateName): bool date_create()->format('Y-m-d H:i:s'), 'system', '', - self::$states[$this->data['state']][0] . ' -> ' . self::$states[$stateName][0], + self::$states[$this->data['state']][0].' -> '.self::$states[$stateName][0], 1 ); $this->stateHandler->transitionTo($stateName); + return true; } @@ -524,8 +534,9 @@ public function getNextPossibleStates(): array public function render(): void { - if ($this->action === 'create' || !isset($this->id)) { + if ($this->action === 'create' || ! isset($this->id)) { $this->renderProjekt('neues Projekt anlegen'); + return; } @@ -537,7 +548,7 @@ public function render(): void case 'view': $this->renderInteractionPanel(); //echo $this->templater->getStateChooser($this->stateHandler); - $this->renderProjekt('Projekt ' . $this->id); + $this->renderProjekt('Projekt '.$this->id); $this->render_chat_box(); $this->renderProjektSizeGrafic(); $this->renderAuslagenList(); @@ -570,7 +581,7 @@ private function renderProjekt($title): void }, ORG_DATA['rechtsgrundlagen']) )); $sel_recht['values'] = $this->data['recht']; - if (isset($this->data['createdat']) && !empty($this->data['createdat'])) { + if (isset($this->data['createdat']) && ! empty($this->data['createdat'])) { $createDate = $this->data['createdat']; } else { $createDate = date_create()->format('Y-m-d'); @@ -592,7 +603,7 @@ private function renderProjekt($title): void
- templater->getHiddenActionInput(isset($this->id) ? 'update' : 'create'); ?> @@ -633,7 +644,7 @@ private function renderProjekt($title): void
+ ?>
@@ -656,7 +667,7 @@ private function renderProjekt($title): void 'vorname.nachname', 'Projektverantwortlich (Mail)', ['required', 'email'], - '@' . ORG_DATA['mail-domain'] + '@'.ORG_DATA['mail-domain'] ); ?>
templater->getDropdownForm( @@ -680,7 +691,7 @@ private function renderProjekt($title): void ); } ?> templater->getWikiLinkForm( 'protokoll', $this->data['protokoll'], @@ -732,15 +743,15 @@ private function renderProjekt($title): void $this->data['posten-name'][] = ''; - foreach ($this->data['posten-name'] as $row_nr => $null) { - $new_row = ($row_nr) === count($this->data['posten-name']); - if ($new_row && !$tablePartialEditable) { - continue; - } - $sel_titel = $selectable_titel; - if (isset($this->data['posten-titel'][$row_nr])) { - $sel_titel['values'] = $this->data['posten-titel'][$row_nr]; - } ?> + foreach ($this->data['posten-name'] as $row_nr => $null) { + $new_row = ($row_nr) === count($this->data['posten-name']); + if ($new_row && ! $tablePartialEditable) { + continue; + } + $sel_titel = $selectable_titel; + if (isset($this->data['posten-titel'][$row_nr])) { + $sel_titel['values'] = $this->data['posten-titel'][$row_nr]; + } ?> . @@ -750,51 +761,51 @@ class='fa fa-fw fa-trash'> echo ''; } ?> templater->getTextForm( - 'posten-name[]', - !$new_row ? $this->data['posten-name'][$row_nr] : '', - null, - 'Name des Postens', - '', - ['required'] - ); ?> + 'posten-name[]', + ! $new_row ? $this->data['posten-name'][$row_nr] : '', + null, + 'Name des Postens', + '', + ['required'] + ); ?> templater->getTextForm( - 'posten-bemerkung[]', - !$new_row ? $this->data['posten-bemerkung'][$row_nr] : '', - null, - 'optional', - '', - [] - ); ?> + 'posten-bemerkung[]', + ! $new_row ? $this->data['posten-bemerkung'][$row_nr] : '', + null, + 'optional', + '', + [] + ); ?> templater->getDropdownForm( - 'posten-titel[]', - $sel_titel, - null, - 'HH-Titel', - '', - [], - true - ); ?> + 'posten-titel[]', + $sel_titel, + null, + 'HH-Titel', + '', + [], + true + ); ?> templater->getMoneyForm( - 'posten-einnahmen[]', - !$new_row ? $this->data['posten-einnahmen'][$row_nr] : 0, - null, - '', - '', - ['required'], - 'einnahmen' - ); ?> + 'posten-einnahmen[]', + ! $new_row ? $this->data['posten-einnahmen'][$row_nr] : 0, + null, + '', + '', + ['required'], + 'einnahmen' + ); ?> templater->getMoneyForm( - 'posten-ausgaben[]', - !$new_row ? $this->data['posten-ausgaben'][$row_nr] : 0, - null, - '', - '', - ['required'], - 'ausgaben' - ); ?> + 'posten-ausgaben[]', + ! $new_row ? $this->data['posten-ausgaben'][$row_nr] : 0, + null, + '', + '', + ['required'], + 'ausgaben' + ); ?> + } ?> @@ -850,7 +861,7 @@ class='fa fa-fw fa-trash'> ?> @@ -874,7 +885,7 @@ private function renderBackButton(): void private function renderInteractionPanel(): void { - $url = str_replace('//', '/', URIBASE . 'projekt/' . $this->id . '/'); + $url = str_replace('//', '/', URIBASE.'projekt/'.$this->id.'/'); $nextValidStates = $this->stateHandler->getNextStates(true); $disabledStates = array_diff($this->stateHandler->getAllAllowedTransitionableStates(), $nextValidStates); ?>
@@ -911,7 +922,7 @@ class="fa fa-fw fa-trash">
0) { ?> - ' . PHP_EOL; $ah = new AuslagenHandler2(['pid' => $this->id, 'action' => 'view']); $ah->render_auslagen_beleg_diagrams('Nice Diagrams'); */ - return; + } private function renderAuslagenList(): void @@ -1068,12 +1079,12 @@ private function renderAuslagenList(): void
$this->id, 'action' => 'view']); - $ah->render_project_auslagen(true); ?> + $ah->render_project_auslagen(true); ?>
where('projekt_id', $this->id)->count() > 0; } diff --git a/legacy/lib/forms/projekte/StateHandler.php b/legacy/lib/forms/projekte/StateHandler.php index 119278a2..ba0c08ba 100644 --- a/legacy/lib/forms/projekte/StateHandler.php +++ b/legacy/lib/forms/projekte/StateHandler.php @@ -13,6 +13,7 @@ class StateHandler * @var string */ private $actualState; + /** * @var array */ @@ -22,16 +23,19 @@ class StateHandler * @var array */ private $validations; + /** * @var array */ private $postTransitionHooks; + /** * @var array */ private $states; private $parentTableName; + /** * @var string[][] keys: gremien, mail */ @@ -40,18 +44,17 @@ class StateHandler /** * StateHandler constructor. * - * @param $parentTableName - * @param array $allStates - * @param array $transitions - * @param array $validations - * @param array $postTransitionHooks - * @param null $start if empty or null, draft will be picked if available, otherwise first entry in states + * @param array $allStates + * @param array $transitions + * @param array $validations + * @param array $postTransitionHooks + * @param null $start if empty or null, draft will be picked if available, otherwise first entry in states */ public function __construct($parentTableName, $allStates, $transitions, $validations = [], $postTransitionHooks = [], $start = null, array $owners = []) { $this->owners = $owners; $this->parentTableName = $parentTableName; - if (!is_array($allStates) || !is_array($transitions)) { + if (! is_array($allStates) || ! is_array($transitions)) { throw new InvalidArgumentException('Keine Arrays in States / Transitions übergeben!'); } @@ -67,21 +70,21 @@ public function __construct($parentTableName, $allStates, $transitions, $validat $this->states = $allStates; foreach ($this->states as $state => $desc) { - if (!isset($validations[$state])) { + if (! isset($validations[$state])) { $validations[$state] = static function ($newState) { return true; }; - } elseif (!is_callable($validations[$state])) { + } elseif (! is_callable($validations[$state])) { throw new InvalidArgumentException("Validator zu $state ist keine Funktion!"); } - if (!isset($postTransitionHooks[$state])) { + if (! isset($postTransitionHooks[$state])) { $postTransitionHooks[$state] = static function ($newState) { return true; }; - } elseif (!is_callable($postTransitionHooks[$state])) { + } elseif (! is_callable($postTransitionHooks[$state])) { throw new InvalidArgumentException("Validator zu $state ist keine Funktion!"); } - if (!isset($transitions[$state])) { + if (! isset($transitions[$state])) { throw new InvalidArgumentException("Cannot find state '$state' in \$transition array as key"); } } @@ -97,8 +100,6 @@ public function getStates(): array } /** - * @param $newState - * * @return bool * * @throws IllegalStateException @@ -106,13 +107,13 @@ public function getStates(): array */ public function transitionTo($newState) { - if (!$this->isExitingState($newState)) { + if (! $this->isExitingState($newState)) { throw new IllegalStateException("$newState nicht bekannt!"); } - if (!$this->isTransitionableTo($newState)) { + if (! $this->isTransitionableTo($newState)) { throw new IllegalTransitionException("$this->actualState nicht in $newState überführbar - Daten fehlen!"); } - if (!$this->isAllowedToTransitionTo($newState)) { + if (! $this->isAllowedToTransitionTo($newState)) { throw new IllegalTransitionException("$this->actualState nicht in $newState überführbar - nicht die passenden Rechte!"); } $oldState = $this->actualState; @@ -120,19 +121,17 @@ public function transitionTo($newState) if (isset($this->postTransitionHooks[$oldState])) { return $this->postTransitionHooks[$oldState]($newState); } + return true; } - /** - * @param $state - */ private function isExitingState($state): bool { return isset($this->states[$state]); } /** - * @param $newState string + * @param $newState string */ public function isTransitionableTo($newState): bool { @@ -177,6 +176,7 @@ private function checkPermissionArray($permArray): bool $ret = $ret || AuthHandler::getInstance()->hasGremium($this->owners['gremien']); $ret = $ret || AuthHandler::getInstance()->getUserMail() === $this->owners['mail']; } + // var_dump($ret); return $ret; } @@ -189,6 +189,7 @@ public function getAllAllowedTransitionableStates(): array $ret[] = $stateName; } } + return $ret; } @@ -198,7 +199,7 @@ public function getActualState(): string } /** - * @param $onlyValidChanges bool + * @param $onlyValidChanges bool */ public function getNextStates($onlyValidChanges = false): array { @@ -206,8 +207,8 @@ public function getNextStates($onlyValidChanges = false): array } /** - * @param $state string - * @param $onlyValidChanges bool + * @param $state string + * @param $onlyValidChanges bool */ public function getNextStatesFrom($state, $onlyValidChanges = false): array { @@ -222,6 +223,7 @@ public function getNextStatesFrom($state, $onlyValidChanges = false): array } else { $ret = array_keys($list); } + return $ret; } @@ -231,13 +233,14 @@ public function getFullStateName(): string } /** - * @param $state string + * @param $state string */ public function getFullStateNameFrom(string $state): string { - if (!$this->isExitingState($state)) { + if (! $this->isExitingState($state)) { return false; } + return $this->states[$state][0] ?? $state; } @@ -247,7 +250,7 @@ public function getAltStateName(): string } /** - * @param $state string + * @param $state string */ public function getAltStateNameFrom($state): string { diff --git a/legacy/lib/forms/projekte/auslagen/AuslagenHandler2.php b/legacy/lib/forms/projekte/auslagen/AuslagenHandler2.php index f53852f3..2c500223 100644 --- a/legacy/lib/forms/projekte/auslagen/AuslagenHandler2.php +++ b/legacy/lib/forms/projekte/auslagen/AuslagenHandler2.php @@ -32,9 +32,12 @@ * implement auslagen handler * * @category framework + * * @author michael gnehr * @author Stura - Referat IT + * * @since 07.05.2018 + * * @copyright Copyright Referat IT (C) 2018 - All rights reserved */ class AuslagenHandler2 extends FormHandlerInterface @@ -96,6 +99,7 @@ class AuslagenHandler2 extends FormHandlerInterface 'booked' => ['Gebucht', 'Gezahlt und Gebucht'], 'revocation' => ['Nichtig', ''], ]; + /** * possible substates * may multile subStates are possible @@ -180,6 +184,7 @@ class AuslagenHandler2 extends FormHandlerInterface 'instructed' => ['groups' => ['ref-finanzen-belege']], ], ]; + private static $validFieldKeys = [ 'belege' => '', 'files' => '', @@ -192,6 +197,7 @@ class AuslagenHandler2 extends FormHandlerInterface 'hv-ok' => '', 'belege-ok' => '', ]; + private static $writePermissionAll = [ 'draft' => [], 'wip' => [], @@ -200,6 +206,7 @@ class AuslagenHandler2 extends FormHandlerInterface 'booked' => [], 'revocation' => [], ]; + private static $writePermissionFields = [ 'draft' => [ 'auslagen-name' => ['groups' => ['login']], @@ -224,7 +231,9 @@ class AuslagenHandler2 extends FormHandlerInterface 'booked' => [], 'revocation' => [], ]; + private static $visibleFields = []; + /** * error flag * set in constructor @@ -232,12 +241,14 @@ class AuslagenHandler2 extends FormHandlerInterface * @var bool */ private $error; + /** * jeson result set * * @var array */ private $json_result = []; + /** * @var DBConnector */ @@ -251,28 +262,31 @@ class AuslagenHandler2 extends FormHandlerInterface * @var int */ private $projekt_id; + /** * @var array */ private $projekt_data; + /** * auslagen id * * @var int */ private $auslagen_id; + /** * auslagen data - * - * @var */ private $auslagen_data; + /** * additional title * * @var string */ private $title; + /** * routing info * @@ -294,34 +308,37 @@ class AuslagenHandler2 extends FormHandlerInterface 'user' => '', 'realname' => '', ]; + /** * contains form ids for submit buttons */ private $formSubmitButtons = []; + private $templater; // --------------------------------------------------------- /* ---------- PERMISSION ----------- */ private $permissionHandler; + private $stateHandler; /** * class constructor * check projekt id and auslagen id * - * @param array $routeInfo - * required keys: - * action, pid + * @param array $routeInfo + * required keys: + * action, pid */ public function __construct(array $routeInfo) { $this->error = false; // errors ---------------------------- - if (!isset($routeInfo['pid'])) { + if (! isset($routeInfo['pid'])) { $this->error = true; throw new LegacyDieException(400, 'missing parameter: pid - project id'); } - if (!isset($routeInfo['action'])) { + if (! isset($routeInfo['action'])) { $this->error = true; throw new LegacyDieException(400, 'missing parameter: action'); } @@ -331,14 +348,14 @@ public function __construct(array $routeInfo) $this->projekt_id = $routeInfo['pid']; // check projekt exists -------------------- - if (!$this->getDbProject()) { + if (! $this->getDbProject()) { return; } // set error // check auslage exists -------------------- if (isset($this->routeInfo['aid'])) { // check auslagen id exists -------------------- $this->auslagen_id = $routeInfo['aid']; - if (!$this->getDbAuslagen() || !$this->getDbBelegePostenFiles()) { + if (! $this->getDbAuslagen() || ! $this->getDbBelegePostenFiles()) { return; } @@ -349,7 +366,7 @@ public function __construct(array $routeInfo) $this->stateInfo = self::state2stateInfo('draft'); } - if($routeInfo['action'] === 'belege-pdf' || $routeInfo['action'] === 'zahlungsanweisung-pdf'){ + if ($routeInfo['action'] === 'belege-pdf' || $routeInfo['action'] === 'zahlungsanweisung-pdf') { return; } @@ -361,9 +378,9 @@ public function __construct(array $routeInfo) } // check if editable and action != create // if user is owner or in same organisation or is ref-finanzen - if ($this->stateInfo['editable'] && $this->routeInfo['action'] !== 'create' && !(isset($this->routeInfo['mfunction']) + if ($this->stateInfo['editable'] && $this->routeInfo['action'] !== 'create' && ! (isset($this->routeInfo['mfunction']) && $this->routeInfo['mfunction'] === 'updatecreate' - && !isset($this->routeInfo['aid'])) && !$this->checkPermissionByMap(self::$groups['strict_editable'])) { + && ! isset($this->routeInfo['aid'])) && ! $this->checkPermissionByMap(self::$groups['strict_editable'])) { $this->stateInfo['editable'] = false; } $this->stateInfo['project-editable'] = ( @@ -373,11 +390,12 @@ public function __construct(array $routeInfo) // check if there auslage should be edited $auth = AuthHandler::getInstance(); - if (!$this->stateInfo['project-editable'] && !$auth->hasGroup('ref-finanzen-belege')) { + if (! $this->stateInfo['project-editable'] && ! $auth->hasGroup('ref-finanzen-belege')) { if ($routeInfo['action'] === 'create' || $routeInfo['action'] === 'edit' || ($routeInfo['action'] === 'post' && isset($routeInfo['mfunction']) && $routeInfo['mfunction'] !== 'belegpdf')) { $this->error = 'Für das aktuelle Projekt sind (momentan) keine Abrechnungen möglich.'; + return; } } @@ -399,6 +417,7 @@ public function __construct(array $routeInfo) break; default: $this->error = 'Ungültiger request in AuslagenHandler.php'; + return; } // TODO ------------------------- @@ -444,11 +463,12 @@ private function getDbProject(): bool [], ['version' => true] ); - if (!empty($res)) { + if (! empty($res)) { $this->projekt_data = $res[0]; $this->projekt_data['auslagen'] = []; } else { - $this->error = 'Das Projekt mit der ID: ' . $this->projekt_id . ' existiert nicht. :('; + $this->error = 'Das Projekt mit der ID: '.$this->projekt_id.' existiert nicht. :('; + return false; } // get auslagen liste @@ -460,7 +480,7 @@ private function getDbProject(): bool [], ['auslagen.id' => true] ); - if (!empty($res)) { + if (! empty($res)) { $aus = []; foreach ($res as $row) { $aus[] = $row; @@ -468,6 +488,7 @@ private function getDbProject(): bool $this->projekt_data['auslagen'] = $aus; } $this->getDbProjektPosten(); + return true; } @@ -490,7 +511,7 @@ private function getDbProjektPosten(): bool ] ); $aus = []; - if (!empty($res)) { + if (! empty($res)) { foreach ($res as $row) { $aus[] = $row; } @@ -498,6 +519,7 @@ private function getDbProjektPosten(): bool return false; } $this->projekt_data['posten'] = $aus; + return true; } @@ -518,12 +540,14 @@ private function getDbAuslagen(): bool ['type' => 'inner', 'table' => 'projekte', 'on' => [['projekte.id', 'auslagen.projekt_id']]], ] ); - if (!empty($res)) { + if (! empty($res)) { $this->auslagen_data = $res[0]; + return true; } - $this->error = 'Eine Abrechnung mit der ID: ' . $this->auslagen_id . ' existiert nicht. :(
'; + $this->error = 'Eine Abrechnung mit der ID: '.$this->auslagen_id.' existiert nicht. :(
'; + return false; } @@ -561,7 +585,7 @@ private function getDbBelegePostenFiles(): bool ] ); $belege = []; - if (!empty($res)) { + if (! empty($res)) { $last_beleg = -1; $last_posten = -1; foreach ($res as $row) { @@ -613,6 +637,7 @@ private function getDbBelegePostenFiles(): bool } } $this->auslagen_data['belege'] = $belege; + return true; } @@ -622,14 +647,14 @@ private function getDbBelegePostenFiles(): bool private function stateFromAuslagenData(): void { $this->stateInfo = self::state2stateInfo($this->auslagen_data['state']); - if (!$this->auslagen_id) { + if (! $this->auslagen_id) { return; } // sub states - revocation if ($this->stateInfo['state'] === 'revocation') { $this->stateInfo['substate'] .= (($this->stateInfo['substate']) ? ',' : '') - . ($this->auslagen_data['rejected'] ? + .($this->auslagen_data['rejected'] ? 'rejected' : 'revoked'); } // sub states - wip - ok_* @@ -637,17 +662,17 @@ private function stateFromAuslagenData(): void $this->stateInfo['substate'] .= ($this->auslagen_data['ok-belege'] ? (($this->stateInfo['substate']) ? ',' : '') - . 'ok-belege' + .'ok-belege' : ''); $this->stateInfo['substate'] .= ($this->auslagen_data['ok-hv'] ? (($this->stateInfo['substate']) ? ',' : '') - . 'ok-hv' + .'ok-hv' : ''); $this->stateInfo['substate'] .= ($this->auslagen_data['ok-kv'] ? (($this->stateInfo['substate']) ? ',' : '') - . 'ok-kv' + .'ok-kv' : ''); } // sub state - instructed @@ -655,7 +680,7 @@ private function stateFromAuslagenData(): void $this->stateInfo['substate'] .= ($this->auslagen_data['payed'] ? (($this->stateInfo['substate']) ? ',' : '') - . 'payed' + .'payed' : ''); } } @@ -699,16 +724,18 @@ public static function state2stateInfo($state): array if ($split && isset($split[3])) { $out['realname'] = $split[3]; } + return $out; } // --------------------------------------------------------- /* ------------- CONSTRUCTOR ------------- */ - public function isOwner() : bool + public function isOwner(): bool { $owner = explode(';', $this->auslagen_data['created']); $owner = $owner[1]; + return \Auth::user()->username === $owner; } @@ -738,7 +765,7 @@ private function checkPermissionByMap(bool|array $map): bool ]; // check dynamic permissions foreach ($map['dynamic'] as $type) { - if (!isset($dynamic[$type])) { + if (! isset($dynamic[$type])) { continue; } switch ($type) { @@ -755,11 +782,12 @@ private function checkPermissionByMap(bool|array $map): bool } } } + return false; } /** - * @param string $verwendungszweck will be searched through with regex for fetching project / auslagen id + * @param string $verwendungszweck will be searched through with regex for fetching project / auslagen id */ public static function hookZahlung(string $verwendungszweck): void { @@ -775,7 +803,7 @@ public static function hookZahlung(string $verwendungszweck): void $wholeMatch = $matches[0]; $ah = new AuslagenHandler2(['pid' => $projectId, 'aid' => $auslagenId, 'action' => 'none']); $stateChanged = $ah->state_change('payed', $ah->getAuslagenEtag()); - if (!$stateChanged) { + if (! $stateChanged) { HTMLPageRenderer::addFlash(BT::TYPE_WARNING, "$wholeMatch konnte nicht in den Status 'gezahlt' überführt werden. Bitte prüfe diesen Eintrag manuell."); } } @@ -784,19 +812,18 @@ public function getStateString(): string { $subStateName = $this->stateInfo['substate']; if (isset(self::$subStates[$subStateName])) { - $sub = ' - ' . self::$subStates[$subStateName][2]; + $sub = ' - '.self::$subStates[$subStateName][2]; } else { $sub = ''; } - return self::getStateStringFromName($this->stateInfo['state']) . $sub; + + return self::getStateStringFromName($this->stateInfo['state']).$sub; } // --------------------------------------------------------- /* ---------- DB FUNCTIONS ---------- */ - public static function initStaticVars(): void - { - } + public static function initStaticVars(): void {} public static function getStateStringFromName($statename) { @@ -805,17 +832,19 @@ public static function getStateStringFromName($statename) public function getAuslagenEtag() { - if (!isset($this->auslagen_data['etag']) && !$this->getDbAuslagen()) { + if (! isset($this->auslagen_data['etag']) && ! $this->getDbAuslagen()) { return false; } + return $this->auslagen_data['etag']; } public function getBelegPostenFiles() { - if (!$this->getDbBelegePostenFiles()) { + if (! $this->getDbBelegePostenFiles()) { return false; } + return $this->auslagen_data['belege']; } @@ -872,10 +901,10 @@ public function handlePost(): void if ($this->error) { $this->_renderPostError(); } - if (!isset($this->routeInfo['mfunction'])) { + if (! isset($this->routeInfo['mfunction'])) { $this->error = 'mfunction not set.'; } - if (!$this->error) { + if (! $this->error) { switch ($this->routeInfo['mfunction']) { case 'updatecreate': if ($this->stateInfo['editable']) { @@ -905,19 +934,19 @@ public function handlePost(): void break; case 'belegpdf': // deprecated but error handling not fully migrated yet - if (!isset($this->auslagen_data['id'])) { + if (! isset($this->auslagen_data['id'])) { $this->error = 'Die Abrechnung wurde nicht gefunden'; - } elseif (!isset($this->auslagen_data['belege']) || count($this->auslagen_data['belege']) <= 0) { + } elseif (! isset($this->auslagen_data['belege']) || count($this->auslagen_data['belege']) <= 0) { $this->error = 'Die Abrechnung enthält keine Belege'; } else { // missing file? foreach ($this->auslagen_data['belege'] as $b) { - if (!$b['file']) { - $this->error = 'Für den Beleg [ID: ' . $b['id'] . '][NR: B' . $b['short'] . '] muss noch eine Datei hinterlegt werden.'; + if (! $b['file']) { + $this->error = 'Für den Beleg [ID: '.$b['id'].'][NR: B'.$b['short'].'] muss noch eine Datei hinterlegt werden.'; break; } } - if (!$this->error) { + if (! $this->error) { $this->post_belegpdf(); } } @@ -925,7 +954,7 @@ public function handlePost(): void break; case 'zahlungsanweisung': // deprecated - if (!isset($this->auslagen_data['id'])) { + if (! isset($this->auslagen_data['id'])) { $this->error = 'Die Abrechnung wurde nicht gefunden'; } elseif (in_array($this->stateInfo['state'], ['ok', 'instructed', 'booked'])) { $this->post_zahlungsanweisungpdf(); @@ -970,9 +999,10 @@ private function post_createupdate(): void // check etag if no new auslage if ($this->routeInfo['validated']['auslagen-id'] !== 'NEW' && $this->auslagen_data['etag'] !== $this->routeInfo['validated']['etag']) { - $this->error = '

Die Prüfsumme der Abrechnung stimmt nicht mit der gesendeten überein.

' . - '

Die Abrechnung wurde in der Zwischenzeit geändert, daher muss die Seite neu geladen werden...

' . - '

Die übertragene Version liegt ' . ($this->auslagen_data['version'] - $this->routeInfo['validated']['version']) . ' Version(en) zurück.

'; + $this->error = '

Die Prüfsumme der Abrechnung stimmt nicht mit der gesendeten überein.

'. + '

Die Abrechnung wurde in der Zwischenzeit geändert, daher muss die Seite neu geladen werden...

'. + '

Die übertragene Version liegt '.($this->auslagen_data['version'] - $this->routeInfo['validated']['version']).' Version(en) zurück.

'; + return; } if ($this->routeInfo['validated']['auslagen-id'] === 'NEW') { @@ -1001,14 +1031,14 @@ private function post_createupdate(): void if (str_contains($kb, 'new_')) { $changed_belege_flag = true; $new_belege[$kb] = $b; - } elseif (!isset($this->auslagen_data['belege'][$kb])) { + } elseif (! isset($this->auslagen_data['belege'][$kb])) { $changed_belege_flag = true; // ignore this invalid elements } else { $ob = $this->auslagen_data['belege'][$kb]; $changed_belege[$kb] = $ob; - $fileIdx = 'beleg_' . $kb; - if (!$ob['file_id'] && isset($_FILES[$fileIdx]['error']) && $_FILES[$fileIdx]['error'][0] === 0) { + $fileIdx = 'beleg_'.$kb; + if (! $ob['file_id'] && isset($_FILES[$fileIdx]['error']) && $_FILES[$fileIdx]['error'][0] === 0) { $changed_belege_flag = true; } } @@ -1017,7 +1047,7 @@ private function post_createupdate(): void if (str_contains($kp, 'new_')) { $changed_posten_flag = true; $new_posten[$kp] = ['posten' => $p, 'beleg_id' => $kb]; - } elseif (!isset($this->auslagen_data['belege'][$kb]['posten'][$kp])) { + } elseif (! isset($this->auslagen_data['belege'][$kb]['posten'][$kp])) { $changed_posten_flag = true; // ignore invalid elements } else { @@ -1033,12 +1063,12 @@ private function post_createupdate(): void } // gelöschte elemente foreach ($this->auslagen_data['belege'] as $kb => $b) { - if (!isset($this->routeInfo['validated']['belege'][$kb])) { + if (! isset($this->routeInfo['validated']['belege'][$kb])) { $changed_belege_flag = true; $removed_belege[$kb] = $b; } else { foreach ($b['posten'] as $kp => $p) { - if (!isset($this->routeInfo['validated']['belege'][$kb]['posten'][$kp])) { + if (! isset($this->routeInfo['validated']['belege'][$kb]['posten'][$kp])) { $changed_posten_flag = true; $removed_posten[$kp] = $p; } @@ -1100,8 +1130,8 @@ private function post_createupdate(): void $beleg_file_map = []; // changed ------ foreach ($changed_belege as $kb => $b) { - $fileIdx = 'beleg_' . $kb; - if (!$b['file_id'] && isset($_FILES[$fileIdx]['error'][0]) && $_FILES[$fileIdx]['error'][0] != 4) { + $fileIdx = 'beleg_'.$kb; + if (! $b['file_id'] && isset($_FILES[$fileIdx]['error'][0]) && $_FILES[$fileIdx]['error'][0] != 4) { $beleg_file_map[$kb] = [ 'file' => $fileIdx, 'link' => $b['id'], @@ -1122,9 +1152,9 @@ private function post_createupdate(): void $beleg_shortcounter = 0; $map_new_beleg_beleg_idx = []; foreach ($new_belege as $kb => $b) { - ++$beleg_shortcounter; + $beleg_shortcounter++; $db_beleg = [ - 'short' => $this->auslagen_data['version'] . '' . $beleg_shortcounter, + 'short' => $this->auslagen_data['version'].''.$beleg_shortcounter, 'created_on' => date_create()->format('Y-m-d H:i:s'), 'datum' => ($b['datum']) ?: null, 'beschreibung' => $b['beschreibung'], @@ -1133,7 +1163,7 @@ private function post_createupdate(): void $idd = $this->db->dbInsert('belege', $db_beleg); $db_beleg['id'] = $idd; $map_new_beleg_beleg_idx[$kb] = $idd; - $fileIdx = 'beleg_' . $kb; + $fileIdx = 'beleg_'.$kb; if (isset($_FILES[$fileIdx]['error'][0]) && $_FILES[$fileIdx]['error'][0] === 0) { $beleg_file_map[$kb] = [ 'file' => $fileIdx, @@ -1179,10 +1209,10 @@ private function post_createupdate(): void && isset($removed_belege[$map['beleg_id']])) { continue; } - ++$posten_shortcounter; + $posten_shortcounter++; $db_posten = [ 'id' => $nextBelegPostenId++, - 'short' => (int) ($this->auslagen_data['version'] . '' . $posten_shortcounter), + 'short' => (int) ($this->auslagen_data['version'].''.$posten_shortcounter), 'projekt_posten_id' => $map['posten']['projekt-posten'], 'ausgaben' => $map['posten']['out'], 'einnahmen' => $map['posten']['in'], @@ -1221,7 +1251,7 @@ private function post_createupdate(): void 'type' => 'modal', 'subtype' => 'server-success', 'headline' => 'Eingaben gespeichert', - 'redirect' => URIBASE . 'projekt/' . $this->projekt_id . '/auslagen/' . $this->auslagen_data['id'], + 'redirect' => URIBASE.'projekt/'.$this->projekt_id.'/auslagen/'.$this->auslagen_data['id'], ]; } @@ -1237,6 +1267,7 @@ private function get_empty_auslage(): array $newInfo['date'] = date_create()->format('Y-m-d H:i:s'); $newInfo['user'] = $auth->getUsername(); $newInfo['realname'] = $auth->getUserFullName(); + return [ 'id' => null, 'projekt_id' => $this->projekt_id, @@ -1268,10 +1299,11 @@ private function get_empty_auslage(): array protected static function encryptedStr(string $str): string { $p = $str; - if (!$p) { + if (! $p) { return ''; } $p = CryptoHandler::pad_string($p); + return CryptoHandler::encrypt_by_key($p, self::getKey()); } @@ -1284,15 +1316,17 @@ private static function getKey(): string $env = new EnvSetter(base_path('/.env')); $key = Key::createNewRandomKey()->saveToAsciiSafeString(); $env->setEnvVar('IBAN_SECRET_KEY', $key); + return $key; } private function post_filedelete(): void { if ($this->auslagen_data['etag'] !== $this->routeInfo['validated']['etag']) { - $this->error = '

Die Prüfsumme der Abrechnung stimmt nicht mit der gesendeten überein.

' . - '

Die Abrechnung wurde in der Zwischenzeit geändert, daher muss die Seite neu geladen werden...

' . - '

Die übertragene Version liegt ' . ($this->auslagen_data['version'] - $this->routeInfo['validated']['version']) . ' Version(en) zurück.

'; + $this->error = '

Die Prüfsumme der Abrechnung stimmt nicht mit der gesendeten überein.

'. + '

Die Abrechnung wurde in der Zwischenzeit geändert, daher muss die Seite neu geladen werden...

'. + '

Die übertragene Version liegt '.($this->auslagen_data['version'] - $this->routeInfo['validated']['version']).' Version(en) zurück.

'; + return; } $auth = (AUTH_HANDLER); @@ -1312,8 +1346,9 @@ private function post_filedelete(): void break; } } - if (!$found_file_id) { + if (! $found_file_id) { $this->error = 'Die Angegebene Datei konnte nicht gefunden werden.'; + return; } // delete file by link id @@ -1339,7 +1374,7 @@ private function post_filedelete(): void 'type' => 'modal', 'subtype' => 'server-success', 'headline' => 'Eingaben gespeichert', - 'redirect' => URIBASE . 'projekt/' . $this->projekt_id . '/auslagen/' . $this->auslagen_data['id'] . '/edit', + 'redirect' => URIBASE.'projekt/'.$this->projekt_id.'/auslagen/'.$this->auslagen_data['id'].'/edit', ]; } @@ -1349,8 +1384,8 @@ private function post_filedelete(): void private function post_statechange(): void { $newState = $this->routeInfo['validated']['state']; - if (!$this->state_change_possible($newState) || - !$this->state_change($newState, $this->routeInfo['validated']['etag'])) { + if (! $this->state_change_possible($newState) || + ! $this->state_change($newState, $this->routeInfo['validated']['etag'])) { $this->error = 'Diese Statusänderung ist momentan nicht möglich.'; } else { $this->json_result = [ @@ -1360,9 +1395,9 @@ private function post_statechange(): void 'type' => 'modal', 'subtype' => 'server-success', 'headline' => 'Erfolgreich', - 'redirect' => URIBASE . 'projekt/' . $this->projekt_id . '/auslagen/' . $this->auslagen_data['id'], + 'redirect' => URIBASE.'projekt/'.$this->projekt_id.'/auslagen/'.$this->auslagen_data['id'], ]; - if ($newState === 'wip' && !$this->auslagen_data['ok-belege']) { + if ($newState === 'wip' && ! $this->auslagen_data['ok-belege']) { $this->json_result['reload'] = 5000; $this->json_result['msg'] .= '
Bitte beachte, dass gegebenenfalls noch Belege eingereicht werden müssen.
(Vorlage: "Belege PDF")
'; } @@ -1382,7 +1417,7 @@ public function state_change_possible(string $newState, bool $is_sub = false): b // main stateChange ----------------------------------- if (isset(self::$states[$newState])) { // state change possible - notwendig - if (!isset(self::$stateChanges[$c][$newState])) { + if (! isset(self::$stateChanges[$c][$newState])) { return false; } // state change possible (subtypes required) - optional @@ -1392,9 +1427,9 @@ public function state_change_possible(string $newState, bool $is_sub = false): b $required_sub[] = $sub; } } - if (!$is_sub) { + if (! $is_sub) { foreach ($required_sub as $required) { - if (!str_contains($this->stateInfo['substate'], $required)) { + if (! str_contains($this->stateInfo['substate'], $required)) { return false; } } @@ -1409,9 +1444,9 @@ public function state_change_possible(string $newState, bool $is_sub = false): b // mainstatechange possible ? // same state || mainstate change possible if (self::$subStates[$newState][0] == $c || $this->state_change_possible( - self::$subStates[$newState][0], - $newState - )) { + self::$subStates[$newState][0], + $newState + )) { // if substatechange possible if (isset(self::$stateChanges[$newState][$c]) && $this->checkPermissionByMap(self::$stateChanges[$newState][$c])) { @@ -1419,6 +1454,7 @@ public function state_change_possible(string $newState, bool $is_sub = false): b } } } + return false; } @@ -1507,8 +1543,10 @@ public function state_change(string $newState, string $etag): bool // $tmp_auslage2 = $this->db->dbFetchAll('auslagen',[DBConnector::FETCH_ASSOC], [], ['id' => $this->auslagen_data['id']]); } } + return true; } + return false; } @@ -1516,36 +1554,36 @@ public function generate_belege_pdf(): void { $filePath = "/auslagen/{$this->auslagen_id}/belege-pdf-v{$this->auslagen_data['version']}.pdf"; // nothing to do if this version of the file already exists - if(\Storage::exists($filePath)){ + if (\Storage::exists($filePath)) { return; } // clean up old versions of the summary to make sure there are no leftovers from deleted files File::delete(File::glob(storage_path("app/auslagen/{$this->auslagen_id}/belege-pdf-v*.pdf"))); // generate new pdf - $info = self::state2stateInfo('draft;' . $this->auslagen_data['created']); + $info = self::state2stateInfo('draft;'.$this->auslagen_data['created']); // generate belege table $belegeTableRows = []; $belegeFiles = []; $files = []; $fh = new FileHandler($this->db); foreach ($this->auslagen_data['belege'] as $key => $beleg) { - $name = 'A' . $this->auslagen_id . '-B' . $beleg['short']; + $name = 'A'.$this->auslagen_id.'-B'.$beleg['short']; $belegeTableRows[] = [ 'id' => $name, 'date' => $beleg['datum'], 'desc' => $beleg['beschreibung'], ]; $belegeFiles[] = [ - 'filePath' => $key . '.pdf', + 'filePath' => $key.'.pdf', 'name' => $name, 'fullPage' => false, ]; - $files[$key . '.pdf'] = \Storage::get("auslagen/{$this->auslagen_id}/{$beleg['file']['hashname']}.pdf"); + $files[$key.'.pdf'] = \Storage::get("auslagen/{$this->auslagen_id}/{$beleg['file']['hashname']}.pdf"); } - $tex = new LatexGenerator(); + $tex = new LatexGenerator; $pdf = $tex->renderPdf('belege-pdf', [ - 'footer' => 'IP-'. $this->projekt_id . ' A' . $this->auslagen_id, + 'footer' => 'IP-'.$this->projekt_id.' A'.$this->auslagen_id, 'projektMeta' => [ 'ID' => $this->projekt_id, 'Name' => $this->projekt_data['name'], @@ -1553,7 +1591,7 @@ public function generate_belege_pdf(): void 'Erstellt am' => $this->projekt_data['createdat'], ], 'auslagenMeta' => [ - 'ID' => 'A' . $this->auslagen_id, + 'ID' => 'A'.$this->auslagen_id, 'Sub-Name' => $this->auslagen_data['name_suffix'], 'Erstellt am' => $info['date'], 'Eingereicht von' => $info['realname'], @@ -1573,18 +1611,18 @@ public function generate_belege_pdf(): void ], 'belegeFiles' => $belegeFiles, ], $files); - if($pdf !== null){ + if ($pdf !== null) { \Storage::put($filePath, $pdf); + return; } throw new LegacyDieException('Belege PDF kann nicht generiert werden'); - } public function generate_zahlungsanweisung_pdf(): void { $fileName = "/auslagen/{$this->auslagen_id}/zahlungsanweisung-v{$this->auslagen_data['version']}.pdf"; - if(\Storage::exists($fileName)){ + if (\Storage::exists($fileName)) { return; } @@ -1604,10 +1642,10 @@ public function generate_zahlungsanweisung_pdf(): void } } $details[] = [ - 'B' . $beleg['short'], + 'B'.$beleg['short'], // 'projektposten' => $posten['projekt_posten_id'], - number_format($posten['einnahmen'], 2, ',', '') . ' EUR', - number_format($posten['ausgaben'], 2, ',', '') . ' EUR', + number_format($posten['einnahmen'], 2, ',', '').' EUR', + number_format($posten['ausgaben'], 2, ',', '').' EUR', $pposten['haushaltstitel.titel_nr'], '__________', // space for booking number entry by hand ]; @@ -1619,8 +1657,8 @@ public function generate_zahlungsanweisung_pdf(): void // label + zusatzfreitext $recht_array = ORG_DATA['rechtsgrundlagen'][$this->projekt_data['recht']] ?? []; $recht = $recht_array['label'] ?? $this->projekt_data['recht']; - if (!empty($this->projekt_data['recht-additional'])) { - $recht .= ': ' . $this->projekt_data['recht-additional']; + if (! empty($this->projekt_data['recht-additional'])) { + $recht .= ': '.$this->projekt_data['recht-additional']; } $hv = explode(';', $this->auslagen_data['ok-hv']); $kv = explode(';', $this->auslagen_data['ok-kv']); @@ -1628,23 +1666,23 @@ public function generate_zahlungsanweisung_pdf(): void $hvString = $hv[2]; // . ' ('. date_create($hv[0])->format('d.m.y') .')'; $kvString = $kv[2]; // . ' ('. date_create($kv[0])->format('d.m.y') .')'; - $tex = new LatexGenerator(); + $tex = new LatexGenerator; $pdf = $tex->renderPdf('zahlungsanweisung', [ 'auslagenMeta' => [ - 'Projekt-ID' => 'P-' . - date_create($this->projekt_data['createdat'])->format('y') . '-' . + 'Projekt-ID' => 'P-'. + date_create($this->projekt_data['createdat'])->format('y').'-'. $this->projekt_id, 'Projektname' => $this->projekt_data['name'], 'Projektträger' => $this->projekt_data['org'], 'Rechtsgrundlage' => $recht, - 'Abrechnungs-ID' => 'A' . $this->auslagen_id, + 'Abrechnungs-ID' => 'A'.$this->auslagen_id, 'Abrechnungsname' => $this->auslagen_data['name_suffix'], ], 'zahlungsMeta' => [ 'Name' => $this->auslagen_data['zahlung-name'], 'Adresse' => $this->auslagen_data['address'], 'IBAN' => chunk_split(self::decryptedStr($this->auslagen_data['zahlung-iban']), 4, ' '), - 'Betrag' => number_format($summed_value, 2, ',', '') . ' EUR', + 'Betrag' => number_format($summed_value, 2, ',', '').' EUR', 'Datum der Zahlung' => '___.___.______', ], 'signatures' => [ @@ -1661,6 +1699,7 @@ public function generate_zahlungsanweisung_pdf(): void if ($pdf !== null) { \Storage::put($fileName, $pdf); + return; } @@ -1673,7 +1712,7 @@ public function generate_zahlungsanweisung_pdf(): void protected static function decryptedStr(string $str): string { $p = $str; - if (!$p) { + if (! $p) { return ''; } try { @@ -1684,6 +1723,7 @@ protected static function decryptedStr(string $str): string ); } $p = CryptoHandler::unpad_string($p); + return $p; } @@ -1709,14 +1749,14 @@ private function renderAuslagenerstattung(): void /* @var $auth AuthHandler */ $auth = $auth::getInstance(); $editable = $this->stateInfo['editable']; - $current_form_id = 'auslagen-form-' . count($this->formSubmitButtons); + $current_form_id = 'auslagen-form-'.count($this->formSubmitButtons); $this->formSubmitButtons[] = $current_form_id; - $this->render_auslagen_links();?> -

title) ?: ''); ?>

+ $this->render_auslagen_links(); ?> +

title) ?: ''); ?>

- routeInfo['action'] === 'view') ? $this->getStateSvg() . $this->getSvgHiddenFields() : ''; ?> + routeInfo['action'] === 'view') ? $this->getStateSvg().$this->getSvgHiddenFields() : ''; ?> routeInfo['action'] !== 'create' || (isset($this->auslagen_data['state']) && $this->auslagen_data['state'] !== 'draft')); ?> @@ -1736,27 +1776,27 @@ private function renderAuslagenerstattung(): void } else { echo self::$states[$this->stateInfo['state']][0]; } - ?>
+ ?>
routeInfo['action'] !== 'create') { - $tmpState = self::state2stateInfo('draft;' . $this->auslagen_data['created']); - if ($this->checkPermissionByMap(self::$groups['stateless']['view_creator'])) { - echo "{$tmpState['date']} {$tmpState['realname']}"; - } else { - echo $tmpState['date']; - } - } else { - echo '-'; - } - ?>
+ if ($this->routeInfo['action'] !== 'create') { + $tmpState = self::state2stateInfo('draft;'.$this->auslagen_data['created']); + if ($this->checkPermissionByMap(self::$groups['stateless']['view_creator'])) { + echo "{$tmpState['date']} {$tmpState['realname']}"; + } else { + echo $tmpState['date']; + } + } else { + echo '-'; + } + ?>
routeInfo['action'] !== 'create') ? - $this->auslagen_data['version'] . " ({$this->auslagen_data['last_change']})" : '-'; ?>
+ $this->auslagen_data['version']." ({$this->auslagen_data['last_change']})" : '-'; ?>
@@ -1809,7 +1849,7 @@ private function renderAuslagenerstattung(): void templater->getHiddenActionInput(''); ?> - +
@@ -1820,9 +1860,9 @@ private function renderAuslagenerstattung(): void 'Name der Abrechnung (zur internen Wiedererkennung möglichst eindeutig)', '', [], - ' ' . htmlspecialchars( + ' '.htmlspecialchars( $this->projekt_data['name'] - ) . '' + ).'' ); ?>

@@ -1838,21 +1878,21 @@ private function renderAuslagenerstattung(): void auslagen_data['zahlung-iban'] ?? null; - if ($iban_text) { - $iban_text = self::decryptedStr($iban_text); - } - if (!$auth->hasGroup('ref-finanzen-belege')) { - $iban_text = self::trimIban($iban_text); - } elseif ($iban_text !== '' && !is_null($iban_text)) { - $iban_text = chunk_split($iban_text, 4, ' '); - } - echo $this->templater->getTextForm( - 'zahlung-iban', - $iban_text, - [12, 12, 6], - 'DE ...', - 'Zahlungsempfänger IBAN' - ); ?> + if ($iban_text) { + $iban_text = self::decryptedStr($iban_text); + } + if (! $auth->hasGroup('ref-finanzen-belege')) { + $iban_text = self::trimIban($iban_text); + } elseif ($iban_text !== '' && ! is_null($iban_text)) { + $iban_text = chunk_split($iban_text, 4, ' '); + } + echo $this->templater->getTextForm( + 'zahlung-iban', + $iban_text, + [12, 12, 6], + 'DE ...', + 'Zahlungsempfänger IBAN' + ); ?>
templater->getTextForm( 'zahlung-vwzk', @@ -1868,10 +1908,10 @@ private function renderAuslagenerstattung(): void $tmplabel = ($this->routeInfo['action'] === 'edit' || $this->routeInfo['action'] === 'create') ? 'Anschrift Empfangsberechtigter/ZahlungspflichtigerDer StuRa ist nach §12(2)-3 ThürStudFVO verpflichtet, diese Angaben abzufragen und aufzubewahren. Nach §18 ThürStudFVO beträgt die Dauer mindestens 6 Jahre nach Genehmigung der Entlastung.' : 'Anschrift Empfangsberechtigter/Zahlungspflichtiger'; - $tmpvalue = ($this->checkPermissionByMap(self::$groups['stateless']['finanzen']) - || $this->checkPermissionByMap(self::$groups['stateless']['owner']) - || empty($this->auslagen_data['address']) - ) ? $this->auslagen_data['address'] ?? null : 'Versteckt'; ?> + $tmpvalue = ($this->checkPermissionByMap(self::$groups['stateless']['finanzen']) + || $this->checkPermissionByMap(self::$groups['stateless']['owner']) + || empty($this->auslagen_data['address']) + ) ? $this->auslagen_data['address'] ?? null : 'Versteckt'; ?> templater->getTextareaForm( 'address', $tmpvalue, @@ -1887,12 +1927,12 @@ private function renderAuslagenerstattung(): void $belege = $this->auslagen_data['belege'] ?? []; - $this->render_beleg_sums($belege, 'Gesamt'); + $this->render_beleg_sums($belege, 'Gesamt'); - $this->render_beleg_container($belege, $editable, 'Belege'); + $this->render_beleg_container($belege, $editable, 'Belege'); - $beleg_nr = 0; - $tablePartialEditable = true; // $this->permissionHandler->isEditable(["posten-name", "posten-bemerkung", "posten-einnahmen", "posten-ausgaben"], "and");?> + $beleg_nr = 0; + $tablePartialEditable = true; // $this->permissionHandler->isEditable(["posten-name", "posten-bemerkung", "posten-einnahmen", "posten-ausgaben"], "and");?>
@@ -1901,14 +1941,13 @@ private function renderAuslagenerstattung(): void routeInfo['action'] !== 'create' && $this->routeInfo['action'] !== 'edit') { if ($auth->hasGroup('ref-finanzen-belege') || $auth->getUsername() === self::state2stateInfo( - 'wip;' . $this->auslagen_data['created'] - )['user']) { + 'wip;'.$this->auslagen_data['created'] + )['user']) { $this->render_chat_box(); } } ?> generate(); + return $diagram->getChart(); } @@ -1965,7 +2005,7 @@ public function getDiagramStatelistFiltered(): array if ($k === 'revocation') { continue; } - if (!$this->state_change_possible($k)) { + if (! $this->state_change_possible($k)) { continue; } $s = $keymap[$k]; @@ -1975,7 +2015,7 @@ public function getDiagramStatelistFiltered(): array $set[$s['l']][$s['k']]['options']['trigger'] = true; } // may remove substate: reject - if (!$this->checkPermissionByMap(self::$groups['stateless']['finanzen'])) { + if (! $this->checkPermissionByMap(self::$groups['stateless']['finanzen'])) { $s = $keymap['rejected']; unset($set[$s['l']][$s['k']]['children'][$s['c']]); $set[$s['l']][$s['k']]['target'] = [['draft', 6, ['y' => 20]]]; @@ -1991,7 +2031,7 @@ public function getDiagramStatelistFiltered(): array foreach (self::$subStates as $k => $info) { $s = $keymap[$k]; // if substate was unset - if (!isset($set[$s['l']][$s['k']]['children'][$s['c']])) { + if (! isset($set[$s['l']][$s['k']]['children'][$s['c']])) { continue; } // if state = child.parent and substate is set -> continue @@ -2011,7 +2051,7 @@ public function getDiagramStatelistFiltered(): array if ($info[0] === 'revocation') { continue; } - if (!isset($set[$s['l']][$s['k']]['children'][$s['c']])) { + if (! isset($set[$s['l']][$s['k']]['children'][$s['c']])) { continue; } if (strpos($this->stateInfo['substate'], $ss) !== false && $this->stateInfo['state'] == $info[0]) { @@ -2119,11 +2159,11 @@ public function getDiagramStatelist(): array public function getSvgHiddenFields(): string { - return '
'; } } echo '
'; - if (!$this->hasError()) { + if (! $this->hasError()) { $this->renderModals(); } $this->renderFooter(); @@ -126,11 +132,11 @@ private function setPhpHeader(): void // by micha-dev // https://people.mozilla.com/~bsterne/content-security-policy/details.html // https://wiki.mozilla.org/Security/CSP/Specification - # header("X-Content-Security-Policy: allow 'self'; options inline-script eval-script"); - # header('X-Frame-Options: DENY'); - # header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); - # header('Cache-Control: post-check=0, pre-check=0', false); - # header('Pragma: no-cache'); + // header("X-Content-Security-Policy: allow 'self'; options inline-script eval-script"); + // header('X-Frame-Options: DENY'); + // header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); + // header('Cache-Control: post-check=0, pre-check=0', false); + // header('Pragma: no-cache'); } private function includeCSS(): string @@ -142,9 +148,10 @@ private function includeCSS(): string $cssFiles = array_merge($cssFiles, ...array_column($this->routeInfo['load'], 'css')); } foreach ($cssFiles as $cssFile) { - $out .= "" . PHP_EOL; + $out .= "".PHP_EOL; } - $out .= "" . PHP_EOL; + $out .= "".PHP_EOL; + return $out; } @@ -180,9 +187,10 @@ private function includeJS(): string } //var_dump($this->routeInfo["load"]); foreach ($jsFiles as $jsFile) { - $out .= "" . PHP_EOL; + $out .= "".PHP_EOL; } - $out .= "" . PHP_EOL; + $out .= "".PHP_EOL; + return $out; } @@ -195,7 +203,7 @@ private function renderPanelTabs($tabs, $linkbase, $activeTab): void @@ -205,7 +213,7 @@ private function renderPanelTabs($tabs, $linkbase, $activeTab): void private function renderModals(): void { - $this->buildModal('please-wait', 'Bitte warten - Die Anfrage wird verarbeitet.', '' . + $this->buildModal('please-wait', 'Bitte warten - Die Anfrage wird verarbeitet.', ''. '
'); $this->buildModal('server-message', 'Antwort vom Server', '...'); $this->buildModal('server-question', 'Antwort vom Server', '...', 'Ok', 'Fenster schließen'); @@ -277,12 +285,13 @@ private function renderModals(): void ); } - public static function injectModal($id, $titel, $bodycontent, $abortLabel = null, $actionLabel = null, $danger = false, callable $canConfirm = null, string $actionButtonType = "button"){ + public static function injectModal($id, $titel, $bodycontent, $abortLabel = null, $actionLabel = null, $danger = false, ?callable $canConfirm = null, string $actionButtonType = 'button') + { (new HTMLPageRenderer([]))->buildModal($id, $titel, $bodycontent, $abortLabel, $actionLabel, $danger, $canConfirm, $actionButtonType); } private function buildModal($id, $titel, $bodycontent, $abortLabel = null, $actionLabel = null, $danger = false, - callable $canConfirm = null, string $actionButtonType = "button"): void + ?callable $canConfirm = null, string $actionButtonType = 'button'): void { if ($danger === 'danger') { $buttonType1 = 'primary'; @@ -316,7 +325,7 @@ private function buildModal($id, $titel, $bodycontent, $abortLabel = null, $acti @@ -340,22 +349,22 @@ private function renderProfiling(): void return; } $out = ''; - for ($i = 0; $i < $size - 1; ++$i) { - $out .= "" . self::$profiling_names[$i] . ''; - $out .= "" . - basename(self::$profiling_sources[$i]['file']) . ':' . - self::$profiling_sources[$i]['line'] . ' + for ($i = 0; $i < $size - 1; $i++) { + $out .= "".self::$profiling_names[$i].''; + $out .= "". + basename(self::$profiling_sources[$i]['file']).':'. + self::$profiling_sources[$i]['line'].' '; $sum += self::$profiling_timing[$i + 1] - self::$profiling_timing[$i]; - $out .= '
' . sprintf('   %f
', self::$profiling_timing[$i + 1] - self::$profiling_timing[$i]) . '
'; + $out .= '
'.sprintf('   %f
', self::$profiling_timing[$i + 1] - self::$profiling_timing[$i]).'
'; } - $out .= "" . self::$profiling_names[$size - 1] . ''; - $out .= "" . - basename(self::$profiling_sources[$size - 1]['file']) . ':' . - self::$profiling_sources[$size - 1]['line'] . ' + $out .= "".self::$profiling_names[$size - 1].''; + $out .= "". + basename(self::$profiling_sources[$size - 1]['file']).':'. + self::$profiling_sources[$size - 1]['line'].' '; //Wrapp all output till now with div - $out = '

Ladezeit: ' . sprintf('%f', $sum) . '

' . $out; + $out = '

Ladezeit: '.sprintf('%f', $sum).'

'.$out; $out .= '
'; echo $out; } @@ -369,13 +378,13 @@ private function renderFooter(): void } /** - * @param string $TYPE const of BT:: + * @param string $TYPE const of BT:: */ public static function addFlash(string $TYPE, string $string, mixed $debugInfo = ''): void { $alert = HtmlAlert::make($TYPE)->body($string); if (DEV) { - if (!is_string($debugInfo)) { + if (! is_string($debugInfo)) { $debugInfo = var_export($debugInfo, true); } $strong = match ($TYPE) { @@ -386,7 +395,7 @@ public static function addFlash(string $TYPE, string $string, mixed $debugInfo = // primary? // secondary? }; - $alert->appendBody(PHP_EOL . Html::tag('i')->body($debugInfo), false)->strongMsg($strong); + $alert->appendBody(PHP_EOL.Html::tag('i')->body($debugInfo), false)->strongMsg($strong); } $flashs = request()?->session()->get('flash', []); $flashs[] = $alert; diff --git a/legacy/lib/framework/render/JsonController.php b/legacy/lib/framework/render/JsonController.php index 2ea415a6..94387a5a 100644 --- a/legacy/lib/framework/render/JsonController.php +++ b/legacy/lib/framework/render/JsonController.php @@ -3,11 +3,16 @@ * FRAMEWORK JsonHandler * * @category framework + * * @author michael g * @author Stura - Referat IT + * * @since 17.02.2018 + * * @copyright Copyright (C) 2018 - All rights reserved + * * @platform PHP + * * @requirements PHP 7.0 or higher */ @@ -19,6 +24,7 @@ class JsonController { /** * json result of the function + * * @var array */ protected $json_result; @@ -29,9 +35,7 @@ class JsonController * private class constructor * implements singleton pattern */ - public function __construct() - { - } + public function __construct() {} /** * dummy function for inheritance @@ -56,7 +60,8 @@ public function json_access_denied($message = false) /** * returns 404 not found in html format - * @param false|string $message (optional) error message + * + * @param false|string $message (optional) error message */ public function json_not_found($message = false) { @@ -67,7 +72,8 @@ public function json_not_found($message = false) /** * echo json result stored in $this->json_result - * @param bool $jsonHeader, default: false + * + * @param bool $jsonHeader, default: false */ protected function print_json_result($jsonHeader = false): void { @@ -75,13 +81,12 @@ protected function print_json_result($jsonHeader = false): void } /** - * @param array $json json data - * @param bool $jsonHeader, default: true + * @param array $json json data + * @param bool $jsonHeader, default: true */ public static function print_json(array $json, $jsonHeader = true): void { - #$json = json_encode($json, JSON_HEX_QUOT | JSON_HEX_TAG); + //$json = json_encode($json, JSON_HEX_QUOT | JSON_HEX_TAG); throw new LegacyJsonException($json); - } } diff --git a/legacy/lib/framework/render/MenuRenderer.php b/legacy/lib/framework/render/MenuRenderer.php index 5a2c1acf..ff410f00 100644 --- a/legacy/lib/framework/render/MenuRenderer.php +++ b/legacy/lib/framework/render/MenuRenderer.php @@ -23,7 +23,7 @@ class MenuRenderer extends Renderer public function __construct($pathinfo = []) { - if (!isset($pathinfo['action']) || empty($pathinfo)) { + if (! isset($pathinfo['action']) || empty($pathinfo)) { $pathinfo['action'] = self::DEFAULT; } $this->pathinfo = $pathinfo; @@ -75,7 +75,7 @@ public function render(): void public function renderProjekte($active): void { - [$hhps, $hhp_id] = $this->renderHHPSelector($this->pathinfo, URIBASE . "menu/$active/"); + [$hhps, $hhp_id] = $this->renderHHPSelector($this->pathinfo, URIBASE."menu/$active/"); echo "
"; $hhp_von = $hhps[$hhp_id]['von']; $hhp_bis = $hhps[$hhp_id]['bis']; @@ -115,6 +115,7 @@ static function ($val) { ), 'warning' ); + return; } if (is_null($hhp_bis)) { @@ -132,7 +133,7 @@ static function ($val) { } break; default: - throw new LegacyDieException(400, 'Not known active Tab: ' . $active); + throw new LegacyDieException(400, 'Not known active Tab: '.$active); break; } @@ -164,7 +165,7 @@ static function ($res, $key) use (&$pids) { ); } ); - if (!empty($pids)) { + if (! empty($pids)) { $auslagen = DBConnector::getInstance()->dbFetchAll( 'auslagen', [DBConnector::FETCH_ASSOC, DBConnector::FETCH_GROUPED], @@ -193,7 +194,7 @@ static function ($res, $key) use (&$pids) {
$inhalt) { if (count($inhalt) === 0) { continue; @@ -218,15 +219,15 @@ static function ($res, $key) use (&$pids) { $year = date('y', strtotime($projekt['createdat'])); ?>
- 0) { ?> -
renderTable( - [ - 'Name', - 'Zahlungsempfänger', - 'Einnahmen', - 'Ausgaben', - 'Status', - ], - [$auslagen[$id]], - [], - [ - [$this, 'auslagenLinkEscapeFunction'], - // 3 Parameter - null, - // 1 parameter - [$this, 'moneyEscapeFunction'], - [$this, 'moneyEscapeFunction'], - function ($stateString) { - $text = AuslagenHandler2::getStateStringFromName( - AuslagenHandler2::state2stateInfo( - $stateString - )['state'] - ); - return "
$text
"; - }, - ], - [ - [ - '', - 'Eingereicht:', - 'Σ: ' . number_format( - $sum_e_in, - 2 - ) . ' €', - 'Σ: ' . number_format( - $sum_e_out, - 2 - ) . ' €', - 'Δ: ' . number_format( - $sum_e_out - $sum_e_in, - 2 - ) . ' €', + $sum_a_in = 0; + $sum_a_out = 0; + $sum_e_in = 0; + $sum_e_out = 0; + foreach ($auslagen[$id] as $a) { + if (strpos($a['state'], 'booked') === 0 || strpos($a['state'], 'instructed') === 0) { + $sum_a_in += $a['einnahmen']; + $sum_a_out += $a['ausgaben']; + } + if (strpos($a['state'], 'revocation') !== 0 && strpos($a['state'], 'draft') !== 0) { + $sum_e_in += $a['einnahmen']; + $sum_e_out += $a['ausgaben']; + } + } + + $this->renderTable( + [ + 'Name', + 'Zahlungsempfänger', + 'Einnahmen', + 'Ausgaben', + 'Status', + ], + [$auslagen[$id]], + [], + [ + [$this, 'auslagenLinkEscapeFunction'], + // 3 Parameter + null, + // 1 parameter + [$this, 'moneyEscapeFunction'], + [$this, 'moneyEscapeFunction'], + function ($stateString) { + $text = AuslagenHandler2::getStateStringFromName( + AuslagenHandler2::state2stateInfo( + $stateString + )['state'] + ); + + return "
$text
"; + }, + ], + [ + [ + '', + 'Eingereicht:', + 'Σ: '.number_format( + $sum_e_in, + 2 + ).' €', + 'Σ: '.number_format( + $sum_e_out, + 2 + ).' €', + 'Δ: '.number_format( + $sum_e_out - $sum_e_in, + 2 + ).' €', + ], + [ + '', + 'Ausgezahlt:', + 'Σ: '.number_format( + $sum_a_in, + 2 + ).' €', + 'Σ: '.number_format( + $sum_a_out, + 2 + ).' €', + 'Δ: '.number_format( + $sum_a_out - $sum_a_in, + 2 + ).' €', ], - [ - '', - 'Ausgezahlt:', - 'Σ: ' . number_format( - $sum_a_in, - 2 - ) . ' €', - 'Σ: ' . number_format( - $sum_a_out, - 2 - ) . ' €', - 'Δ: ' . number_format( - $sum_a_out - $sum_a_in, - 2 - ) . ' €', - ], - ] - ); ?> + ] + ); ?>
-
renderAlert( - 'Warnung', - "In deinen Gremien wurden in diesem Haushaltsjahr noch keine Projekte angelegt. Fange doch jetzt damit an! Neues Projekt erstellen", - 'warning' - ); + 'Warnung', + "In deinen Gremien wurden in diesem Haushaltsjahr noch keine Projekte angelegt. Fange doch jetzt damit an! Neues Projekt erstellen", + 'warning' + ); } ?> true, 'id' => false] ); - if (!is_array($extern_meta) || empty($extern_meta)) { + if (! is_array($extern_meta) || empty($extern_meta)) { $this->renderAlert('Schade', 'Hier existieren noch keine externen Anträge. Beschwere dich am besten bei Dave um das zu ändern!', 'info'); + return; } $idToKeys = []; @@ -390,7 +393,8 @@ public function renderExtern(): void }; $innerHeaderHeadlineFun = function ($content) { $date = date_create($content['projekt_von'])->format('y'); - return "EP-" . $date . '-' . $content['id'] . ''; + + return "EP-".$date.'-'.$content['id'].''; }; $innerHeaderFun = function ($content) { return $content['projekt_name']; @@ -436,7 +440,7 @@ public function renderExtern(): void $escFun = [ function ($extern_id, $vorgang_id) { - return "V$vorgang_id " . + return "V$vorgang_id ". ""; }, function ($vorkasse, $bewilligung, $preuf, $rueck, $mahn) { @@ -453,10 +457,11 @@ function ($vorkasse, $bewilligung, $preuf, $rueck, $mahn) { } else { $str = ''; } + return $str; }, function ($hhpId, $titelId, $titelName, $titelNr) { - return "HP$hhpId - " . + return "HP$hhpId - ". "$titelNr"; }, function ($value) use ($obj) { @@ -473,6 +478,7 @@ function ($value, $pruef, $rueck, $vorkasse) use ($obj, &$sum_value) { $out_val = $value - $sum_value; $sum_value = $value; } + return $obj->moneyEscapeFunction($out_val); }, function ($wiederspruch) { @@ -516,7 +522,7 @@ function ($wiederspruch) { public function setOverviewTabs($active): void { - $linkbase = URIBASE . 'menu/'; + $linkbase = URIBASE.'menu/'; $tabs = [ 'mygremium' => " Meine Gremien", 'allgremium' => " Alle Gremien", @@ -531,13 +537,13 @@ public function setOverviewTabs($active): void public function setTodoTabs($active): void { - $linkbase = URIBASE . 'menu/'; + $linkbase = URIBASE.'menu/'; $tabs = [ 'belege' => " Belege fehlen", 'hv' => " Haushaltsverantwortliche*r", 'kv' => " Kassenverantwortliche*r", ]; - if(AuthHandler::getInstance()->hasGroup('ref-finanzen-kv')){ + if (AuthHandler::getInstance()->hasGroup('ref-finanzen-kv')) { $tabs['kv/exportBank'] = " Überweisungen"; } //$tabs["search"] = " Suche"; @@ -596,7 +602,7 @@ private function renderStuRaView(): void //TODO: also externe Anträge // $groups[] = ["name" => "Externe Anträge", "fields" => ["type" => "extern-express", "state" => "need-stura",]]; [$header, $internContent, $escapeFunctions] = $this->fetchProjectsWithState('need-stura'); - [, $internContentHV,] = $this->fetchProjectsWithState('ok-by-hv'); + [, $internContentHV] = $this->fetchProjectsWithState('ok-by-hv'); $groups = [ 'Vom StuRa abzustimmen' => $internContent, 'zur Verkündung (genehmigt von HV)' => $internContentHV, @@ -635,6 +641,7 @@ private function fetchProjectsWithState(string $statestring): array [$this, 'moneyEscapeFunction'], [$this, 'date2relstrEscapeFunction'], ]; + return [$header, $dbres, $escapeFunctionsIntern]; } @@ -657,8 +664,7 @@ private function renderHVView(): void } /** - * @param string $missingColumn can be: hv, kv, belege - * + * @param string $missingColumn can be: hv, kv, belege * @return array [$header, $auslagen, $escapeFunctionAuslagen] */ private function fetchAuslagenWithState(string $stateString, string $missingColumn): array @@ -699,6 +705,7 @@ private function fetchAuslagenWithState(string $stateString, string $missingColu [$this, 'moneyEscapeFunction'], [$this, 'date2relstrEscapeFunction'], ]; + return [$headerAuslagen, $auslagen, $escapeFunctionsAuslagen]; } @@ -717,7 +724,7 @@ public function renderKVView(): void } - private function renderMissingBelege() : void + private function renderMissingBelege(): void { $this->setTodoTabs('belege'); [$headerAuslagen, $auslagenWIP, $escapeFunctionsAuslagen] = $this->fetchAuslagenWithState('wip', 'belege'); @@ -763,11 +770,12 @@ private function renderExportBank(): void null, // 1 Parameter function ($str) { $p = $str; - if (!$p) { + if (! $p) { return ''; } $p = CryptoHandler::decrypt_by_key($p, $_ENV['IBAN_SECRET_KEY']); $p = CryptoHandler::unpad_string($p); + return $p; }, // 1 Parameter function ($pId, $pCreate, $aId, $vwdzweck, $aName, $pName) { // 6 Parameter - Verwendungszweck @@ -776,13 +784,14 @@ function ($pId, $pCreate, $aId, $vwdzweck, $aName, $pName) { // 6 Parameter - V $ret = array_filter( $ret, static function ($val) { - return !empty(trim($val)); + return ! empty(trim($val)); } ); $ret = implode(' - ', $ret); if (strlen($ret) > 140) { $ret = substr($ret, 0, 140); } + return $ret; }, function ($ausgaben, $einnahmen) use ($obj) { // 2 Parameter diff --git a/legacy/lib/framework/render/Renderer.php b/legacy/lib/framework/render/Renderer.php index 81152e4d..1596bee5 100644 --- a/legacy/lib/framework/render/Renderer.php +++ b/legacy/lib/framework/render/Renderer.php @@ -4,7 +4,6 @@ use App\Exceptions\LegacyDieException; use framework\DBConnector; -use ReflectionException; use ReflectionFunction; use ReflectionMethod; use Symfony\Component\HttpFoundation\Request; @@ -12,8 +11,11 @@ abstract class Renderer extends EscFunc { public const ALERT_WARNING = 'warning'; + public const ALERT_INFO = 'info'; + public const ALERT_DANGER = 'danger'; + public const ALERT_SUCCESS = 'success'; protected $routeInfo; @@ -29,11 +31,11 @@ public function __construct(array $routeInfo = []) public function render(): void { $action = $this->routeInfo['action']; - $methodName = 'action' . str_replace('-', '', ucwords($action, '-')); + $methodName = 'action'.str_replace('-', '', ucwords($action, '-')); if (method_exists($this, $methodName)) { echo $this->$methodName(); } else { - throw new LegacyDieException(404, "Methode $methodName not found in " . __CLASS__); + throw new LegacyDieException(404, "Methode $methodName not found in ".__CLASS__); } } @@ -48,7 +50,7 @@ protected function renderTable( array_walk( $escapeFunctions, static function (&$val) use ($defaultFunction) { - if (!isset($val) || empty($val)) { + if (! isset($val) || empty($val)) { $val = $defaultFunction; } } @@ -96,18 +98,17 @@ static function (&$val) use ($defaultFunction) { } if (count(reset($content)) !== $paramSum && count($keys) !== $paramSum) { throw new LegacyDieException(500, - "In Gruppe '$groupName' passt Spaltenzahl (" . count( + "In Gruppe '$groupName' passt Spaltenzahl (".count( reset($content) - ) . ') bzw. Key Anzahl (' . count( + ).') bzw. Key Anzahl ('.count( $keys - ) . ") nicht zur benötigten Parameterzahl $paramSum \n es wurden " . count( + ).") nicht zur benötigten Parameterzahl $paramSum \n es wurden ".count( $escapeFunctions - ) . ' Funktionen übergeben ' . $diff . ' wurde(n) hinzugefügt.' + ).' Funktionen übergeben '.$diff.' wurde(n) hinzugefügt.' ); } } - if (count($keys) === 0) { $keys = range(0, $paramSum); $assoc = false; @@ -126,7 +127,7 @@ static function (&$val) use ($defaultFunction) { $rows) { - if (!is_int($groupName)) { ?> + if (! is_int($groupName)) { ?> @@ -137,32 +138,32 @@ static function (&$val) use ($defaultFunction) { $reflectionOfFunction) { - //var_export($keys); - $arg_keys = array_slice( - $keys, - $shiftIdx, - $reflectionOfFunction->getNumberOfParameters() - ); - $args = []; - foreach ($arg_keys as $arg_key) { - $args[] = $row[$arg_key]; - } - //var_export($args); - //var_export($row); - //var_export($reflectionOfFunction->getNumberOfParameters()); - $shiftIdx += $reflectionOfFunction->getNumberOfParameters(); - if ($isReflectionMethods[$idx]) { - echo '' . call_user_func_array($escapeFunctions[$idx], $args) . ''; - } else { - echo '' . $reflectionOfFunction->invokeArgs($args) . ''; - } - } ?> + $shiftIdx = 0; + foreach ($reflectionsOfFunctions as $idx => $reflectionOfFunction) { + //var_export($keys); + $arg_keys = array_slice( + $keys, + $shiftIdx, + $reflectionOfFunction->getNumberOfParameters() + ); + $args = []; + foreach ($arg_keys as $arg_key) { + $args[] = $row[$arg_key]; + } + //var_export($args); + //var_export($row); + //var_export($reflectionOfFunction->getNumberOfParameters()); + $shiftIdx += $reflectionOfFunction->getNumberOfParameters(); + if ($isReflectionMethods[$idx]) { + echo ''.call_user_func_array($escapeFunctions[$idx], $args).''; + } else { + echo ''.$reflectionOfFunction->invokeArgs($args).''; + } + } ?> @@ -171,7 +172,7 @@ static function (&$val) use ($defaultFunction) { 0) { ?> ' . htmlspecialchars($text) . ''; + echo ''.htmlspecialchars($text).''; } protected function formatDateToMonthYear($dateString) { - return !empty($dateString) ? strftime('%b %Y', strtotime($dateString)) : ''; + return ! empty($dateString) ? strftime('%b %Y', strtotime($dateString)) : ''; } protected function renderHiddenInput($name, $value): void @@ -212,21 +213,17 @@ protected function renderHiddenInput($name, $value): void } /** - * @param $data array - * @param $groupHeaderFun - * @param $innerHeaderHeadlineFun - * @param $innerHeaderFun - * @param $innerContentFun + * @param $data array */ protected function renderAccordionPanels(array $data, $groupHeaderFun, $innerHeaderHeadlineFun, $innerHeaderFun, $innerContentFun): void { ?>
$groupContent) { - if (count($groupContent) === 0) { - continue; - } ?> + if (isset($data) && ! empty($data) && $data) { + foreach ($data as $groupHeadline => $groupContent) { + if (count($groupContent) === 0) { + continue; + } ?>
renderAlert( - 'Warnung', - "In deinen Gremien wurden in diesem Haushaltsjahr noch keine Projekte angelegt. Fange doch jetzt damit an! Neues Projekt erstellen", - 'warning' - ); - } ?> + $i++; + } + } else { + $this->renderAlert( + 'Warnung', + "In deinen Gremien wurden in diesem Haushaltsjahr noch keine Projekte angelegt. Fange doch jetzt damit an! Neues Projekt erstellen", + 'warning' + ); + } ?> "success"
, "info", "warning" or "danger" + * @param $type string has to be "success", "info", "warning" or "danger" */ protected function renderAlert($strongMsg, $msg, string $type = self::ALERT_SUCCESS): void { - if (!in_array($type, [self::ALERT_SUCCESS, self::ALERT_INFO, self::ALERT_WARNING, self::ALERT_DANGER])) { + if (! in_array($type, [self::ALERT_SUCCESS, self::ALERT_INFO, self::ALERT_WARNING, self::ALERT_DANGER])) { throw new LegacyDieException(500, 'Falscher Datentyp in renderAlert()'); } if (is_array($msg)) { @@ -316,6 +311,7 @@ protected function makeClickableMails($text) foreach ($matches[0] as $match) { $text = str_replace($match, $this->mailto($match), $text); } + return $text; } @@ -335,10 +331,11 @@ protected function makeProjektsClickable($text) $projekt_id = array_pop($array); $text = str_replace( $match, - "$match", + "$match", $text ); } + return $text; } @@ -369,24 +366,24 @@ protected function renderHHPSelector($routeInfo, $urlPrefix = URIBASE, $urlSuffi [], ['von' => false] ); - if (!isset($hhps) || empty($hhps)) { + if (! isset($hhps) || empty($hhps)) { throw new LegacyDieException(500, 'Konnte keine Haushaltspläne finden'); } - if (!isset($routeInfo['hhp-id'])) { + if (! isset($routeInfo['hhp-id'])) { foreach (array_reverse($hhps, true) as $id => $hhp) { if ($hhp['state'] === 'final') { $routeInfo['hhp-id'] = $id; } } } ?> -
'> + '>