Skip to content

Commit

Permalink
Merge pull request #433 from jesusantguerrero/release/alpha7
Browse files Browse the repository at this point in the history
Release/alpha7
  • Loading branch information
jesusantguerrero authored Jul 29, 2024
2 parents 41ae983 + 1c9b3b0 commit 0c678c8
Show file tree
Hide file tree
Showing 31 changed files with 1,234 additions and 500 deletions.
5 changes: 4 additions & 1 deletion app/Domains/Automation/Services/LogerAutomationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class LogerAutomationService

public static function run(Automation $automation, $eventData = null)
{
echo "starting $automation->name with $automation->id \n";
echo "\n starting workflow:$automation->id:$automation->name";
$tasks = $automation->tasks;
$trigger = $automation->triggerTask;

Expand All @@ -32,12 +32,15 @@ public static function run(Automation $automation, $eventData = null)
$previousTask = null;
}
$entity = $task->entity;
echo "\n starting workflow-task:$task->id:$task->name";
$lastData = $entity::handle($automation, $lastData, $task, $previousTask, $trigger);
if (!$lastData) {
break;
}
$previousTask = $task;
}

echo "\n \n";
}

public static function setupService($serviceId, $service)
Expand Down
2 changes: 1 addition & 1 deletion app/Domains/Integration/Actions/APAP/APAPAlert.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function handle(Automation $automation, mixed $mail, int $index = 0): Tra
'categoryGroup' => '',
'description' => $product,
'amount' => $total * $type,
'currencyCode' => APAP::parseCurrency($tdValues[11]),
'currencyCode' => APAP::parseCurrency($tdValues[11]) ?? "DOP",
]);
} catch (Exception $e) {
Log::error($e->getMessage());
Expand Down
53 changes: 53 additions & 0 deletions app/Domains/Integration/Actions/APAP/APAPNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace App\Domains\Integration\Actions\APAP;

use Exception;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Symfony\Component\DomCrawler\Crawler;
use App\Domains\Automation\Models\Automation;
use App\Domains\Integration\Concerns\MailToTransaction;
use App\Domains\Integration\Concerns\TransactionDataDTO;

class APAPNotification implements MailToTransaction
{
use APAPAction;

public function handle(Automation $automation, mixed $mail, int $index = 0): TransactionDataDTO | null
{
$html= str_replace('<?xml version="1.0" encoding="utf-8"?>', "", $mail['message']);
$html= str_replace('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">', "", $html);
// dd($html);
$body = new Crawler($html, true, null , true);
try {
if (!$body) return null;
$productLine = $body->filter('table')->first()->text();
$visaPos = strpos($productLine, 'Visa');
$product = Str::substr($productLine, $visaPos - 1, strpos($productLine, 'terminada') - $visaPos - 1);


$tdValues = $body->filter('table td')->each(function (Crawler $node) {
return $node->text();
});

$total = (int) str_replace(',', '', $tdValues[13]);
$type = 1;

return new TransactionDataDTO([
'id' => (int) $mail['id'],
'date' => date('Y-m-d', strtotime($mail['date'])),
'payee' => $tdValues[15],
'category' => '',
'categoryGroup' => '',
'description' => $product,
'amount' => $total * $type,
'currencyCode' => APAP::parseCurrency($tdValues[11]) ?? "DOP",
]);
} catch (Exception $e) {
Log::error($e->getMessage());
return null;
}

}
}
17 changes: 4 additions & 13 deletions app/Domains/Integration/Actions/TransactionCreateEntry.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use App\Domains\Automation\Models\Automation;
use App\Domains\Transaction\Models\TransactionLine;
use App\Domains\Automation\Models\AutomationTaskAction;
use App\Domains\Transaction\Services\TransactionService;
use App\Domains\Automation\Concerns\AutomationActionContract;

class TransactionCreateEntry implements AutomationActionContract
Expand Down Expand Up @@ -63,20 +64,10 @@ public static function handle(
]),
];

$transaction = Transaction::where([
"team_id" => $transactionData['team_id'],
'date' => $transactionData['date'],
'total' => $transactionData['total'],
'currency_code' => $transactionData['currency_code'],
'direction' => $transactionData['direction'],
'payee_id' => $transactionData['payee_id'],
])
->where(
fn($q) => $q->where('description', $transactionData['description'])
->orWhere('reference', $transactionData['description'])
)->first();
$transactionService = new TransactionService();

