initial commit
[namibia] / module / Workspace / src / Workspace / Amf / Workspace.php
1 <?php
2 namespace Workspace\Amf;
3
4
5
6 /**
7  * Device AMF Workspace.
8  * @author andre.fourie
9  */
10 class Workspace
11 {
12
13         /**
14          * @var boolean
15          */
16         protected $authenticated = false;
17         /**
18          * @var \User\Service\Authentication
19          */
20         protected $authDetails;
21         /**
22          * @var \Zend\ServiceManager\ServiceLocatorInterface
23          */
24     protected $serviceLocator;
25
26
27
28     /**
29      * Summoning.
30      * @param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator
31      */
32         public function __construct(\Zend\ServiceManager\ServiceLocatorInterface $serviceLocator)
33         {
34                 $this->serviceLocator = $serviceLocator;
35                 \Utility\Registry::setEntityManager(
36                                 $this->serviceLocator->get('doctrine.entitymanager.orm_default')
37                                 );
38         }
39
40         /**
41          * Set authentication session.
42          * @param unknown $token
43          */
44         protected function setAuth($token)
45         {
46                 \Utility\Registry::setSession($token);
47                 $this->authenticated = true;
48                 $this->authDetails = \Utility\Registry::getAuthData();
49         }
50
51         /**
52          * Authenticate user.
53          * @param string $email
54          * @param string $pin
55          * @return struct
56          */
57         public function login($email, $pin)
58         {
59                 $input = new \Workspace\Utility\ServiceInput('ParamSet', array(
60                                 'Login' => array(
61                                                 'email' => $email,
62                                                 'pin'   => $pin
63                                 )
64                 ));
65                 $serviceInput = new \Workspace\Utility\ServiceInput('ServiceInput', array(
66                                 'data' => $input->pack()
67                 ));
68                 $profileService = $this->serviceLocator->get('User.Service.Profile');
69                 $response = $profileService->deviceLogin($serviceInput->pack());
70                 return array(
71                                 'Meta' => array_merge(
72                                                 array('Task' => __METHOD__),
73                                                 $response['Meta']
74                                                 ),
75                                 'Data' => $response['Data']
76                 );
77         }
78
79         /**
80          * Claim a job item from queue.
81          * @param string $authToken
82          * @param string $datasetName
83          * @param integer $id
84          * @return struct
85          */
86         public function claimJob($authToken, $datasetName, $id)
87         {
88                 #-> Session.
89                 if (!$this->setAuth($authToken))
90                 {
91                         return array(
92                                         'Meta' => array(
93                                                         'Task'         => __METHOD__,
94                                                         'Status'       => 'Exception',
95                                                         'StatusReason' => 'Invalid session token.'
96                                         ),
97                                         'Data' => array()
98                         );
99                 }
100
101                 switch ($datasetName)
102                 {
103                         case 'valuations':
104                                 $entityName = '\Stock\Entity\Valuation';
105                                 break;
106                         default:
107                                 return array(
108                                                 'Meta' => array(
109                                                                 'Task'         => __METHOD__,
110                                                                 'Status'       => 'Exception',
111                                                                 'StatusReason' => 'Invalid dataset requested.'
112                                                 ),
113                                                 'Data' => array()
114                                 );
115                                 break;
116                 }
117                 $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
118                 $record = $em->getRepository($entityName)
119                         ->find($id);
120                 if (is_null($record) || 1 != $record->queueStatus)
121                 {
122                         return array(
123                                         'Meta' => array(
124                                                         'Task'         => __METHOD__,
125                                                         'Status'       => 'Fail',
126                                                         'StatusReason' => 'Job not available.',
127                                                         'DatasetName'  => $datasetName
128                                         ),
129                                         'Data' => $record->toArray()
130                         );
131                 }
132                 $record->queueStatus = 2;
133                 $em->flush();
134                 return array(
135                                 'Meta' => array(
136                                                 'Task'        => __METHOD__,
137                                                 'Status'      => 'Success',
138                                                 'DatasetName' => $datasetName
139                                 ),
140                                 'Data' => $record->toArray()
141                 );
142         }
143
144         /**
145          * Retrieve a dataset.
146          * @param string $authToken
147          * @param string $datasetName
148          * @return struct
149          */
150         public function getDataset($authToken, $datasetName)
151         {
152                 #-> Session.
153                 if (!$this->setAuth($authToken))
154                 {
155                         return array(
156                                         'Meta' => array(
157                                                         'Task'         => __METHOD__,
158                                                         'Status'       => 'Exception',
159                                                         'StatusReason' => 'Invalid session token.'
160                                         ),
161                                         'Data' => array()
162                         );
163                 }
164
165                 $datasetName = $this->request['datasetName'];
166                 switch ($datasetName)
167                 {
168                         #-> Location
169                         case 'countries': $entityName = '\Location\Entity\Country'; break;
170                         case 'regions': $entityName = '\Location\Entity\Region'; break;
171                         case 'towns': $entityName = '\Location\Entity\Town'; break;
172                         #-> Stock
173                         case 'valuations': $entityName = '\Stock\Entity\Valuation'; break;
174                         case 'accessories': $entityName = '\Stock\Entity\Accessory'; break;
175                         case 'upholstery': $entityName = '\Stock\Entity\Upholstery'; break;
176                         case 'condition': $entityName = '\Stock\Entity\Condition'; break;
177                         case 'exteriorColours': $entityName = '\Stock\Entity\ExteriorColour'; break;
178                         case 'interiorColours': $entityName = '\Stock\Entity\InteriorColour'; break;
179                         case 'fuelTypes': $entityName = '\Stock\Entity\FuelType'; break;
180                         case 'transmissionTypes': $entityName = '\Stock\Entity\TransmissionType'; break;
181                         case 'natis': $entityName = '\Stock\Entity\Natis'; break;
182                         case 'papers': $entityName = '\Stock\Entity\Paper'; break;
183                         case 'years': $entityName = '\Stock\Entity\Year'; break;
184                         case 'categories': $entityName = '\Stock\Entity\Category'; break;
185                         case 'makes': $entityName = '\Stock\Entity\Make'; break;
186                         case 'models': $entityName = '\Stock\Entity\Model'; break;
187                         case 'types': $entityName = '\Stock\Entity\Type'; break;
188                         default:
189                                 return array(
190                                                 'Meta' => array(
191                                                                 'Task'         => __METHOD__,
192                                                                 'Status'       => 'Fail',
193                                                                 'StatusReason' => 'Unknown dataset requested.',
194                                                                 'DatasetName'  => $datasetName
195                                                 ),
196                                                 'Data' => array()
197                                 );
198                                 break;
199                 }
200                 $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
201                 if ('Build' == $entityName::PULL_SYNCH_STRATEGY)
202                 {
203                         $timeStart = 0;
204                         $timeEnd   = time();
205                         $numPages  = 1;
206                         $page      = 1;
207                         $timestamp = time();
208                         $filter = 'WHERE 1 = 1 ';
209                         $filter .= defined($entityName . '::JOB_QUEUE')
210                                 ? 'AND a.queueStatus = 1'
211                                 : '';
212                         $filter .= $entityName::ARCHIVE
213                                 ? 'AND a.archived = 0'
214                                 : '';
215                         $query = $em->createQuery(
216                                         "SELECT a FROM $entityName a $filter ORDER BY a.id ASC"
217                         );
218                 }
219                 else
220                 {
221                         $page = isset($this->request['page'])
222                                 ? (int) $this->request['page']
223                                 : 1;
224                         $timeStart = isset($this->request['timeStart'])
225                                 ? (int) $this->request['timeStart']
226                                 : 0;
227                         $timeEnd = isset($this->request['timeEnd'])
228                                 ? (int) $this->request['timeEnd']
229                                 : time();
230                         $recs = 10;
231                         $filter = '';
232                         $filter .= defined($entityName . '::JOB_QUEUE')
233                                 ? 'AND a.queueStatus = 1'
234                                 : '';
235                         $filter .= $entityName::ARCHIVE
236                                 ? 'AND a.archived = 0'
237                                 : '';
238                         $query = $em->createQuery(
239                                         "SELECT a FROM $entityName a "
240                                         . "WHERE a.archived = :archived"
241                                         . " $filter"
242                                         . " AND (a.created BETWEEN :timeStart AND :timeEnd"
243                                         . "      OR a.updated BETWEEN :timeStart AND :timeEnd)"
244                                         . " ORDER BY a.id ASC"
245                                         )
246                                 ->setParameter('archived', false)
247                                 ->setParameter('timeStart', date(\Utility\Definitions\Locale::getDateTimeFormat(), $timeStart))
248                                 ->setParameter('timeEnd', date(\Utility\Definitions\Locale::getDateTimeFormat(), $timeEnd));
249                         $numRecsRes = $em->createQuery(
250                                         "SELECT COUNT(a.id) AS total "
251                                         . "FROM $entityName a "
252                                         . "WHERE a.archived = :archived"
253                                         . " $filter"
254                                         . " AND (a.created BETWEEN :timeStart AND :timeEnd"
255                                         . "      OR a.updated BETWEEN :timeStart AND :timeEnd)"
256                                         )
257                                 ->setParameter('archived', false)
258                                 ->setParameter('timeStart', date(\Utility\Definitions\Locale::getDateTimeFormat(), $timeStart))
259                                 ->setParameter('timeEnd', date(\Utility\Definitions\Locale::getDateTimeFormat(), $timeEnd))
260                                 ->getSingleResult();
261                         $numRecs = $numRecsRes['total'];
262                         error_log("num records: $numRecs");
263                         $numPages = (0 < $numRecs)
264                                 ? ceil($numRecs / $recs)
265                                 : 0;
266                         $query->setFirstResult(($page -1) * $recs)
267                                 ->setMaxResults($recs);
268                 }
269                 $dataset = $query->getResult();
270
271                 if (defined($entityName . '::JOB_QUEUE'))
272                 {
273                         foreach ($dataset as $rowId => $record)
274                         {
275                                 $dataset[$rowId] = $record->toQueueArray();
276                         }
277                 }
278                 else
279                 {
280                         foreach ($dataset as $rowId => $record)
281                         {
282                                 $dataset[$rowId] = $record->toSynchArray();
283                         }
284                 }
285                 return array(
286                                 'Meta' => array(
287                                         'Task'        => __METHOD__,
288                                         'Status'      => 'Success',
289                                         'DatasetName' => $datasetName,
290                                         'Strategy'    => $entityName::PULL_SYNCH_STRATEGY,
291                                         'DataPages'   => $numPages,
292                                         'Page'        => $page,
293                                         'StartTime'   => $timeStart,
294                                         'EndTime'     => $timeEnd
295                                 ),
296                                 'Data' => $dataset
297                 );
298         }
299
300 }