summaryrefslogtreecommitdiff
path: root/generator/after-bake/src/Controller/ServicesController.php
blob: a3a034b9c826ff78ea0dd869fbc4268e7c49bfbe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
<?php
/**
 * Copyright 2016 Ludovic Pouzenc <ludovic@pouzenc.fr>
 * Copyright 2016 Nicolas Goaziou <mail@nicolasgoaziou.fr>
 * 
 * This file is part of CHD Gestion.
 * 
 * CHD Gestion is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * CHD Gestion is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with CHD Gestion.  If not, see <http://www.gnu.org/licenses/>.
**/
namespace App\Controller;

use App\Controller\AppController;
use Cake\Datasource\ConnectionManager;
use Cake\I18n\Time;
use DateTime;

/**
 * Services Controller
 *
 * @property \App\Model\Table\ServicesTable $Services
 */
class ServicesController extends AppController
{

	public function initialize()
   	{
		parent::initialize();
		if ($this->request->action === 'index') {
			$this->loadComponent('Paginator', [ 'limit' => 15, 'order' => [ 'Services.id' => 'DESC' ] ]);
			$this->loadComponent('Search.Prg');
		}
	}

    /**
     * Index method
     * 
     * @return void
     */
    public function index()
    {
        $this->paginate = [
            'contain' => ['Adherents', 'ServiceTypes', 'ServiceStatuts', 'Ippubliques']
        ];
		$query = $this->Services
					->find('search', $this->Services->filterParams($this->request->query));
		$this->set('services', $this->paginate($query));
        $this->set('_serialize', ['services']);

		$this->loadModel('ServiceTypes');
		$this->set('serviceTypes', $this->ServiceTypes->find('list')->toArray());
		$this->loadModel('ServiceStatuts');
		$this->set('serviceStatuts', $this->ServiceStatuts->find('list')->toArray());
    }

