Failed Conditions
Push — master ( 8edf11...8ca883 )
by Sylvain
08:08 queued 01:18
created

AccountRepository::getNextCodeAvailable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 7
ccs 0
cts 5
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Repository;
6
7
use Application\DBAL\Types\AccountTypeType;
8
use Application\Model\Account;
9
use Application\Model\User;
10
use Doctrine\ORM\Query;
11
use Ecodev\Felix\Repository\LimitedAccessSubQuery;
12
use Exception;
13
use Money\Money;
14
15
/**
16
 * Class AccountRepository
17
 *
18
 * @method null|Account findOneByCode(int $code)
19
 */
20
class AccountRepository extends AbstractRepository implements LimitedAccessSubQuery
21
{
22
    const ACCOUNT_ID_FOR_BANK = 10025;
23
24
    /**
25
     * In memory max code that keep being incremented if we create several account at once without flushing in DB
26
     */
27
    private ?int $maxCode = null;
28
29
    /**
30
     * Clear all caches
31
     */
32 118
    public function clearCache(): void
33
    {
34 118
        $this->maxCode = null;
35 118
    }
36
37
    /**
38
     * Returns pure SQL to get ID of all objects that are accessible to given user.
39
     *
40
     * @param null|User $user
41
     */
42 22
    public function getAccessibleSubQuery(?\Ecodev\Felix\Model\User $user): string
43
    {
44 22
        if (!$user) {
45 1
            return '-1';
46
        }
47
48 21
        if (in_array($user->getRole(), [
49 21
            User::ROLE_TRAINER,
50
            User::ROLE_ACCOUNTING_VERIFICATOR,
51
            User::ROLE_RESPONSIBLE,
52
            User::ROLE_ADMINISTRATOR,
53 21
        ], true)) {
54 11
            return $this->getAllIdsQuery();
55
        }
56
57 10
        if ($user->getRole() === User::ROLE_FORMATION_RESPONSIBLE) {
58
            return $this->getAllIdsForAnyOwner();
59
        }
60
61 10
        return $this->getAllIdsForFamilyQuery($user);
62
    }
63
64
    /**
65
     * Unsecured way to get a account from its ID.
66
     *
67
     * This should only be used in tests or controlled environment.
68
     */
69 5
    public function getOneById(int $id): Account
70
    {
71 5
        $account = $this->getAclFilter()->runWithoutAcl(function () use ($id) {
72 5
            return $this->findOneById($id);
73 5
        });
74
75 5
        if (!$account) {
76 1
            throw new Exception('Account #' . $id . ' not found');
77
        }
78
79 5
        return $account;
80
    }
81
82
    /**
83
     * This will return, and potentially create, an account for the given user
84
     */
85 21
    public function getOrCreate(User $user): Account
86
    {
87
        global $container;
88
89
        // If an account already exists, because getOrCreate was called once before without flushing in between,
90
        // then can return immediately
91 21
        if ($user->getAccount()) {
92 14
            return $user->getAccount();
93
        }
94
95
        // If user have an owner, then create account for the owner instead
96 9
        if ($user->getOwner()) {
97
            $user = $user->getOwner();
98
        }
99
100 9
        $account = $this->getAclFilter()->runWithoutAcl(function () use ($user) {
101 9
            return $this->findOneByOwner($user);
0 ignored issues
show
Bug introduced by
The method findOneByOwner() does not exist on Application\Repository\AccountRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

101
            return $this->/** @scrutinizer ignore-call */ findOneByOwner($user);
Loading history...
102 9
        });
103
104 9
        if (!$account) {
105 9
            $account = new Account();
106 9
            $this->getEntityManager()->persist($account);
107 9
            $account->setOwner($user);
108 9
            $account->setType(AccountTypeType::LIABILITY);
109 9
            $account->setName($user->getName());
110
111 9
            $config = $container->get('config');
112 9
            $parentCode = (int) $config['accounting']['customerDepositsAccountCode'];
113 9
            $parent = $this->getAclFilter()->runWithoutAcl(function () use ($parentCode) {
114 9
                return $this->findOneByCode($parentCode);
115 9
            });
116
117
            // Find the max account code, using the liability parent code as prefix
118 9
            if (!$this->maxCode) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->maxCode of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
119 9
                $maxQuery = 'SELECT MAX(code) FROM account WHERE code LIKE ' . $this->getEntityManager()->getConnection()->quote($parent->getCode() . '%');
120 9
                $this->maxCode = (int) $this->getEntityManager()->getConnection()->fetchOne($maxQuery);
121
122
                // If there is no child account yet, reserve enough digits for many users
123 9
                if ($this->maxCode === $parent->getCode()) {
124 1
                    $this->maxCode = $parent->getCode() * 10000;
125
                }
126
            }
127
128 9
            $nextCode = ++$this->maxCode;
129 9
            $account->setCode($nextCode);
130
131 9
            $account->setParent($parent);
132
        }
133
134 9
        return $account;
135
    }
136
137
    /**
138
     * Sum balance by account type
139
     *
140
     * @API\Input(type="AccountType")
141
     */
142 2
    public function totalBalanceByType(string $accountType): Money
143
    {
144 2
        $qb = $this->getEntityManager()->getConnection()->createQueryBuilder()
145 2
            ->select('SUM(balance)')
146 2
            ->from($this->getClassMetadata()->getTableName())
147 2
            ->where('type = :type');
148
149 2
        $qb->setParameter('type', $accountType);
150
151 2
        $result = $qb->execute();
152
153 2
        return Money::CHF($result->fetchOne());
0 ignored issues
show
Bug introduced by
The method fetchOne() does not exist on integer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

153
        return Money::CHF($result->/** @scrutinizer ignore-call */ fetchOne());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
154
    }
155
156
    /**
157
     * Update all accounts' balance
158
     */
159 1
    public function updateAccountsBalance(): void
160
    {
161 1
        $connection = $this->getEntityManager()->getConnection();
162 1
        $sql = 'CALL update_account_balance(0)';
163 1
        $connection->executeQuery($sql);
164 1
    }
165
166
    /**
167
     * Return the next available Account code
168
     */
169
    public function getNextCodeAvailable(): int
170
    {
171
        $qb = _em()->getConnection()->createQueryBuilder()
172
            ->select('IFNULL(MAX(a.code) + 1, 1)')
173
            ->from('account', 'a');
174
175
        return (int) $qb->execute()->fetchOne();
0 ignored issues
show
Bug introduced by
The method fetchOne() does not exist on integer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

175
        return (int) $qb->execute()->/** @scrutinizer ignore-call */ fetchOne();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
176
    }
177
178 1
    public function getRootAccountsQuery(): Query
179
    {
180 1
        $qb = $this->createQueryBuilder('account')
181 1
            ->andWhere('account.parent IS NULL')
182 1
            ->orderBy('account.code');
183
184 1
        return $qb->getQuery();
185
    }
186
187 2
    public function deleteAccountOfNonFamilyOwnerWithoutAnyTransactions(): int
188
    {
189
        $sql = <<<STRING
190 2
                DELETE account FROM account
191
                INNER JOIN user ON account.owner_id = user.id
192
                AND user.owner_id IS NOT NULL
193
                AND user.owner_id != user.id
194
                WHERE
195
                account.id NOT IN (SELECT credit_id FROM transaction_line WHERE credit_id IS NOT NULL)
196
                AND account.id NOT IN (SELECT debit_id FROM transaction_line WHERE debit_id IS NOT NULL) 
197
            STRING;
198
199 2
        $count = $this->getEntityManager()->getConnection()->executeStatement($sql);
200
201 2
        return $count;
202
    }
203
}
204