Issues (158)

app/Console/Commands/SyncUsers.php (1 issue)

Labels
Severity
1
<?php declare(strict_types=1);
2
3
namespace App\Console\Commands;
4
5
use App\User;
6
use App\Alma\AlmaUsers as AlmaConnector;
7
use Illuminate\Console\Command;
0 ignored issues
show
This use statement conflicts with another class in this namespace, App\Console\Commands\Command. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
9
use Illuminate\Database\Eloquent\Builder;
10
use PDOException;
11
use Scriptotek\Alma\Client as AlmaClient;
12
use Scriptotek\Alma\Exception\RequestFailed;
13
14
class SyncUsers extends Command
15
{
16
    /**
17
     * The name and signature of the console command.
18
     *
19
     * @var string
20
     */
21
    protected $signature = 'bibrex:sync-users';
22
23
    /**
24
     * The console command description.
25
     *
26
     * @var string
27
     */
28
    protected $description = 'Fetch changes to Alma users and try to link unlinked users.';
29
30
    /** @var AlmaClient */
31
    protected $alma;
32
33
    /** @var AlmaConnector */
34
    protected $almaConnector;
35
36
    /**
37
     * Create a new command instance.
38
     *
39
     * @param AlmaClient $alma
40
     */
41
    public function __construct(AlmaClient $alma, AlmaConnector $almaConnector)
42
    {
43
        parent::__construct();
44
        $this->alma = $alma;
45
        $this->almaConnector = $almaConnector;
46
    }
47
48
    /**
49
     * Update a single user
50
     *
51
     * @param User $user
52
     */
53
    protected function processUser(User $user)
54
    {
55
        if ($user->in_alma) {
56
            // Låner er allerede koblet til Alma
57
            if ($this->almaConnector->updateLocalUserFromAlmaUser($user)) {
58
                if ($user->isDirty()) {
59
                    \Log::info(sprintf(
60
                        'Brukeren <a href="%s">%s</a> ble oppdatert fra Alma.',
61
                        action('UsersController@getShow', $user->id),
62
                        $user->name
63
                    ));
64
                }
65
            } else {
66
                \Log::warning(sprintf(
67
                    'Brukeren <a href="%s">%s</a> finnes ikke lenger i Alma.',
68
                    action('UsersController@getShow', $user->id),
69
                    $user->name
70
                ));
71
            }
72
        } elseif ($this->almaConnector->updateLocalUserFromAlmaUser($user)) {
73
            // Sjekk om låner kan kobles til Alma
74
            \Log::info(sprintf(
75
                'Brukeren <a href="%s">%s</a> ble koblet med en Alma-bruker.',
76
                action('UsersController@getShow', $user->id),
77
                $user->name
78
            ));
79
            $this->transferLoans($user);
80
        } else {
81
            // Lokal bruker
82
        }
83
84
        try {
85
            $user->save();
86
        } catch (PDOException $e) {
87
            $this->error('Konflikt!');
88
            \Log::warning(sprintf(
89
                'Brukeren <a href="%s">%s</a> kunne ikke lagres på grunn av en konflikt - to brukere har ' .
90
                'samme strekkode eller feide-id. Sjekk i brukerlista om det er to brukere som kan slås sammen.',
91
                action('UsersController@getShow', $user->id),
92
                $user->name
93
            ));
94
            return;
95
        }
96
97
        if ($user->in_alma) {
98
            // Check if user have loans of thing_id 1 and transfer them if so.
99
            // In case the user was manually synced during the day.
100
            $tempLoans = $user->loans()->whereHas('item', function (Builder $query) {
101
                $query->where('thing_id', 1);
102
            })->count();
103
104
            if ($tempLoans) {
105
                $this->transferLoans($user);
106
            }
107
        }
108
    }
109
110
    /**
111
     * Execute the console command.
112
     *
113
     * @return mixed
114
     */
115
    public function handle()
116
    {
117
        foreach (\DB::table('users')->get(['id']) as $row) {
118
            $user = User::find($row->id);
119
            // Users may be deleted during the sync process. Therefore we
120
            // make sure the user still exists before processing it, to
121
            // avoid re-creating a deleted user.p
122
            if (!is_null($user)) {
123
                $this->line("Checking user {$user->id}");
124
                $this->processUser($user);
125
            }
126
        }
127
        $this->line("Done");
128
    }
129
130
    protected function transferLoans(User $localUser)
131
    {
132
        $almaUser = $this->alma->users[$localUser->alma_primary_id];
133
134
        if (is_null($almaUser)) {
135
            \Log::error("Kunne ikke overføre lån fordi Alma-brukeren ikke ble funnet. Meget uventet.");
136
            return;
137
        }
138
139
        $n = 0;
140
141
        foreach ($localUser->loans as $loan) {
142
            if ($loan->item->thing_id == 1) {
143
                // Loan should be transferred from the temporary card to the user
144
145
                $barcode = $loan->item->barcode;
146
                $library = $loan->library;
147
148
                $errBecause = "Kunne ikke overføre lån av $barcode i Alma fordi";
149
150
                if (is_null($library->temporary_barcode)) {
151
                    \Log::error("$errBecause biblioteket ikke lenger har et midlertidig lånekort.");
152
                    continue;
153
                }
154
155
                if (is_null($library->library_code)) {
156
                    \Log::error("$errBecause biblioteket ikke lenger har en bibliotekskode.");
157
                    continue;
158
                }
159
160
                $tempUser = $this->alma->users[$library->temporary_barcode];
161
                $almaLibrary = $this->alma->libraries[$library->library_code];
162
163
                if (is_null($tempUser)) {
164
                    \Log::error("$errBecause brukeren '{$library->temporary_barcode}' ikke ble funnet i Alma.");
165
                    continue;
166
                }
167
168
                $almaItem = $this->alma->items->fromBarcode($barcode);
169
                $almaLoan = $almaItem->loan;
170
171
                if (is_null($almaLoan)) {
172
                    \Log::warning("$errBecause dokumentet i mellomtiden har blitt returnert i Alma.");
173
174
                    // Checkin local loan and delete temporary item
175
                    $loan->checkIn();
176
177
                    continue;
178
                }
179
180
                if ($almaLoan->user_id != $library->temporary_barcode) {
181
                    \Log::warning("$errBecause dokumentet ikke lenger er utlånt til {$library->temporary_barcode}.");
182
183
                    // Checkin local loan and delete temporary item
184
                    $loan->checkIn();
185
186
                    continue;
187
                }
188
189
                if (count($almaItem->requests)) {
190
                    \Log::warning("$errBecause dokumentet har reserveringer.");
191
                    continue;
192
                }
193
194
                // Cross fingers
195
                try {
196
                    $almaItem->scanIn($almaLibrary, 'DEFAULT_CIRC_DESK', [
197
                        'place_on_hold_shelf' => 'false',
198
                        'auto_print_slip' => 'false',
199
                    ]);
200
                    $almaItem->checkOut($almaUser, $almaLibrary);
201
                } catch (RequestFailed $e) {
202
                    \Log::warning($errBecause . ' ' . $e->getMessage());
203
                    continue;
204
                }
205
206
                \Log::info(sprintf(
207
                    'Overførte lån av <a href="%s">%s</a> til Alma-brukeren.',
208
                    action('ItemsController@show', $loan->item->id),
209
                    $barcode
210
                ));
211
212
                // Checkin local loan and delete temporary item
213
                $loan->checkIn();
214
215
                $n++;
216
            }
217
        }
218
    }
219
}
220