    /**
     * View method
     *
     * @param string|null $id Service id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $service = $this->Services->get($id, [
            'contain' => ['Adherents', 'ServiceTypes', 'ServiceStatuts', 'Ippubliques', 'Equipements' => ['EquipementModeles','Ipmgmt']]
        ]);
        $this->set('service', $service);
        $this->set('_serialize', ['service']);
    }

    /**
     * Add method
     *
     * @return void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $service = $this->Services->newEntity();
        //$service = $this->Services->newEntity(['date_debut' => new DateTime('now')]);
        if ($this->request->is('post')) {
			//FIXME il y a un pépin avec la saisie des datetime, voir si ya pas un helper / widget qui va mieux
			$this->request->data['date_debut'] = new DateTime('now');

			if ( is_numeric($this->request->data('service_type_id')) ) {
				$serviceTypeId = $this->request->data('service_type_id');

				// Utilisation du prix par défaut (pour le type de service donné)
				$this->loadModel('ServiceTypes');
				$serviceType = $this->ServiceTypes->get($serviceTypeId);
				if ( $serviceType ) {
					$this->request->data['prix_ht'] = $serviceType->prix_base_ht;
				}

				// Statut de service "Actif CHD (service_statut_id 4) si service de type Adhésion (service_type_id 1)
				// Statut de service "Prévu" (service_statut_id 1) par défaut
				$this->request->data['service_statut_id'] = ($serviceTypeId==1)?4:1;
			}

            $service = $this->Services->patchEntity($service, $this->request->data);
            if ($this->Services->save($service)) {
                $this->Flash->success(__('The service has been saved.'));
                return $this->redirect(['controller' => 'Adherents', 'action' => 'view', $service->adherent_id]);
            } else {
				debug($service);
				debug($this->request->data);
                $this->Flash->error(__('The service could not be saved. Please, try again.'));
			}
        }

		$defaultAdherent = NULL;
		$defaultServiceType = 1;
		$defaultServiceStatut = 4;

		if ( is_numeric($this->request->query('a')) ) {
			$defaultAdherent = $this->request->query('a');
			// Services non résiliés de l'adhérent passé en argument
			$hasOtherServices = $this->Services->find()
				->select('id')
				->where(['adherent_id =' => $defaultAdherent, 'service_statut_id !=' => 6])
				->first();
			if ( $hasOtherServices ) {
				$defaultServiceType = 2;
				$defaultServiceStatut = 1;
			}
		}

        $adherents = $this->Services->Adherents->find('list');
        $serviceTypes = $this->Services->ServiceTypes->find('list');
        $serviceStatuts = $this->Services->ServiceStatuts->find('list');
        $ippubliques = $this->Services->Ippubliques->find('list');
        $this->set(compact('service', 'defaultAdherent', 'adherents', 'defaultServiceType', 'serviceTypes', 'defaultServiceStatut', 'serviceStatuts', 'ippubliques'));
        $this->set('_serialize', ['service']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Service id.
     * @return void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $service = $this->Services->get($id, [
            'contain' => ['Adherents', 'ServiceTypes']
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
			//FIXME : forbid change of read-only fields in the form
            $service = $this->Services->patchEntity($service, $this->request->data);
            if ($this->Services->save($service)) {
                $this->Flash->success(__('The service has been saved.'));
                return $this->redirect(['controller' => 'Adherents', 'action' => 'view', $service->adherent_id]);
            } else {
                $this->Flash->error(__('The service could not be saved. Please, try again.'));
            }
        }
        //$adherents = $this->Services->Adherents->find('list');
        //$serviceTypes = $this->Services->ServiceTypes->find('list');
        $serviceStatuts = $this->Services->ServiceStatuts->find('list');
        //$ippubliques = $this->Services->Ippubliques->find('list');
        $this->set(compact('service', 'serviceStatuts'));
        $this->set('_serialize', ['service']);
    }

    public function activate($id = null)
    {
        $this->request->allowMethod(['post']);
		$this->loadModel('Equipements');
		$service = $this->Services->get($id);
		if ( $service ) {
			if ( $service->ippublique_id === NULL && $service->service_statut_id === 1 /* Prévu */ ) {
				//TODO : quick'n'dirty, à améliorer
				$conn = ConnectionManager::get('default');
				$rawq='SELECT FREE_IP(' . $service->id . ')';
				$stmt = $conn->execute($rawq);
				$free_ip = current($stmt->fetch());
				// Fin quick'n'dirty
				
				if ( strlen($free_ip) > 7 ) {
					$patch = array(
						'service_statut_id' => 4, /* Actif CHD */
						'ippublique_id' => $free_ip,
						'date_debut' => new DateTime('now'),
					);
					$service = $this->Services->patchEntity($service, $patch);
					if ($this->Services->save($service)) {
						$this->Flash->success(__('The service has been saved.'));
					} else {
						$this->Flash->error(__('The service could not be saved. Please, try again.'));
					}
				} else {
					$this->Flash->error(__('Can\'t find a free IP public address. Please make sure that equipements are associated to the service.'));
				}
			} else {
				$this->Flash->error(__('Can\'t activate the service. Bad service state.'));
			}
			return $this->redirect(['controller' => 'Adherents', 'action' => 'view', $service->adherent_id]);
		}
	}

    public function migrate($id = null)
    {
        $this->request->allowMethod(['post']);
		$this->loadModel('Equipements');
        $service = $this->Services->get($id, [
            'contain' => ['Equipements']
        ]);

		//TODO : quick'n'dirty, à améliorer
		$conn = ConnectionManager::get('default');
		$rawq='SELECT FREE_IP(' . $service->id . ')';
		$stmt = $conn->execute($rawq);
		$free_ip = current($stmt->fetch());
		// Fin quick'n'dirty

		$new_service = $this->Services->newEntity([
			'adherent_id'		=> $service->adherent_id,
			'service_type_id'	=> $service->service_type_id,
			'prix_ht'			=> $service->prix_ht,
			'description'		=> $service->description,
			'lat'				=> $service->lat,
			'lng'				=> $service->lng,
			'service_statut_id'	=> 4,
			'ippublique_id'		=> $free_ip,
			'date_debut'		=> Time::now(),
		]);

		$service->date_fin = Time::now();
		$service->service_statut_id = 3;

		if ( (strlen($free_ip) > 7) && $this->Services->save($new_service)) {
			$fail = false;
			foreach ( $service->equipements as $equipement ) {
				$equipement->service_id = $new_service->id;
				if ( ! $this->Equipements->save($equipement) ) {
					$fail = true;
				}
			}
			if ( $fail==false && $this->Services->save($service) ) {
				$this->Flash->success(__('The service has been saved.'));
				return $this->redirect(['controller' => 'Adherents', 'action' => 'view', $service->adherent_id]);
			}
		}
		$this->Flash->error(__('The service could not be saved. Please, try again.'));
        $this->set(compact('service', 'new_service'));
        $this->set('_serialize', ['service', 'new_service']);
    }
}