1: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2:
3: class Appointments_Model extends CI_Model {
4: /**
5: * Class Constructor
6: */
7: public function __construct() {
8: parent::__construct();
9: }
10:
11: /**
12: * Add an appointment record to the database.
13: *
14: * This method adds a new appointment to the database. If the
15: * appointment doesn't exists it is going to be inserted, otherwise
16: * the record is going to be updated.
17: *
18: * @expectedException ValidationException Raises when the appointment data
19: * are invalid.
20: * @expectedException DatabaseException Raises when the insert or update
21: * operation fail to complete successfully.
22: *
23: * @param array $appointment_data Associative array with the appointment
24: * data. Each key has the same name with the database fields.
25: * @return int Returns the appointments id.
26: */
27: public function add($appointment_data) {
28: // Validate the appointment data before doing anything.
29: if (!$this->validate_data($appointment_data)) {
30: throw new ValidationException('Appointment data are invalid.');
31: }
32:
33: // Perform insert() or update() operation.
34: if (!isset($appointment_data['id'])) {
35: $appointment_data['id'] = $this->insert($appointment_data);
36: } else {
37: $this->update($appointment_data);
38: }
39:
40: return $appointment_data['id'];
41: }
42:
43: /**
44: * Check if a particular appointment record already exists.
45: *
46: * This method checks wether the given appointment already exists
47: * in the database. It doesn't search with the id, but by using the
48: * following fields: "start_datetime", "end_datetime", "id_users_provider",
49: * "id_users_customer", "id_services".
50: *
51: * @expectedException InvalidArgumentException When the $appointment_data
52: * array does not contain the necessary field.
53: *
54: * @param array $appointment_data Associative array with the appointment's
55: * data. Each key has the same name with the database fields.
56: * @return bool Returns wether the record exists or not.
57: */
58: public function exists($appointment_data) {
59: if (!isset($appointment_data['start_datetime'])
60: || !isset($appointment_data['end_datetime'])
61: || !isset($appointment_data['id_users_provider'])
62: || !isset($appointment_data['id_users_customer'])
63: || !isset($appointment_data['id_services'])) {
64: throw new InvalidArgumentException('Not all appointment field values '
65: . 'are provided : ' . print_r($appointment_data, TRUE));
66: }
67:
68: $num_rows = $this->db->get_where('ea_appointments', array(
69: 'start_datetime' => $appointment_data['start_datetime'],
70: 'end_datetime' => $appointment_data['end_datetime'],
71: 'id_users_provider' => $appointment_data['id_users_provider'],
72: 'id_users_customer' => $appointment_data['id_users_customer'],
73: 'id_services' => $appointment_data['id_services'],))
74: ->num_rows();
75:
76: return ($num_rows > 0) ? TRUE : FALSE;
77: }
78:
79: /**
80: * Insert a new appointment record to the database.
81: *
82: * @expectedException DatabaseException Raises when the insert operation
83: * failes to complete successfully.
84: *
85: * @param array $appointment_data Associative array with the appointment's
86: * data. Each key has the same name with the database fields.
87: * @return int Returns the id of the new record.
88: */
89: private function insert($appointment_data) {
90: $appointment_data['book_datetime'] = date('Y-m-d H:i:s');
91: $appointment_data['hash'] = $this->generate_hash();
92:
93: if (!$this->db->insert('ea_appointments', $appointment_data)) {
94: throw new DatabaseException('Could not insert appointment record.');
95: }
96:
97: return intval($this->db->insert_id());
98: }
99:
100: /**
101: * Update an existing appointment record in the database.
102: *
103: * The appointment data argument should already include the record
104: * id in order to process the update operation.
105: *
106: * @expectedException DatabaseException Raises when the update operation
107: * failes to complete successfully.
108: *
109: * @param array $appointment_data Associative array with the appointment's
110: * data. Each key has the same name with the database fields.
111: */
112: private function update($appointment_data) {
113: $this->db->where('id', $appointment_data['id']);
114: if (!$this->db->update('ea_appointments', $appointment_data)) {
115: throw new DatabaseException('Could not update appointment record.');
116: }
117: }
118:
119: /**
120: * Find the database id of an appointment record.
121: *
122: * The appointment data should include the following fields in order
123: * to get the unique id from the database: "start_datetime", "end_datetime",
124: * "id_users_provider", "id_users_customer", "id_services".
125: *
126: * <strong>IMPORTANT!</strong> The record must already exists in the
127: * database, otherwise an exception is raised.
128: *
129: * @expectedException DatabaseException Raises when this method cannot
130: * find any record that matches the given data.
131: *
132: * @param array $appointment_data Array with the appointment data. The
133: * keys of the array should have the same names as the db fields.
134: * @return int Returns the db id of the record that matches the apppointment
135: * data.
136: */
137: public function find_record_id($appointment_data) {
138: $this->db->where(array(
139: 'start_datetime' => $appointment_data['start_datetime'],
140: 'end_datetime' => $appointment_data['end_datetime'],
141: 'id_users_provider' => $appointment_data['id_users_provider'],
142: 'id_users_customer' => $appointment_data['id_users_customer'],
143: 'id_services' => $appointment_data['id_services']
144: ));
145:
146: $result = $this->db->get('ea_appointments');
147:
148: if ($result->num_rows() == 0) {
149: throw new DatabaseException('Could not find appointment record id.');
150: }
151:
152: return $result->row()->id;
153: }
154:
155: /**
156: * Validate appointment data before the insert or update operations
157: * are executed.
158: *
159: * @param array $appointment_data Contains the appointment data.
160: * @return bool Returns the validation result.
161: */
162: public function validate_data($appointment_data) {
163: $this->load->helper('data_validation');
164:
165: try {
166: // If a appointment id is given, check wether the record exists
167: // in the database.
168: if (isset($appointment_data['id'])) {
169: $num_rows = $this->db->get_where('ea_appointments',
170: array('id' => $appointment_data['id']))->num_rows();
171: if ($num_rows == 0) {
172: throw new Exception('Provided appointment id does not '
173: . 'exist in the database.');
174: }
175: }
176:
177: // Check if appointment dates are valid.
178: if (!validate_mysql_datetime($appointment_data['start_datetime'])) {
179: throw new Exception('Appointment start datetime is invalid.');
180: }
181:
182: if (!validate_mysql_datetime($appointment_data['end_datetime'])) {
183: throw new Exception('Appointment end datetime is invalid.');
184: }
185:
186: // Check if the provider's id is valid.
187: $num_rows = $this->db
188: ->select('*')
189: ->from('ea_users')
190: ->join('ea_roles', 'ea_roles.id = ea_users.id_roles', 'inner')
191: ->where('ea_users.id', $appointment_data['id_users_provider'])
192: ->where('ea_roles.slug', DB_SLUG_PROVIDER)
193: ->get()->num_rows();
194: if ($num_rows == 0) {
195: throw new Exception('Appointment provider id is invalid.');
196: }
197:
198: // Check if the customer's id is valid.
199: $num_rows = $this->db
200: ->select('*')
201: ->from('ea_users')
202: ->join('ea_roles', 'ea_roles.id = ea_users.id_roles', 'inner')
203: ->where('ea_users.id', $appointment_data['id_users_customer'])
204: ->where('ea_roles.slug', DB_SLUG_CUSTOMER)
205: ->get()->num_rows();
206: if ($num_rows == 0) {
207: throw new Exception('Appointment customer id is invalid.');
208: }
209:
210: // Check if the service id is valid.
211: $num_rows = $this->db->get_where('ea_services',
212: array('id' => $appointment_data['id_services']))->num_rows();
213: if ($num_rows == 0) {
214: throw new Exception('Appointment customer id is invalid.');
215: }
216:
217: return TRUE;
218: } catch (Exception $exc) {
219: return FALSE;
220: }
221: }
222:
223: /**
224: * Delete an existing appointment record from the database.
225: *
226: * @expectedException InvalidArgumentException Raises when the $appointment_id
227: * is not an integer.
228: *
229: * @param int $appointment_id The record id to be deleted.
230: * @return bool Returns the delete operation result.
231: */
232: public function delete($appointment_id) {
233: if (!is_numeric($appointment_id)) {
234: throw new InvalidArgumentException('Invalid argument type $appointment_id : '
235: . $appointment_id);
236: }
237:
238: $num_rows = $this->db->get_where('ea_appointments',
239: array('id' => $appointment_id))->num_rows();
240:
241: if ($num_rows == 0) {
242: return FALSE; // Record does not exist.
243: }
244:
245: $this->db->where('id', $appointment_id);
246: return $this->db->delete('ea_appointments');
247: }
248:
249: /**
250: * Get a specific row from the appointments table.
251: *
252: * @param int $appointment_id The record's id to be returned.
253: * @return array Returns an associative array with the selected
254: * record's data. Each key has the same name as the database
255: * field names.
256: */
257: public function get_row($appointment_id) {
258: if (!is_numeric($appointment_id)) {
259: throw new InvalidArgumentException('Invalid argument given. Expected '
260: . 'integer for the $appointment_id : ' . $appointment_id);
261: }
262: return $this->db->get_where('ea_appointments',
263: array('id' => $appointment_id))->row_array();
264: }
265:
266: /**
267: * Get a specific field value from the database.
268: *
269: * @param string $field_name The field name of the value to be returned.
270: * @param int $appointment_id The selected record's id.
271: * @return string Returns the records value from the database.
272: */
273: public function get_value($field_name, $appointment_id) {
274: if (!is_numeric($appointment_id)) {
275: throw new InvalidArgumentException('Invalid argument given, expected '
276: . 'integer for the $appointment_id : ' . $appointment_id);
277: }
278:
279: if (!is_string($field_name)) {
280: throw new InvalidArgumentException('Invalid argument given, expected '
281: . 'string for the $field_name : ' . $field_name);
282: }
283:
284: if ($this->db->get_where('ea_appointments',
285: array('id' => $appointment_id))->num_rows() == 0) {
286: throw new InvalidArgumentException('The record with the provided id '
287: . 'does not exist in the database : ' . $appointment_id);
288: }
289:
290: $row_data = $this->db->get_where('ea_appointments',
291: array('id' => $appointment_id))->row_array();
292:
293: if (!isset($row_data[$field_name])) {
294: throw new InvalidArgumentException('The given field name does not '
295: . 'exist in the database : ' . $field_name);
296: }
297:
298: return $row_data[$field_name];
299: }
300:
301: /**
302: * Get all, or specific records from appointment's table.
303: *
304: * @example $this->Model->getBatch('id = ' . $recordId);
305: *
306: * @param string $where_clause (OPTIONAL) The WHERE clause of
307: * the query to be executed. DO NOT INCLUDE 'WHERE' KEYWORD.
308: * @return array Returns the rows from the database.
309: */
310: public function get_batch($where_clause = '') {
311: if ($where_clause != '') {
312: $this->db->where($where_clause);
313: }
314:
315: return $this->db->get('ea_appointments')->result_array();
316: }
317:
318: /**
319: * Generate a unique hash for the given appointment data.
320: *
321: * This method uses the current date-time to generate a unique
322: * hash string that is later used to identify this appointment.
323: * Hash is needed when the email is send to the user with an
324: * edit link.
325: *
326: * @return string Returns the unique appointment hash.
327: */
328: public function generate_hash() {
329: $current_date = new DateTime();
330: return md5($current_date->getTimestamp());
331: }
332: }
333:
334: /* End of file appointments_model.php */
335: /* Location: ./application/models/appointments_model.php */