if ($transaction) {
if ($transaction = $transactionService->findIfDuplicated($transactionData)) {
print_r($transaction);
return $transaction;
}

Expand Down
33 changes: 33 additions & 0 deletions app/Domains/Transaction/Listeners/DeleteTransactionPayment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace App\Domains\Transaction\Listeners;

use Insane\Journal\Models\Core\Payment;
use Illuminate\Contracts\Queue\ShouldQueue;
use Insane\Journal\Events\TransactionDeleted;
use App\Domains\Transaction\Services\ReconciliationService;

class DeleteTransactionPayment implements ShouldQueue
{
/**
* Create the event listener.
*/
public function __construct(private ReconciliationService $service)
{
//
}

/**
* Handle the event.
*/
public function handle(TransactionDeleted $event): void
{
echo $event->transaction->transactionable_type;
if ($event->transaction->transactionable_type == Payment::class) {
$payment = $event->transaction->transactionable;
$billingCycle = $payment->payable;
$payment->delete();
$billingCycle->update();
}
}
}
45 changes: 42 additions & 3 deletions app/Domains/Transaction/Models/BillingCycle.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Domains\Transaction\Models;

use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Insane\Journal\Models\Core\Payment;
Expand Down Expand Up @@ -143,9 +144,9 @@ public static function checkPayments($payable)
}

public function linkPayment(Transaction $transaction, $formData) {
// if ($this->debt <= 0) {
// throw new Exception("The document {$this->concept} is already paid");
// }
if ($this->debt <= 0) {
throw new Exception("The document {$this->concept} is already paid");
}

$payment = $this->payments()->create([
"amount" => $transaction->total,
Expand All @@ -171,4 +172,42 @@ public function linkPayment(Transaction $transaction, $formData) {

return $payment;
}

public function createPayment($formData)
{
$paid = $this->payments->sum('amount');
if ($paid >= $this->total) {
throw new Exception("This invoice is already paid");
}

$debt = $this->total - $paid;

$formData['amount'] = $formData['amount'] > $debt ? $debt : $formData['amount'];
$payment = $this->payments()->create([
...$formData,
'user_id' => $formData['user_id'] ?? $this->user_id,
'team_id' => $formData['team_id'] ?? $this->team_id,
'client_id' => $formData['client_id'] ?? $this->user_id,
]);

$this->save();
return $payment;
}

public function createPaymentTransaction(Payment $payment) {
$direction = Transaction::DIRECTION_CREDIT;
$counterAccountId = $this->account_id;

return [
"team_id" => $payment->team_id,
"user_id" => $payment->user_id,
"date" => $payment->payment_date,
"description" => $payment->concept,
"direction" => $direction,
"total" => $payment->amount,
"account_id" => $payment->account_id,
"counter_account_id" => $counterAccountId,
"items" => []
];
}
}
7 changes: 7 additions & 0 deletions app/Domains/Transaction/Services/CreditCardReportService.php
Original file line number Diff line number Diff line change
Expand Up @@ -307,4 +307,11 @@ public function linkCreditCardPayment(BillingCycle $billingCycle, Transaction $t
$billingCycle->linkPayment($transaction, $postData);
$billingCycle->save();
}

public function addPayment(BillingCycle $billingCycle, $postData)
{
$payment = $billingCycle->createPayment($postData);
$billingCycle->save();
return $payment;
}
}
39 changes: 31 additions & 8 deletions app/Domains/Transaction/Services/TransactionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,12 @@ public static function getCategoryExpenseDetails($teamId, $startDate, $endDate,
];
}

