Completed
Push — master ( a8e708...5c0517 )
by Arthur
06:07
created

UserRepository::recordInductionCompleted()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4286
cc 2
eloc 5
nc 2
nop 1
1
<?php namespace BB\Repo;
2
3
use BB\Entities\User;
4
use Carbon\Carbon;
5
6
class UserRepository extends DBRepository
7
{
8
9
    /**
10
     * @var User
11
     */
12
    protected $model;
13
    /**
14
     * @var AddressRepository
15
     */
16
    private $addressRepository;
17
    /**
18
     * @var ProfileDataRepository
19
     */
20
    private $profileDataRepository;
21
    /**
22
     * @var SubscriptionChargeRepository
23
     */
24
    private $subscriptionChargeRepository;
25
26
    public function __construct(User $model, AddressRepository $addressRepository, ProfileDataRepository $profileDataRepository, SubscriptionChargeRepository $subscriptionChargeRepository)
27
    {
28
        $this->model = $model;
29
        $this->perPage = 150;
30
        $this->addressRepository = $addressRepository;
31
        $this->profileDataRepository = $profileDataRepository;
32
        $this->subscriptionChargeRepository = $subscriptionChargeRepository;
33
    }
34
35
    public function getActive()
36
    {
37
        return $this->model->active()->get();
0 ignored issues
show
Bug introduced by
The method active() does not exist on BB\Entities\User. Did you maybe mean scopeActive()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
38
    }
39
40
    public function getBillableActive()
41
    {
42
        return $this->model->active()->notSpecialCase()->get();
0 ignored issues
show
Bug introduced by
The method active() does not exist on BB\Entities\User. Did you maybe mean scopeActive()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
43
    }
44
45
    public function getPaginated(array $params)
46
    {
47
        $model = $this->model->with('roles')->with('profile');
48
49
        if ($params['showLeft']) {
50
            $model = $model->where('status', 'left');
51
        } else {
52
            $model = $model->where('status', '!=', 'left');
53
        }
54
55 View Code Duplication
        if ($this->isSortable($params)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
            return $model->orderBy($params['sortBy'], $params['direction'])->simplePaginate($this->perPage);
57
        }
58
        return $model->simplePaginate($this->perPage);
59
    }
60
61
62
    /**
63
     * Return a collection of members for public display
64
     * @param bool $showPrivateMembers Some members don't want to listed on public pages, set to true to show everyone
65
     * @return mixed
66
     */
67
    public function getActivePublicList($showPrivateMembers = false)
68
    {
69
        if ($showPrivateMembers) {
70
            return $this->model->with('profile', 'roles')->active()->where('status', '!=', 'leaving')->orderBy('given_name')->get();
71
        } else {
72
            return $this->model->with('profile', 'roles')->active()->where('status', '!=', 'leaving')->where('profile_private', 0)->orderBy('given_name')->get();
73
        }
74
    }
75
76
    public function getTrustedMissingPhotos()
77
    {
78
        return \DB::table('users')->join('profile_data', 'users.id', '=', 'profile_data.user_id')->where('key_holder', '1')->where('active', '1')->where('profile_data.profile_photo', 0)->get();
79
    }
80
81
    /**
82
     * Get a list of active members suitable for use in a dropdown
83
     * @return array
84
     */
85
    public function getAllAsDropdown()
86
    {
87
        $members = $this->getActive();
88
        $memberDropdown = [];
89
        foreach ($members as $member) {
90
            $memberDropdown[$member->id] = $member->name;
91
        }
92
        return $memberDropdown;
93
    }
94
95
    /**
96
     * @param array   $memberData The new members details
97
     * @param boolean $isAdminCreating Is the user making the change an admin
98
     * @return User
99
     */
100
    public function registerMember(array $memberData, $isAdminCreating)
101
    {
102
        if (empty($memberData['profile_photo_private'])) {
103
            $memberData['profile_photo_private'] = false;
104
        }
105
106
        if (empty($memberData['password'])) {
107
            unset($memberData['password']);
108
        }
109
110
        $memberData['hash'] = str_random(30);
111
112
        $memberData['rules_agreed'] = $memberData['rules_agreed']? Carbon::now(): null;
113
114
        $user = $this->model->create($memberData);
115
        $this->profileDataRepository->createProfile($user->id);
116
117
        $this->addressRepository->saveUserAddress($user->id, $memberData['address'], $isAdminCreating);
118
119
        return $user;
120
    }
121
122
    /**
123
     * The user has setup a payment method of some kind so they are now considered active
124
     * This will kick off the automated member checking processes
125
     *
126
     * @param integer $userId
127
     */
128
    public function ensureMembershipActive($userId)
129
    {
130
        $user = $this->getById($userId);
131
132
        //user needs to have a recent sub charge and one that was paid or is due
133
134
        $user->active = true;
135
        $user->status = 'active';
136
        $user->save();
137
138
        $outstandingCharges = $this->subscriptionChargeRepository->hasOutstandingCharges($userId);
139
140
        //If the user doesn't have any charges currently processing or they dont have an expiry date or are past their expiry data create a charge
141
        if ( ! $outstandingCharges && ( ! $user->subscription_expires || $user->subscription_expires->lt(Carbon::now()))) {
142
            //create a charge
143
144
            $chargeDate = Carbon::now();
145
146
            //If we are passed the end of month cutoff push the charge date forward to their actual charge date
147
            if ((Carbon::now()->day > 28) && $user->payment_day === 1) {
148
                $chargeDate = $chargeDate->day(1)->addMonth();
149
            }
150
151
            $this->subscriptionChargeRepository->createChargeAndBillDD($userId, $chargeDate, $user->monthly_subscription, 'due', $user->subscription_id);
152
        }
153
    }
154
155
    /**
156
     * @param integer $userId           The ID of the user to be updated
157
     * @param array   $recordData       The data to be updated
158
     * @param boolean $isAdminUpdating  Is the user making the change an admin
159
     */
160
    public function updateMember($userId, array $recordData, $isAdminUpdating)
161
    {
162
        //If the password field hasn't been filled in unset it so it doesn't get set to a blank password
163
        if (empty($recordData['password'])) {
164
            unset($recordData['password']);
165
        }
166
167
        //Update the main user record
168
        $this->update($userId, $recordData);
169
170
        //Update the user address
171
        if (isset($recordData['address']) && is_array($recordData['address'])) {
172
            $this->addressRepository->updateUserAddress($userId, $recordData['address'], $isAdminUpdating);
173
        }
174
    }
175
176
    /**
177
     * The member has left, disable their account and cancel any out stand sub charge records
178
     * The payment day is also cleared so when they start again the payment is charge happens at restart time
179
     *
180
     * @param $userId
181
     */
182
    public function memberLeft($userId)
183
    {
184
        $user = $this->getById($userId);
185
        $user->active       = false;
186
        $user->status       = 'left';
187
        $user->payment_day  = '';
188
        $user->save();
189
190
        $this->subscriptionChargeRepository->cancelOutstandingCharges($userId);
191
    }
192
193
    /**
194
     * Record the new gocardless preauth id against the user and make sure their payment method reflects this
195
     *
196
     * @param integer $userId
197
     * @param string  $subscriptionId
198
     */
199
    public function recordGoCardlessVariableDetails($userId, $subscriptionId)
200
    {
201
        $user = $this->getById($userId);
202
        if (empty($user->payment_day)) {
203
            $user->payment_day    = Carbon::now()->day;
204
        }
205
        $user->subscription_id    = $subscriptionId;
206
        $user->payment_method     = 'gocardless-variable';
207
        $user->save();
208
    }
209
210
    /**
211
     * Record the fact that the user has agreed to the member induction and the rules
212
     *
213
     * @param $userId
214
     */
215
    public function recordInductionCompleted($userId)
216
    {
217
        $user = $this->getById($userId);
218
219
        $user->induction_completed = true;
220
221
        $user->rules_agreed = $user->rules_agreed? $user->rules_agreed: Carbon::now();
222
223
        $user->save();
224
    }
225
226
}