public static function getCategoryExpensesGroup($teamId, $startDate, $endDate, $limit = null)
public static function getCategoryExpensesGroup($teamId, $startDate, $endDate, $limit = null, $categories = [])
{
$categories = collect($categories);
$excluded = $categories->filter( fn ($id) => $id < 0)->map(fn($item) => abs($item))->all();
$included = $categories->filter( fn ($id) => $id > 0)->all();

$totals = DB::table('transaction_lines')->where([
'transaction_lines.team_id' => $teamId,
'transactions.status' => 'verified',
Expand All @@ -203,12 +207,13 @@ public static function getCategoryExpensesGroup($teamId, $startDate, $endDate, $
->whereNot('catGroup.name', BudgetReservedNames::INFLOW->value)
->whereBetween('transactions.date', [$startDate, $endDate])
->select(DB::raw("
ABS(sum(transaction_lines.amount * transaction_lines.type)) as total,
catGroup.name,
catGroup.id,
group_concat(concat(transaction_lines.id, '/',accounts.name, '/', transactions.date, '/', payees.name, '/', transaction_lines.concept, '/', amount * transaction_lines.type) SEPARATOR '|') as details
",
))
ABS(sum(transaction_lines.amount * transaction_lines.type)) as total,
catGroup.name,
catGroup.id,
group_concat(concat(transaction_lines.id, '/',accounts.name, '/', transactions.date, '/', payees.name, '/', transaction_lines.concept, '/', amount * transaction_lines.type) SEPARATOR '|') as details
"))
->when(count($excluded), fn($q) => $q->whereNotIn('transaction_lines.category_id', $excluded))
->when(count($included), fn($q) => $q->whereIn('transaction_lines.category_id', $included))
->join('transactions', 'transactions.id', 'transaction_id')
->join('accounts', 'accounts.id', 'transaction_lines.account_id')
->join('categories', 'categories.id', 'transaction_lines.category_id')
Expand Down Expand Up @@ -514,5 +519,23 @@ public function getCreditCardSpentTransactions(int $teamId) {
'g.display_id' => 'liabilities',
])
->get();
}
}

public function findIfDuplicated($transactionData) {
print_r($transactionData);
return Transaction::where([
"team_id" => $transactionData['team_id'],
'date' => $transactionData['date'],
'total' => $transactionData['total'],
'currency_code' => $transactionData['currency_code'],
'direction' => $transactionData['direction'],
'payee_id' => $transactionData['payee_id'],
])
->where(
fn($q) => $q->where('description', $transactionData['description'])
->orWhere('reference', $transactionData['reference'])
)
->orWhere("reference", $transactionData['reference'])
->first();
}
}
12 changes: 12 additions & 0 deletions app/Http/Controllers/Api/BillingCycleApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,16 @@ public function linkPayments(CreditCardReportService $creditCardReportService, B
}
}

public function addPayment(CreditCardReportService $creditCardReportService, BillingCycle $billingCycle) {
try {
return $creditCardReportService->addPayment($billingCycle, request()->post());
} catch (Exception $e) {
return response([
'status' => [
'message' => $e->getMessage()
]
], 400);
}
}

}
11 changes: 7 additions & 4 deletions app/Http/Controllers/Finance/FinanceTrendController.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,16 @@ public function group(Request $request)
$queryParams = $request->query();
$filters = isset($queryParams['filter']) ? $queryParams['filter'] : [];
[$startDate, $endDate] = $this->getFilterDates($filters);
$excludedCategories = null;

if (isset($filters['category'])) {
$excludedCategories = collect(explode(',', $filters['category']))->map(fn ($id) => "-$id")->all();
}

$teamId = $request->user()->current_team_id;

return [
'data' => TransactionService::getCategoryExpensesGroup($teamId, $startDate, $endDate),
'data' => TransactionService::getCategoryExpensesGroup($teamId, $startDate, $endDate, null, $excludedCategories),
'metaData' => [
'title' => 'Category Group Trends',
'name' => 'group'
Expand Down Expand Up @@ -198,7 +203,7 @@ public function spendingYear()
{
$queryParams = request()->query();
$filters = isset($queryParams['filter']) ? $queryParams['filter'] : [];
[$startDate, $endDate] = $this->getFilterDates($filters);
[ $startDate ] = $this->getFilterDates($filters);
$teamId = request()->user()->current_team_id;
$excludedAccounts = null;
if (isset($filters['category'])) {
Expand Down Expand Up @@ -228,8 +233,6 @@ public function assignedInYear()
$excludedAccounts = collect(explode(',', $filters['category']))->map(fn ($id) => "-$id")->all();
}

// dd(ReportService::generateExpensesByPeriod($teamId, $startDate, 12, 'month', $excludedAccounts), ReportService::getAssignedByPeriod($teamId, $startDate, 12, 'month', $excludedAccounts));

return [
'data' => ReportService::getAssignedByPeriod($teamId, $startDate, 12, 'month', $excludedAccounts),
'metaData' => [
Expand Down
2 changes: 2 additions & 0 deletions app/Providers/EventServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use Laravel\Jetstream\Events\TeamMemberAdded;
use Insane\Journal\Listeners\CreateTeamAccounts;
use App\Listeners\CreateBudgetTransactionMovement;
use App\Domains\Transaction\Listeners\DeleteTransactionPayment;
use App\Domains\Transaction\Listeners\UpdateOpenReconciliations;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
Expand Down Expand Up @@ -76,6 +77,7 @@ class EventServiceProvider extends ServiceProvider
TransactionDeleted::class => [
CreateBudgetTransactionMovement::class,
UpdateBudgetAvailable::class,
DeleteTransactionPayment::class,
],
AppCreated::class => [
ShowInApp::class,
Expand Down
Loading

0 comments on commit 0c678c8

Please sign in to comment.