diff --git a/CRM/Admin/Form/AdhocChargesItem.php b/CRM/Admin/Form/AdhocChargesItem.php index 6bf7122e..a51b21d2 100644 --- a/CRM/Admin/Form/AdhocChargesItem.php +++ b/CRM/Admin/Form/AdhocChargesItem.php @@ -1,5 +1,5 @@ $set) { $configSets[$key] = $set['title']; } - + $resource = civicrm_api3('Resource', 'getsingle', array( 'sequential' => 1, 'id' => $this->_id, )); } - catch (CiviCRM_API3_Exception $e) {} + catch (CiviCRM_API3_Exception $e) {} //allow state changes only when there is enabled config set if(!empty($resource['set_id']) && !in_array($resource['set_id'], array_keys($activeSets['values']))){ diff --git a/CRM/Admin/Form/ResourceConfigOption.php b/CRM/Admin/Form/ResourceConfigOption.php index 6c1ce72c..fc492057 100644 --- a/CRM/Admin/Form/ResourceConfigOption.php +++ b/CRM/Admin/Form/ResourceConfigOption.php @@ -1,5 +1,5 @@ add('text', 'title', E::ts('Title'), array('size' => 50, 'maxlength' => 255), TRUE); $this->add('text', 'weight', E::ts('Weight'), CRM_Core_DAO::getAttribute('CRM_Booking_DAO_ResourceConfigSet', 'weight'), TRUE); $statusCheckbox = $this->add('checkbox', 'is_active', E::ts('Enabled?')); - + //allow state changes and delete only when there are no enabled resources $resourceDao = new CRM_Booking_DAO_Resource(); $resourceDao->set_id = $this->_id; $resourceDao->is_deleted = FALSE; $resourceDao->is_active = TRUE; - + if($resourceDao->count() > 0){ $statusCheckbox->setAttribute('disabled', 'disabled'); } diff --git a/CRM/Booking/BAO/Query.php b/CRM/Booking/BAO/Query.php index acf12cf6..19163300 100644 --- a/CRM/Booking/BAO/Query.php +++ b/CRM/Booking/BAO/Query.php @@ -1,5 +1,5 @@ __table = 'civicrm_booking_adhoc_charges'; parent::__construct(); } + /** - * return foreign keys and entity references + * Returns foreign keys and entity references. * - * @static - * @access public - * @return array of CRM_Core_EntityReference + * @return array + * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() - { - if (!self::$_links) { - self::$_links = array( - new CRM_Core_EntityReference(self::getTableName() , 'booking_id', 'civicrm_booking', 'id') , - new CRM_Core_EntityReference(self::getTableName() , 'item_id', 'civicrm_booking_adhoc_charges_item', 'id') , - ); + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'booking_id', 'civicrm_booking', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'item_id', 'civicrm_booking_adhoc_charges_item', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } - return self::$_links; + return Civi::$statics[__CLASS__]['links']; } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - ) , - 'booking_id' => array( + 'required' => TRUE, + 'where' => 'civicrm_booking_adhoc_charges.id', + 'table_name' => 'civicrm_booking_adhoc_charges', + 'entity' => 'AdhocCharges', + 'bao' => 'CRM_Booking_DAO_AdhocCharges', + 'localizable' => 0, + ], + 'booking_id' => [ 'name' => 'booking_id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - 'FKClassName' => 'CRM_Booking_DAO_Booking', - ) , - 'item_id' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to Booking ID'), + 'required' => TRUE, + 'where' => 'civicrm_booking_adhoc_charges.booking_id', + 'table_name' => 'civicrm_booking_adhoc_charges', + 'entity' => 'AdhocCharges', + 'bao' => 'CRM_Booking_DAO_AdhocCharges', + 'localizable' => 0, + ], + 'item_id' => [ 'name' => 'item_id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - 'FKClassName' => 'CRM_Booking_DAO_AdhocChargesItem', - ) , - 'quantity' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to Item ID'), + 'required' => TRUE, + 'where' => 'civicrm_booking_adhoc_charges.item_id', + 'table_name' => 'civicrm_booking_adhoc_charges', + 'entity' => 'AdhocCharges', + 'bao' => 'CRM_Booking_DAO_AdhocCharges', + 'localizable' => 0, + ], + 'quantity' => [ 'name' => 'quantity', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Quantity') , - 'required' => true, - ) , - 'is_cancelled' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Quantity'), + 'required' => TRUE, + 'where' => 'civicrm_booking_adhoc_charges.quantity', + 'table_name' => 'civicrm_booking_adhoc_charges', + 'entity' => 'AdhocCharges', + 'bao' => 'CRM_Booking_DAO_AdhocCharges', + 'localizable' => 0, + ], + 'is_cancelled' => [ 'name' => 'is_cancelled', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is cancelled') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is cancelled'), + 'import' => TRUE, 'where' => 'civicrm_booking_adhoc_charges.is_cancelled', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'is_deleted' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_adhoc_charges', + 'entity' => 'AdhocCharges', + 'bao' => 'CRM_Booking_DAO_AdhocCharges', + 'localizable' => 0, + ], + 'is_deleted' => [ 'name' => 'is_deleted', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is in the Trash') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is in the Trash'), + 'import' => TRUE, 'where' => 'civicrm_booking_adhoc_charges.is_deleted', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - ); + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_adhoc_charges', + 'entity' => 'AdhocCharges', + 'bao' => 'CRM_Booking_DAO_AdhocCharges', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'booking_id' => 'booking_id', - 'item_id' => 'item_id', - 'quantity' => 'quantity', - 'is_cancelled' => 'is_cancelled', - 'is_deleted' => 'is_deleted', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + + /** + * Returns the list of fields that can be imported + * + * @param bool $prefix + * + * @return array + */ + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_adhoc_charges', $prefix, []); + return $r; + } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be exported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_adhoc_charges'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_adhoc_charges', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of indices + * + * @param bool $localize * - * @access public - * return array - * @static + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_adhoc_charges'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function indices($localize = TRUE) { + $indices = [ + 'index_is_cancelled' => [ + 'name' => 'index_is_cancelled', + 'field' => [ + 0 => 'is_cancelled', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_adhoc_charges::0::is_cancelled', + ], + 'index_is_deleted' => [ + 'name' => 'index_is_deleted', + 'field' => [ + 0 => 'is_deleted', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_adhoc_charges::0::is_deleted', + ], + ]; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/AdhocChargesItem.php b/CRM/Booking/DAO/AdhocChargesItem.php index 7f7873c3..fb5153bc 100644 --- a/CRM/Booking/DAO/AdhocChargesItem.php +++ b/CRM/Booking/DAO/AdhocChargesItem.php @@ -1,298 +1,261 @@ __table = 'civicrm_booking_adhoc_charges_item'; parent::__construct(); } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('ID') , - 'required' => true, - ) , - 'name' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('ID'), + 'required' => TRUE, + 'where' => 'civicrm_booking_adhoc_charges_item.id', + 'table_name' => 'civicrm_booking_adhoc_charges_item', + 'entity' => 'AdhocChargesItem', + 'bao' => 'CRM_Booking_DAO_AdhocChargesItem', + 'localizable' => 0, + ], + 'name' => [ 'name' => 'name', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Name') , - 'required' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Name'), + 'required' => TRUE, 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'label' => array( + 'where' => 'civicrm_booking_adhoc_charges_item.name', + 'table_name' => 'civicrm_booking_adhoc_charges_item', + 'entity' => 'AdhocChargesItem', + 'bao' => 'CRM_Booking_DAO_AdhocChargesItem', + 'localizable' => 0, + ], + 'label' => [ 'name' => 'label', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Label') , - 'required' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Label'), + 'required' => TRUE, 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'price' => array( + 'where' => 'civicrm_booking_adhoc_charges_item.label', + 'table_name' => 'civicrm_booking_adhoc_charges_item', + 'entity' => 'AdhocChargesItem', + 'bao' => 'CRM_Booking_DAO_AdhocChargesItem', + 'localizable' => 0, + ], + 'price' => [ 'name' => 'price', 'type' => CRM_Utils_Type::T_MONEY, - 'title' => E::ts('Price') , - 'required' => true, - ) , - 'weight' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Price'), + 'required' => TRUE, + 'precision' => [ + 20, + 2, + ], + 'where' => 'civicrm_booking_adhoc_charges_item.price', + 'table_name' => 'civicrm_booking_adhoc_charges_item', + 'entity' => 'AdhocChargesItem', + 'bao' => 'CRM_Booking_DAO_AdhocChargesItem', + 'localizable' => 0, + ], + 'weight' => [ 'name' => 'weight', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Weight') , - 'required' => true, - ) , - 'is_active' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Weight'), + 'required' => TRUE, + 'where' => 'civicrm_booking_adhoc_charges_item.weight', + 'table_name' => 'civicrm_booking_adhoc_charges_item', + 'entity' => 'AdhocChargesItem', + 'bao' => 'CRM_Booking_DAO_AdhocChargesItem', + 'localizable' => 0, + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is cancelled') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is cancelled'), + 'import' => TRUE, 'where' => 'civicrm_booking_adhoc_charges_item.is_active', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'default' => '1', - ) , - 'is_deleted' => array( + 'table_name' => 'civicrm_booking_adhoc_charges_item', + 'entity' => 'AdhocChargesItem', + 'bao' => 'CRM_Booking_DAO_AdhocChargesItem', + 'localizable' => 0, + ], + 'is_deleted' => [ 'name' => 'is_deleted', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is in the Trash') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is in the Trash'), + 'import' => TRUE, 'where' => 'civicrm_booking_adhoc_charges_item.is_deleted', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - ); + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_adhoc_charges_item', + 'entity' => 'AdhocChargesItem', + 'bao' => 'CRM_Booking_DAO_AdhocChargesItem', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'name' => 'name', - 'label' => 'label', - 'price' => 'price', - 'weight' => 'weight', - 'is_active' => 'is_active', - 'is_deleted' => 'is_deleted', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be imported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_adhoc_charges_item'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_adhoc_charges_item', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of fields that can be exported * - * @access public - * return array - * @static + * @param bool $prefix + * + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_adhoc_charges_item'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_adhoc_charges_item', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = [ + 'index_is_active' => [ + 'name' => 'index_is_active', + 'field' => [ + 0 => 'is_active', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_adhoc_charges_item::0::is_active', + ], + 'index_is_deleted' => [ + 'name' => 'index_is_deleted', + 'field' => [ + 0 => 'is_deleted', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_adhoc_charges_item::0::is_deleted', + ], + ]; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/Booking.php b/CRM/Booking/DAO/Booking.php index 28aa1408..3fcb8962 100644 --- a/CRM/Booking/DAO/Booking.php +++ b/CRM/Booking/DAO/Booking.php @@ -1,525 +1,526 @@ __table = 'civicrm_booking'; parent::__construct(); } + /** - * return foreign keys and entity references + * Returns foreign keys and entity references. * - * @static - * @access public - * @return array of CRM_Core_EntityReference - */ - static function getReferenceColumns() - { - if (!self::$_links) { - self::$_links = array( - new CRM_Core_EntityReference(self::getTableName() , 'primary_contact_id', 'civicrm_contact', 'id') , - new CRM_Core_EntityReference(self::getTableName() , 'secondary_contact_id', 'civicrm_contact', 'id') , - ); + * @return array + * [CRM_Core_Reference_Interface] + */ + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'primary_contact_id', 'civicrm_contact', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'secondary_contact_id', 'civicrm_contact', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } - return self::$_links; + return Civi::$statics[__CLASS__]['links']; } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - ) , - 'primary_contact_id' => array( + 'required' => TRUE, + 'where' => 'civicrm_booking.id', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'primary_contact_id' => [ 'name' => 'primary_contact_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Primary Contact ID') , - 'required' => true, - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Primary Contact ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('FK to Contact ID'), + 'required' => TRUE, + 'import' => TRUE, 'where' => 'civicrm_booking.primary_contact_id', 'headerPattern' => '/contact(.?id)?/i', 'dataPattern' => '/^\d+$/', - 'export' => true, - 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'secondary_contact_id' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'secondary_contact_id' => [ 'name' => 'secondary_contact_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Secondary Contact ID') , - 'required' => false, - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Secondary Contact ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('FK to Contact ID'), + 'required' => FALSE, + 'import' => TRUE, 'where' => 'civicrm_booking.secondary_contact_id', 'headerPattern' => '/contact(.?id)?/i', 'dataPattern' => '/^\d+$/', - 'export' => true, - 'FKClassName' => 'CRM_Contact_DAO_Contact', - ) , - 'booking_title' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'booking_title' => [ 'name' => 'title', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Title') , - 'required' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Title'), + 'required' => TRUE, 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - 'export' => true, 'where' => 'civicrm_booking.title', - 'headerPattern' => '', - 'dataPattern' => '', - ) , - 'booking_status_id' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'booking_status_id' => [ 'name' => 'status_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Status ID') , - 'required' => true, - 'export' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Status ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('The status associated with this booking. Implicit FK to option_value row in booking status option_group.'), + 'required' => TRUE, 'where' => 'civicrm_booking.status_id', - 'headerPattern' => '', - 'dataPattern' => '', - 'pseudoconstant' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + 'pseudoconstant' => [ 'optionGroupName' => 'booking_status', - ) - ) , - 'booking_date' => array( + 'optionEditPath' => 'civicrm/admin/options/booking_status', + ], + ], + 'booking_date' => [ 'name' => 'booking_date', 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => E::ts('Booking Date') , - 'required' => true, - 'export' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Booking Date'), + 'required' => TRUE, 'where' => 'civicrm_booking.booking_date', - 'headerPattern' => '', - 'dataPattern' => '', - ) , - 'booking_start_date' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'booking_start_date' => [ 'name' => 'start_date', 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => E::ts('Start Date') , - 'required' => true, - 'export' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Start Date'), + 'required' => TRUE, 'where' => 'civicrm_booking.start_date', - 'headerPattern' => '', - 'dataPattern' => '', - ) , - 'booking_end_date' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'booking_end_date' => [ 'name' => 'end_date', 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => E::ts('End Date') , - 'required' => true, - 'export' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('End Date'), + 'required' => TRUE, 'where' => 'civicrm_booking.end_date', - 'headerPattern' => '', - 'dataPattern' => '', - ) , - 'booking_po_number' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'booking_po_number' => [ 'name' => 'po_number', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('PO Number') , - 'required' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('PO Number'), + 'required' => TRUE, 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - 'export' => true, 'where' => 'civicrm_booking.po_number', - 'headerPattern' => '', - 'dataPattern' => '', - ) , - 'booking_total_amount' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'total_amount' => [ 'name' => 'total_amount', 'type' => CRM_Utils_Type::T_MONEY, - 'title' => E::ts('Total amount') , - 'required' => true, - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Total amount'), + 'description' => CRM_Booking_ExtensionUtil::ts('Total amount of this booking calculated from slots,sub slots, ad-hoc charges and discount amount'), + 'required' => TRUE, + 'precision' => [ + 20, + 2, + ], + 'import' => TRUE, 'where' => 'civicrm_booking.total_amount', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'description' => array( + 'export' => TRUE, + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'description' => [ 'name' => 'description', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Description') , + 'title' => CRM_Booking_ExtensionUtil::ts('Description'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'note' => array( + 'where' => 'civicrm_booking.description', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'note' => [ 'name' => 'note', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => E::ts('Note') , - ) , - 'adhoc_charges_note' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Note'), + 'where' => 'civicrm_booking.note', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'adhoc_charges_note' => [ 'name' => 'adhoc_charges_note', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => E::ts('Adhoc Charges Note') , - ) , - 'participants_estimate' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Adhoc Charges Note'), + 'where' => 'civicrm_booking.adhoc_charges_note', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'participants_estimate' => [ 'name' => 'participants_estimate', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Participants Estimate') , + 'title' => CRM_Booking_ExtensionUtil::ts('Participants Estimate'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'participants_actual' => array( + 'where' => 'civicrm_booking.participants_estimate', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'participants_actual' => [ 'name' => 'participants_actual', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Participants Actual') , + 'title' => CRM_Booking_ExtensionUtil::ts('Participants Actual'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'discount_amount' => array( + 'where' => 'civicrm_booking.participants_actual', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'discount_amount' => [ 'name' => 'discount_amount', 'type' => CRM_Utils_Type::T_MONEY, - 'title' => E::ts('Discount Amount') , - ) , - 'booking_is_deleted' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Discount Amount'), + 'precision' => [ + 20, + 2, + ], + 'where' => 'civicrm_booking.discount_amount', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'booking_is_deleted' => [ 'name' => 'is_deleted', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Booking is in the Trash') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Booking is in the Trash'), + 'import' => TRUE, 'where' => 'civicrm_booking.is_deleted', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'created_by' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'created_by' => [ 'name' => 'created_by', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Created By') , - 'required' => true, - ) , - 'created_date' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Created By'), + 'required' => TRUE, + 'where' => 'civicrm_booking.created_by', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'created_date' => [ 'name' => 'created_date', 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => E::ts('Created Date') , - 'required' => true, - ) , - 'updated_by' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Created Date'), + 'required' => TRUE, + 'where' => 'civicrm_booking.created_date', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'updated_by' => [ 'name' => 'updated_by', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Updated By') , - 'required' => true, - ) , - 'updated_date' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Updated By'), + 'required' => TRUE, + 'where' => 'civicrm_booking.updated_by', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + 'updated_date' => [ 'name' => 'updated_date', 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => E::ts('Updated Date') , - 'required' => true, - ) , - ); + 'title' => CRM_Booking_ExtensionUtil::ts('Updated Date'), + 'required' => TRUE, + 'where' => 'civicrm_booking.updated_date', + 'table_name' => 'civicrm_booking', + 'entity' => 'Booking', + 'bao' => 'CRM_Booking_DAO_Booking', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'primary_contact_id' => 'primary_contact_id', - 'secondary_contact_id' => 'secondary_contact_id', - 'title' => 'booking_title', - 'status_id' => 'booking_status_id', - 'booking_date' => 'booking_date', - 'start_date' => 'booking_start_date', - 'end_date' => 'booking_end_date', - 'po_number' => 'booking_po_number', - 'total_amount' => 'total_amount', - 'description' => 'description', - 'note' => 'note', - 'adhoc_charges_note' => 'adhoc_charges_note', - 'participants_estimate' => 'participants_estimate', - 'participants_actual' => 'participants_actual', - 'discount_amount' => 'discount_amount', - 'is_deleted' => 'booking_is_deleted', - 'created_by' => 'created_by', - 'created_date' => 'created_date', - 'updated_by' => 'updated_by', - 'updated_date' => 'updated_date', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be imported * - * @access public - * return array - * @static - */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + * @param bool $prefix + * + * @return array + */ + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of fields that can be exported * - * @access public - * return array - * @static - */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + * @param bool $prefix + * + * @return array + */ + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = [ + 'index_is_deleted' => [ + 'name' => 'index_is_deleted', + 'field' => [ + 0 => 'is_deleted', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking::0::is_deleted', + ], + ]; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/BookingConfig.php b/CRM/Booking/DAO/BookingConfig.php index bb3e1e94..33ef40cd 100644 --- a/CRM/Booking/DAO/BookingConfig.php +++ b/CRM/Booking/DAO/BookingConfig.php @@ -1,375 +1,356 @@ __table = 'civicrm_booking_config'; parent::__construct(); } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - ) , - 'domain_id' => array( + 'required' => TRUE, + 'where' => 'civicrm_booking_config.id', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'domain_id' => [ 'name' => 'domain_id', 'type' => CRM_Utils_Type::T_INT, - ) , - 'day_start_at' => array( + 'where' => 'civicrm_booking_config.domain_id', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'day_start_at' => [ 'name' => 'day_start_at', 'type' => CRM_Utils_Type::T_TIME, - 'title' => E::ts('Day Start At') , - 'required' => true, - ) , - 'day_end_at' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Day Start At'), + 'required' => TRUE, + 'where' => 'civicrm_booking_config.day_start_at', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'day_end_at' => [ 'name' => 'day_end_at', 'type' => CRM_Utils_Type::T_TIME, - 'title' => E::ts('Day End At') , - 'required' => true, - ) , - 'time_period' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Day End At'), + 'required' => TRUE, + 'where' => 'civicrm_booking_config.day_end_at', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'time_period' => [ 'name' => 'time_period', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Time Period') , - 'required' => true, - ) , - 'log_confirmation_email' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Time Period'), + 'required' => TRUE, + 'where' => 'civicrm_booking_config.time_period', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'log_confirmation_email' => [ 'name' => 'log_confirmation_email', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Log Confirmation Email') , - 'required' => true, - ) , - 'unlimited_resource_time_config' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Log Confirmation Email'), + 'description' => CRM_Booking_ExtensionUtil::ts('Create an activity record againt contact for conformation emails'), + 'required' => TRUE, + 'where' => 'civicrm_booking_config.log_confirmation_email', + 'default' => '0', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'unlimited_resource_time_config' => [ 'name' => 'unlimited_resource_time_config', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Unlimited Resource Time Config') , - 'required' => true, - ) , - 'cc_email_address' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Unlimited Resource Time Config'), + 'description' => CRM_Booking_ExtensionUtil::ts('Only allow unlimited resources to be booked within time span of the parent limited resource booking'), + 'required' => TRUE, + 'where' => 'civicrm_booking_config.unlimited_resource_time_config', + 'default' => '1', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'cc_email_address' => [ 'name' => 'cc_email_address', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Cc Email Address') , + 'title' => CRM_Booking_ExtensionUtil::ts('Cc Email Address'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'bcc_email_address' => array( + 'where' => 'civicrm_booking_config.cc_email_address', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'bcc_email_address' => [ 'name' => 'bcc_email_address', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Bcc Email Address') , + 'title' => CRM_Booking_ExtensionUtil::ts('Bcc Email Address'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'slot_new_colour' => array( + 'where' => 'civicrm_booking_config.bcc_email_address', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'slot_new_colour' => [ 'name' => 'slot_new_colour', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Slot New Colour') , + 'title' => CRM_Booking_ExtensionUtil::ts('Slot New Colour'), 'maxlength' => 10, 'size' => CRM_Utils_Type::TWELVE, - ) , - 'slot_being_edited_colour' => array( + 'where' => 'civicrm_booking_config.slot_new_colour', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'slot_being_edited_colour' => [ 'name' => 'slot_being_edited_colour', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Slot Being Edited Colour') , + 'title' => CRM_Booking_ExtensionUtil::ts('Slot Being Edited Colour'), 'maxlength' => 10, 'size' => CRM_Utils_Type::TWELVE, - ) , - 'slot_booked_colour' => array( + 'where' => 'civicrm_booking_config.slot_being_edited_colour', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'slot_booked_colour' => [ 'name' => 'slot_booked_colour', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Slot Booked Colour') , + 'title' => CRM_Booking_ExtensionUtil::ts('Slot Booked Colour'), 'maxlength' => 10, 'size' => CRM_Utils_Type::TWELVE, - ) , - 'slot_provisional_colour' => array( + 'where' => 'civicrm_booking_config.slot_booked_colour', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'slot_provisional_colour' => [ 'name' => 'slot_provisional_colour', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Slot Provisional Colour') , + 'title' => CRM_Booking_ExtensionUtil::ts('Slot Provisional Colour'), 'maxlength' => 10, 'size' => CRM_Utils_Type::TWELVE, - ) , - 'slot_unavailable_colour' => array( + 'where' => 'civicrm_booking_config.slot_provisional_colour', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + 'slot_unavailable_colour' => [ 'name' => 'slot_unavailable_colour', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Slot Unavailable Colour') , + 'title' => CRM_Booking_ExtensionUtil::ts('Slot Unavailable Colour'), 'maxlength' => 10, 'size' => CRM_Utils_Type::TWELVE, - ) , - ); + 'where' => 'civicrm_booking_config.slot_unavailable_colour', + 'table_name' => 'civicrm_booking_config', + 'entity' => 'BookingConfig', + 'bao' => 'CRM_Booking_DAO_BookingConfig', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'domain_id' => 'domain_id', - 'day_start_at' => 'day_start_at', - 'day_end_at' => 'day_end_at', - 'time_period' => 'time_period', - 'log_confirmation_email' => 'log_confirmation_email', - 'unlimited_resource_time_config' => 'unlimited_resource_time_config', - 'cc_email_address' => 'cc_email_address', - 'bcc_email_address' => 'bcc_email_address', - 'slot_new_colour' => 'slot_new_colour', - 'slot_being_edited_colour' => 'slot_being_edited_colour', - 'slot_booked_colour' => 'slot_booked_colour', - 'slot_provisional_colour' => 'slot_provisional_colour', - 'slot_unavailable_colour' => 'slot_unavailable_colour', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be imported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_config'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_config', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of fields that can be exported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_config'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_config', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = []; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/Cancellation.php b/CRM/Booking/DAO/Cancellation.php index ca6c2e34..d0f54221 100644 --- a/CRM/Booking/DAO/Cancellation.php +++ b/CRM/Booking/DAO/Cancellation.php @@ -1,286 +1,237 @@ __table = 'civicrm_booking_cancellation'; parent::__construct(); } + /** - * return foreign keys and entity references + * Returns foreign keys and entity references. * - * @static - * @access public - * @return array of CRM_Core_EntityReference + * @return array + * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() - { - if (!self::$_links) { - self::$_links = array( - new CRM_Core_EntityReference(self::getTableName() , 'booking_id', 'civicrm_booking', 'id') , - ); + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'booking_id', 'civicrm_booking', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } - return self::$_links; + return Civi::$statics[__CLASS__]['links']; } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - ) , - 'booking_id' => array( + 'required' => TRUE, + 'where' => 'civicrm_booking_cancellation.id', + 'table_name' => 'civicrm_booking_cancellation', + 'entity' => 'Cancellation', + 'bao' => 'CRM_Booking_DAO_Cancellation', + 'localizable' => 0, + ], + 'booking_id' => [ 'name' => 'booking_id', 'type' => CRM_Utils_Type::T_INT, - 'FKClassName' => 'CRM_Booking_DAO_Booking', - ) , - 'cancellation_date' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to Booking'), + 'where' => 'civicrm_booking_cancellation.booking_id', + 'table_name' => 'civicrm_booking_cancellation', + 'entity' => 'Cancellation', + 'bao' => 'CRM_Booking_DAO_Cancellation', + 'localizable' => 0, + ], + 'cancellation_date' => [ 'name' => 'cancellation_date', 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => E::ts('Cancellation Date') , - 'required' => true, - ) , - 'cancellation_fee' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Cancellation Date'), + 'required' => TRUE, + 'where' => 'civicrm_booking_cancellation.cancellation_date', + 'table_name' => 'civicrm_booking_cancellation', + 'entity' => 'Cancellation', + 'bao' => 'CRM_Booking_DAO_Cancellation', + 'localizable' => 0, + ], + 'cancellation_fee' => [ 'name' => 'cancellation_fee', 'type' => CRM_Utils_Type::T_MONEY, - 'title' => E::ts('Cancellation charge') , - 'required' => true, - ) , - 'additional_fee' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Cancellation charge'), + 'required' => TRUE, + 'precision' => [ + 20, + 2, + ], + 'where' => 'civicrm_booking_cancellation.cancellation_fee', + 'table_name' => 'civicrm_booking_cancellation', + 'entity' => 'Cancellation', + 'bao' => 'CRM_Booking_DAO_Cancellation', + 'localizable' => 0, + ], + 'additional_fee' => [ 'name' => 'additional_fee', 'type' => CRM_Utils_Type::T_MONEY, - 'title' => E::ts('Additional charge') , - ) , - 'comment' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Additional charge'), + 'precision' => [ + 20, + 2, + ], + 'where' => 'civicrm_booking_cancellation.additional_fee', + 'table_name' => 'civicrm_booking_cancellation', + 'entity' => 'Cancellation', + 'bao' => 'CRM_Booking_DAO_Cancellation', + 'localizable' => 0, + ], + 'comment' => [ 'name' => 'comment', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => E::ts('Comment') , - ) , - ); + 'title' => CRM_Booking_ExtensionUtil::ts('Comment'), + 'where' => 'civicrm_booking_cancellation.comment', + 'table_name' => 'civicrm_booking_cancellation', + 'entity' => 'Cancellation', + 'bao' => 'CRM_Booking_DAO_Cancellation', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'booking_id' => 'booking_id', - 'cancellation_date' => 'cancellation_date', - 'cancellation_fee' => 'cancellation_fee', - 'additional_fee' => 'additional_fee', - 'comment' => 'comment', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be imported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_cancellation'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_cancellation', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of fields that can be exported * - * @access public - * return array - * @static + * @param bool $prefix + * + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_cancellation'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_cancellation', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = []; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/Payment.php b/CRM/Booking/DAO/Payment.php index 9faa5388..ac387cd9 100644 --- a/CRM/Booking/DAO/Payment.php +++ b/CRM/Booking/DAO/Payment.php @@ -1,263 +1,192 @@ __table = 'civicrm_booking_payment'; parent::__construct(); } + /** - * return foreign keys and entity references + * Returns foreign keys and entity references. * - * @static - * @access public - * @return array of CRM_Core_EntityReference - */ - static function getReferenceColumns() - { - if (!self::$_links) { - self::$_links = array( - new CRM_Core_EntityReference(self::getTableName() , 'booking_id', 'civicrm_booking', 'id') , - new CRM_Core_EntityReference(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id') , - ); + * @return array + * [CRM_Core_Reference_Interface] + */ + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'booking_id', 'civicrm_booking', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_id', 'civicrm_contribution', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } - return self::$_links; + return Civi::$statics[__CLASS__]['links']; } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('ID') , - 'required' => true, - ) , - 'booking_id' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('ID'), + 'required' => TRUE, + 'where' => 'civicrm_booking_payment.id', + 'table_name' => 'civicrm_booking_payment', + 'entity' => 'Payment', + 'bao' => 'CRM_Booking_DAO_Payment', + 'localizable' => 0, + ], + 'booking_id' => [ 'name' => 'booking_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Booking ID') , - 'required' => true, - 'FKClassName' => 'CRM_Booking_DAO_Booking', - ) , - 'contribution_id' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Booking ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('Foreign key to the booking id for this payment.'), + 'required' => TRUE, + 'where' => 'civicrm_booking_payment.booking_id', + 'table_name' => 'civicrm_booking_payment', + 'entity' => 'Payment', + 'bao' => 'CRM_Booking_DAO_Payment', + 'localizable' => 0, + ], + 'contribution_id' => [ 'name' => 'contribution_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Contribution ID') , - 'required' => true, - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Contribution ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('Foreign key to the contribution for this payment.'), + 'required' => TRUE, + 'import' => TRUE, 'where' => 'civicrm_booking_payment.contribution_id', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - 'FKClassName' => 'CRM_Contribute_DAO_Contribution', - ) , - ); + 'export' => TRUE, + 'table_name' => 'civicrm_booking_payment', + 'entity' => 'Payment', + 'bao' => 'CRM_Booking_DAO_Payment', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'booking_id' => 'booking_id', - 'contribution_id' => 'contribution_id', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be imported * - * @access public - * return array - * @static + * @param bool $prefix + * + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_payment'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_payment', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of fields that can be exported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_payment'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_payment', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = []; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/Resource.php b/CRM/Booking/DAO/Resource.php index d321d79a..c8a6da2d 100644 --- a/CRM/Booking/DAO/Resource.php +++ b/CRM/Booking/DAO/Resource.php @@ -1,358 +1,344 @@ __table = 'civicrm_booking_resource'; parent::__construct(); } + /** - * return foreign keys and entity references + * Returns foreign keys and entity references. * - * @static - * @access public - * @return array of CRM_Core_EntityReference + * @return array + * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() - { - if (!self::$_links) { - self::$_links = array( - new CRM_Core_EntityReference(self::getTableName() , 'set_id', 'civicrm_booking_resource_config_set', 'id') , - ); + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'set_id', 'civicrm_booking_resource_config_set', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } - return self::$_links; + return Civi::$statics[__CLASS__]['links']; } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - ) , - 'set_id' => array( + 'required' => TRUE, + 'where' => 'civicrm_booking_resource.id', + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + ], + 'set_id' => [ 'name' => 'set_id', 'type' => CRM_Utils_Type::T_INT, - 'FKClassName' => 'CRM_Booking_DAO_ResourceConfigSet', - ) , - 'booking_resource_label' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to resource configuration option set'), + 'where' => 'civicrm_booking_resource.set_id', + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + ], + 'booking_resource_label' => [ 'name' => 'label', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Label') , - 'required' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Label'), + 'required' => TRUE, 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'booking_resource_description' => array( + 'where' => 'civicrm_booking_resource.label', + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + ], + 'booking_resource_description' => [ 'name' => 'description', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Label') , + 'title' => CRM_Booking_ExtensionUtil::ts('Label'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'type_id' => array( + 'where' => 'civicrm_booking_resource.description', + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + ], + 'type_id' => [ 'name' => 'type_id', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Type ID') , - 'required' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Type ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('The type associated with this resource. Implicit FK to option_value row in booking_resource_type option_group.'), + 'required' => TRUE, 'maxlength' => 512, 'size' => CRM_Utils_Type::HUGE, - 'pseudoconstant' => array( + 'where' => 'civicrm_booking_resource.type_id', + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + 'pseudoconstant' => [ 'optionGroupName' => 'booking_resource_type', - ) - ) , - 'location_id' => array( + 'optionEditPath' => 'civicrm/admin/options/booking_resource_type', + ], + ], + 'location_id' => [ 'name' => 'location_id', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Location ID') , + 'title' => CRM_Booking_ExtensionUtil::ts('Location ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('The location associated with this resource. Implicit FK to option_value row in booking_resource_location option_group.'), 'maxlength' => 512, 'size' => CRM_Utils_Type::HUGE, - 'pseudoconstant' => array( + 'where' => 'civicrm_booking_resource.location_id', + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + 'pseudoconstant' => [ 'optionGroupName' => 'booking_resource_location', - ) - ) , - 'weight' => array( + 'optionEditPath' => 'civicrm/admin/options/booking_resource_location', + ], + ], + 'weight' => [ 'name' => 'weight', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Weight') , - 'required' => true, - ) , - 'is_unlimited' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Weight'), + 'required' => TRUE, + 'where' => 'civicrm_booking_resource.weight', + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + ], + 'is_unlimited' => [ 'name' => 'is_unlimited', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'required' => true, - ) , - 'is_active' => array( + 'required' => TRUE, + 'where' => 'civicrm_booking_resource.is_unlimited', + 'default' => '0', + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is cancelled') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is cancelled'), + 'import' => TRUE, 'where' => 'civicrm_booking_resource.is_active', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'default' => '1', - ) , - 'is_deleted' => array( + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + ], + 'is_deleted' => [ 'name' => 'is_deleted', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is in the Trash') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is in the Trash'), + 'import' => TRUE, 'where' => 'civicrm_booking_resource.is_deleted', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - ); + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_resource', + 'entity' => 'Resource', + 'bao' => 'CRM_Booking_DAO_Resource', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'set_id' => 'set_id', - 'label' => 'booking_resource_label', - 'description' => 'booking_resource_description', - 'type_id' => 'type_id', - 'location_id' => 'location_id', - 'weight' => 'weight', - 'is_unlimited' => 'is_unlimited', - 'is_active' => 'is_active', - 'is_deleted' => 'is_deleted', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be imported * - * @access public - * return array - * @static + * @param bool $prefix + * + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_resource'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_resource', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of fields that can be exported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_resource'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_resource', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = [ + 'index_is_unlimited' => [ + 'name' => 'index_is_unlimited', + 'field' => [ + 0 => 'is_unlimited', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_resource::0::is_unlimited', + ], + 'index_is_active' => [ + 'name' => 'index_is_active', + 'field' => [ + 0 => 'is_active', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_resource::0::is_active', + ], + 'index_is_deleted' => [ + 'name' => 'index_is_deleted', + 'field' => [ + 0 => 'is_deleted', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_resource::0::is_deleted', + ], + ]; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/ResourceConfigOption.php b/CRM/Booking/DAO/ResourceConfigOption.php index 305b3148..4a695f51 100644 --- a/CRM/Booking/DAO/ResourceConfigOption.php +++ b/CRM/Booking/DAO/ResourceConfigOption.php @@ -1,344 +1,318 @@ __table = 'civicrm_booking_resource_config_option'; parent::__construct(); } + /** - * return foreign keys and entity references + * Returns foreign keys and entity references. * - * @static - * @access public - * @return array of CRM_Core_EntityReference + * @return array + * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() - { - if (!self::$_links) { - self::$_links = array( - new CRM_Core_EntityReference(self::getTableName() , 'set_id', 'civicrm_booking_resource_config_set', 'id') , - ); + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'set_id', 'civicrm_booking_resource_config_set', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } - return self::$_links; + return Civi::$statics[__CLASS__]['links']; } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('ID') , - 'required' => true, - ) , - 'set_id' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('ID'), + 'required' => TRUE, + 'where' => 'civicrm_booking_resource_config_option.id', + 'table_name' => 'civicrm_booking_resource_config_option', + 'entity' => 'ResourceConfigOption', + 'bao' => 'CRM_Booking_DAO_ResourceConfigOption', + 'localizable' => 0, + ], + 'set_id' => [ 'name' => 'set_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Set ID') , - 'required' => true, - 'FKClassName' => 'CRM_Booking_DAO_ResourceConfigSet', - ) , - 'label' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Set ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('Foreign key to the resource set for this option.'), + 'required' => TRUE, + 'where' => 'civicrm_booking_resource_config_option.set_id', + 'table_name' => 'civicrm_booking_resource_config_option', + 'entity' => 'ResourceConfigOption', + 'bao' => 'CRM_Booking_DAO_ResourceConfigOption', + 'localizable' => 0, + ], + 'label' => [ 'name' => 'label', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Label') , - 'required' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Label'), + 'required' => TRUE, 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'price' => array( + 'where' => 'civicrm_booking_resource_config_option.label', + 'table_name' => 'civicrm_booking_resource_config_option', + 'entity' => 'ResourceConfigOption', + 'bao' => 'CRM_Booking_DAO_ResourceConfigOption', + 'localizable' => 0, + ], + 'price' => [ 'name' => 'price', 'type' => CRM_Utils_Type::T_MONEY, - 'title' => E::ts('Price') , - 'required' => true, - ) , - 'max_size' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Price'), + 'required' => TRUE, + 'precision' => [ + 20, + 2, + ], + 'where' => 'civicrm_booking_resource_config_option.price', + 'table_name' => 'civicrm_booking_resource_config_option', + 'entity' => 'ResourceConfigOption', + 'bao' => 'CRM_Booking_DAO_ResourceConfigOption', + 'localizable' => 0, + ], + 'max_size' => [ 'name' => 'max_size', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Max Size') , + 'title' => CRM_Booking_ExtensionUtil::ts('Max Size'), 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'unit_id' => array( + 'where' => 'civicrm_booking_resource_config_option.max_size', + 'table_name' => 'civicrm_booking_resource_config_option', + 'entity' => 'ResourceConfigOption', + 'bao' => 'CRM_Booking_DAO_ResourceConfigOption', + 'localizable' => 0, + ], + 'unit_id' => [ 'name' => 'unit_id', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Unit ID') , + 'title' => CRM_Booking_ExtensionUtil::ts('Unit ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('The unit associated with this config option. Implicit FK to option_value row in booking_size_unit option_group.'), 'maxlength' => 512, 'size' => CRM_Utils_Type::HUGE, - 'pseudoconstant' => array( + 'where' => 'civicrm_booking_resource_config_option.unit_id', + 'table_name' => 'civicrm_booking_resource_config_option', + 'entity' => 'ResourceConfigOption', + 'bao' => 'CRM_Booking_DAO_ResourceConfigOption', + 'localizable' => 0, + 'pseudoconstant' => [ 'optionGroupName' => 'booking_size_unit', - ) - ) , - 'weight' => array( + 'optionEditPath' => 'civicrm/admin/options/booking_size_unit', + ], + ], + 'weight' => [ 'name' => 'weight', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Weight') , - 'required' => true, - ) , - 'is_active' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Weight'), + 'required' => TRUE, + 'where' => 'civicrm_booking_resource_config_option.weight', + 'table_name' => 'civicrm_booking_resource_config_option', + 'entity' => 'ResourceConfigOption', + 'bao' => 'CRM_Booking_DAO_ResourceConfigOption', + 'localizable' => 0, + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is cancelled') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is cancelled'), + 'import' => TRUE, 'where' => 'civicrm_booking_resource_config_option.is_active', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'default' => '1', - ) , - 'is_deleted' => array( + 'table_name' => 'civicrm_booking_resource_config_option', + 'entity' => 'ResourceConfigOption', + 'bao' => 'CRM_Booking_DAO_ResourceConfigOption', + 'localizable' => 0, + ], + 'is_deleted' => [ 'name' => 'is_deleted', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is in the Trash') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is in the Trash'), + 'import' => TRUE, 'where' => 'civicrm_booking_resource_config_option.is_deleted', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - ); + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_resource_config_option', + 'entity' => 'ResourceConfigOption', + 'bao' => 'CRM_Booking_DAO_ResourceConfigOption', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'set_id' => 'set_id', - 'label' => 'label', - 'price' => 'price', - 'max_size' => 'max_size', - 'unit_id' => 'unit_id', - 'weight' => 'weight', - 'is_active' => 'is_active', - 'is_deleted' => 'is_deleted', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + + /** + * Returns the list of fields that can be imported + * + * @param bool $prefix + * + * @return array + */ + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_resource_config_option', $prefix, []); + return $r; + } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be exported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_resource_config_option'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_resource_config_option', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of indices + * + * @param bool $localize * - * @access public - * return array - * @static + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_resource_config_option'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function indices($localize = TRUE) { + $indices = [ + 'index_is_active' => [ + 'name' => 'index_is_active', + 'field' => [ + 0 => 'is_active', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_resource_config_option::0::is_active', + ], + 'index_is_deleted' => [ + 'name' => 'index_is_deleted', + 'field' => [ + 0 => 'is_deleted', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_resource_config_option::0::is_deleted', + ], + ]; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/ResourceConfigSet.php b/CRM/Booking/DAO/ResourceConfigSet.php index 1816e176..5bd23729 100644 --- a/CRM/Booking/DAO/ResourceConfigSet.php +++ b/CRM/Booking/DAO/ResourceConfigSet.php @@ -1,272 +1,223 @@ __table = 'civicrm_booking_resource_config_set'; parent::__construct(); } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('ID') , - 'required' => true, - ) , - 'title' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('ID'), + 'required' => TRUE, + 'where' => 'civicrm_booking_resource_config_set.id', + 'table_name' => 'civicrm_booking_resource_config_set', + 'entity' => 'ResourceConfigSet', + 'bao' => 'CRM_Booking_DAO_ResourceConfigSet', + 'localizable' => 0, + ], + 'title' => [ 'name' => 'title', 'type' => CRM_Utils_Type::T_STRING, - 'title' => E::ts('Title') , - 'required' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Title'), + 'required' => TRUE, 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, - ) , - 'weight' => array( + 'where' => 'civicrm_booking_resource_config_set.title', + 'table_name' => 'civicrm_booking_resource_config_set', + 'entity' => 'ResourceConfigSet', + 'bao' => 'CRM_Booking_DAO_ResourceConfigSet', + 'localizable' => 0, + ], + 'weight' => [ 'name' => 'weight', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Weight') , - 'required' => true, - ) , - 'is_active' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Weight'), + 'required' => TRUE, + 'where' => 'civicrm_booking_resource_config_set.weight', + 'table_name' => 'civicrm_booking_resource_config_set', + 'entity' => 'ResourceConfigSet', + 'bao' => 'CRM_Booking_DAO_ResourceConfigSet', + 'localizable' => 0, + ], + 'is_active' => [ 'name' => 'is_active', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is cancelled') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is cancelled'), + 'import' => TRUE, 'where' => 'civicrm_booking_resource_config_set.is_active', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, + 'export' => TRUE, 'default' => '1', - ) , - 'is_deleted' => array( + 'table_name' => 'civicrm_booking_resource_config_set', + 'entity' => 'ResourceConfigSet', + 'bao' => 'CRM_Booking_DAO_ResourceConfigSet', + 'localizable' => 0, + ], + 'is_deleted' => [ 'name' => 'is_deleted', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is in the Trash') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is in the Trash'), + 'import' => TRUE, 'where' => 'civicrm_booking_resource_config_set.is_deleted', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - ); + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_resource_config_set', + 'entity' => 'ResourceConfigSet', + 'bao' => 'CRM_Booking_DAO_ResourceConfigSet', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'title' => 'title', - 'weight' => 'weight', - 'is_active' => 'is_active', - 'is_deleted' => 'is_deleted', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be imported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_resource_config_set'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_resource_config_set', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of fields that can be exported * - * @access public - * return array - * @static + * @param bool $prefix + * + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_resource_config_set'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_resource_config_set', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = [ + 'index_is_active' => [ + 'name' => 'index_is_active', + 'field' => [ + 0 => 'is_active', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_resource_config_set::0::is_active', + ], + 'index_is_deleted' => [ + 'name' => 'index_is_deleted', + 'field' => [ + 0 => 'is_deleted', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_resource_config_set::0::is_deleted', + ], + ]; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/ResourceCriteria.php b/CRM/Booking/DAO/ResourceCriteria.php index 76473a85..5682c845 100644 --- a/CRM/Booking/DAO/ResourceCriteria.php +++ b/CRM/Booking/DAO/ResourceCriteria.php @@ -1,257 +1,190 @@ __table = 'civicrm_booking_resource_criteria'; parent::__construct(); } + /** - * return foreign keys and entity references + * Returns foreign keys and entity references. * - * @static - * @access public - * @return array of CRM_Core_EntityReference + * @return array + * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() - { - if (!self::$_links) { - self::$_links = array( - new CRM_Core_EntityReference(self::getTableName() , 'resource_id', 'civicrm_booking_resource', 'id') , - ); + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'resource_id', 'civicrm_booking_resource', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } - return self::$_links; + return Civi::$statics[__CLASS__]['links']; } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('ID') , - 'required' => true, - ) , - 'resource_id' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('ID'), + 'required' => TRUE, + 'where' => 'civicrm_booking_resource_criteria.id', + 'table_name' => 'civicrm_booking_resource_criteria', + 'entity' => 'ResourceCriteria', + 'bao' => 'CRM_Booking_DAO_ResourceCriteria', + 'localizable' => 0, + ], + 'resource_id' => [ 'name' => 'resource_id', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Resource ID') , - 'required' => true, - 'FKClassName' => 'CRM_Booking_DAO_Resource', - ) , - 'criteria_id' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Resource ID'), + 'description' => CRM_Booking_ExtensionUtil::ts('Foreign key to the resoure for this resource criteria.'), + 'required' => TRUE, + 'where' => 'civicrm_booking_resource_criteria.resource_id', + 'table_name' => 'civicrm_booking_resource_criteria', + 'entity' => 'ResourceCriteria', + 'bao' => 'CRM_Booking_DAO_ResourceCriteria', + 'localizable' => 0, + ], + 'criteria_id' => [ 'name' => 'criteria_id', 'type' => CRM_Utils_Type::T_STRING, - 'required' => true, + 'description' => CRM_Booking_ExtensionUtil::ts('Foreign key to the resource criteria option group.'), + 'required' => TRUE, 'maxlength' => 512, 'size' => CRM_Utils_Type::HUGE, - ) , - ); + 'where' => 'civicrm_booking_resource_criteria.criteria_id', + 'table_name' => 'civicrm_booking_resource_criteria', + 'entity' => 'ResourceCriteria', + 'bao' => 'CRM_Booking_DAO_ResourceCriteria', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'resource_id' => 'resource_id', - 'criteria_id' => 'criteria_id', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be imported * - * @access public - * return array - * @static + * @param bool $prefix + * + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_resource_criteria'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_resource_criteria', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of fields that can be exported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_resource_criteria'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_resource_criteria', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = []; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/Slot.php b/CRM/Booking/DAO/Slot.php index 2e390566..e08eae97 100644 --- a/CRM/Booking/DAO/Slot.php +++ b/CRM/Booking/DAO/Slot.php @@ -1,347 +1,321 @@ __table = 'civicrm_booking_slot'; parent::__construct(); } + /** - * return foreign keys and entity references + * Returns foreign keys and entity references. * - * @static - * @access public - * @return array of CRM_Core_EntityReference + * @return array + * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() - { - if (!self::$_links) { - self::$_links = array( - new CRM_Core_EntityReference(self::getTableName() , 'booking_id', 'civicrm_booking', 'id') , - new CRM_Core_EntityReference(self::getTableName() , 'resource_id', 'civicrm_booking_resource', 'id') , - new CRM_Core_EntityReference(self::getTableName() , 'config_id', 'civicrm_booking_resource_config_option', 'id') , - ); + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'booking_id', 'civicrm_booking', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'resource_id', 'civicrm_booking_resource', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'config_id', 'civicrm_booking_resource_config_option', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } - return self::$_links; + return Civi::$statics[__CLASS__]['links']; } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - ) , - 'booking_id' => array( + 'required' => TRUE, + 'where' => 'civicrm_booking_slot.id', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + 'booking_id' => [ 'name' => 'booking_id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - 'FKClassName' => 'CRM_Booking_DAO_Booking', - ) , - 'resource_id' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to Booking ID'), + 'required' => TRUE, + 'where' => 'civicrm_booking_slot.booking_id', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + 'resource_id' => [ 'name' => 'resource_id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - 'FKClassName' => 'CRM_Booking_DAO_Resource', - ) , - 'config_id' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to resource ID'), + 'required' => TRUE, + 'where' => 'civicrm_booking_slot.resource_id', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + 'config_id' => [ 'name' => 'config_id', 'type' => CRM_Utils_Type::T_INT, - 'FKClassName' => 'CRM_Booking_DAO_ResourceConfigOption', - ) , - 'start' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to resource configuration option ID'), + 'where' => 'civicrm_booking_slot.config_id', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + 'start' => [ 'name' => 'start', 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => E::ts('Start') , - 'required' => true, - ) , - 'end' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Start'), + 'required' => TRUE, + 'where' => 'civicrm_booking_slot.start', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + 'end' => [ 'name' => 'end', 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => E::ts('End') , - 'required' => true, - ) , - 'quantity' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('End'), + 'required' => TRUE, + 'where' => 'civicrm_booking_slot.end', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + 'quantity' => [ 'name' => 'quantity', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Quantity') , - 'required' => true, - ) , - 'note' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Quantity'), + 'required' => TRUE, + 'where' => 'civicrm_booking_slot.quantity', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + 'note' => [ 'name' => 'note', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => E::ts('Note') , - ) , - 'is_cancelled' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Note'), + 'where' => 'civicrm_booking_slot.note', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + 'is_cancelled' => [ 'name' => 'is_cancelled', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is cancelled') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is cancelled'), + 'import' => TRUE, 'where' => 'civicrm_booking_slot.is_cancelled', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'is_deleted' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + 'is_deleted' => [ 'name' => 'is_deleted', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('Slot is in the Trash') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('Slot is in the Trash'), + 'import' => TRUE, 'where' => 'civicrm_booking_slot.is_deleted', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - ); + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_slot', + 'entity' => 'Slot', + 'bao' => 'CRM_Booking_DAO_Slot', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'booking_id' => 'booking_id', - 'resource_id' => 'resource_id', - 'config_id' => 'config_id', - 'start' => 'start', - 'end' => 'end', - 'quantity' => 'quantity', - 'note' => 'note', - 'is_cancelled' => 'is_cancelled', - 'is_deleted' => 'is_deleted', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + + /** + * Returns the list of fields that can be imported + * + * @param bool $prefix + * + * @return array + */ + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_slot', $prefix, []); + return $r; + } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be exported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_slot'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_slot', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of indices + * + * @param bool $localize * - * @access public - * return array - * @static + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_slot'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function indices($localize = TRUE) { + $indices = [ + 'index_is_cancelled' => [ + 'name' => 'index_is_cancelled', + 'field' => [ + 0 => 'is_cancelled', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_slot::0::is_cancelled', + ], + 'index_is_deleted' => [ + 'name' => 'index_is_deleted', + 'field' => [ + 0 => 'is_deleted', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_slot::0::is_deleted', + ], + ]; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/DAO/SubSlot.php b/CRM/Booking/DAO/SubSlot.php index 6612e059..5249c9e2 100644 --- a/CRM/Booking/DAO/SubSlot.php +++ b/CRM/Booking/DAO/SubSlot.php @@ -1,333 +1,303 @@ __table = 'civicrm_booking_sub_slot'; parent::__construct(); } + /** - * return foreign keys and entity references + * Returns foreign keys and entity references. * - * @static - * @access public - * @return array of CRM_Core_EntityReference + * @return array + * [CRM_Core_Reference_Interface] */ - static function getReferenceColumns() - { - if (!self::$_links) { - self::$_links = array( - new CRM_Core_EntityReference(self::getTableName() , 'slot_id', 'civicrm_booking_slot', 'id') , - new CRM_Core_EntityReference(self::getTableName() , 'resource_id', 'civicrm_booking_resource', 'id') , - new CRM_Core_EntityReference(self::getTableName() , 'config_id', 'civicrm_booking_resource_config_option', 'id') , - ); + public static function getReferenceColumns() { + if (!isset(Civi::$statics[__CLASS__]['links'])) { + Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'slot_id', 'civicrm_booking_slot', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'resource_id', 'civicrm_booking_resource', 'id'); + Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'config_id', 'civicrm_booking_resource_config_option', 'id'); + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']); } - return self::$_links; + return Civi::$statics[__CLASS__]['links']; } + /** - * returns all the column names of this table + * Returns all the column names of this table * - * @access public * @return array */ - static function &fields() - { - if (!(self::$_fields)) { - self::$_fields = array( - 'id' => array( + public static function &fields() { + if (!isset(Civi::$statics[__CLASS__]['fields'])) { + Civi::$statics[__CLASS__]['fields'] = [ + 'id' => [ 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, - 'required' => true, - ) , - 'slot_id' => array( + 'required' => TRUE, + 'where' => 'civicrm_booking_sub_slot.id', + 'table_name' => 'civicrm_booking_sub_slot', + 'entity' => 'SubSlot', + 'bao' => 'CRM_Booking_DAO_SubSlot', + 'localizable' => 0, + ], + 'slot_id' => [ 'name' => 'slot_id', 'type' => CRM_Utils_Type::T_INT, - 'FKClassName' => 'CRM_Booking_DAO_Slot', - ) , - 'resource_id' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to Slot ID'), + 'where' => 'civicrm_booking_sub_slot.slot_id', + 'table_name' => 'civicrm_booking_sub_slot', + 'entity' => 'SubSlot', + 'bao' => 'CRM_Booking_DAO_SubSlot', + 'localizable' => 0, + ], + 'resource_id' => [ 'name' => 'resource_id', 'type' => CRM_Utils_Type::T_INT, - 'FKClassName' => 'CRM_Booking_DAO_Resource', - ) , - 'config_id' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to resource ID'), + 'where' => 'civicrm_booking_sub_slot.resource_id', + 'table_name' => 'civicrm_booking_sub_slot', + 'entity' => 'SubSlot', + 'bao' => 'CRM_Booking_DAO_SubSlot', + 'localizable' => 0, + ], + 'config_id' => [ 'name' => 'config_id', 'type' => CRM_Utils_Type::T_INT, - 'FKClassName' => 'CRM_Booking_DAO_ResourceConfigOption', - ) , - 'time_required' => array( + 'description' => CRM_Booking_ExtensionUtil::ts('FK to resource configuration option ID'), + 'where' => 'civicrm_booking_sub_slot.config_id', + 'table_name' => 'civicrm_booking_sub_slot', + 'entity' => 'SubSlot', + 'bao' => 'CRM_Booking_DAO_SubSlot', + 'localizable' => 0, + ], + 'time_required' => [ 'name' => 'time_required', 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME, - 'title' => E::ts('Time Required') , - 'required' => true, - ) , - 'quantity' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Time Required'), + 'required' => TRUE, + 'where' => 'civicrm_booking_sub_slot.time_required', + 'table_name' => 'civicrm_booking_sub_slot', + 'entity' => 'SubSlot', + 'bao' => 'CRM_Booking_DAO_SubSlot', + 'localizable' => 0, + ], + 'quantity' => [ 'name' => 'quantity', 'type' => CRM_Utils_Type::T_INT, - 'title' => E::ts('Quantity') , - 'required' => true, - ) , - 'note' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Quantity'), + 'required' => TRUE, + 'where' => 'civicrm_booking_sub_slot.quantity', + 'table_name' => 'civicrm_booking_sub_slot', + 'entity' => 'SubSlot', + 'bao' => 'CRM_Booking_DAO_SubSlot', + 'localizable' => 0, + ], + 'note' => [ 'name' => 'note', 'type' => CRM_Utils_Type::T_TEXT, - 'title' => E::ts('Note') , - ) , - 'is_cancelled' => array( + 'title' => CRM_Booking_ExtensionUtil::ts('Note'), + 'where' => 'civicrm_booking_sub_slot.note', + 'table_name' => 'civicrm_booking_sub_slot', + 'entity' => 'SubSlot', + 'bao' => 'CRM_Booking_DAO_SubSlot', + 'localizable' => 0, + ], + 'is_cancelled' => [ 'name' => 'is_cancelled', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('SubSlot is cancelled') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('SubSlot is cancelled'), + 'import' => TRUE, 'where' => 'civicrm_booking_sub_slot.is_cancelled', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - 'is_deleted' => array( + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_sub_slot', + 'entity' => 'SubSlot', + 'bao' => 'CRM_Booking_DAO_SubSlot', + 'localizable' => 0, + ], + 'is_deleted' => [ 'name' => 'is_deleted', 'type' => CRM_Utils_Type::T_BOOLEAN, - 'title' => E::ts('SubSlot is in the Trash') , - 'import' => true, + 'title' => CRM_Booking_ExtensionUtil::ts('SubSlot is in the Trash'), + 'import' => TRUE, 'where' => 'civicrm_booking_sub_slot.is_deleted', - 'headerPattern' => '', - 'dataPattern' => '', - 'export' => true, - ) , - ); + 'export' => TRUE, + 'default' => '0', + 'table_name' => 'civicrm_booking_sub_slot', + 'entity' => 'SubSlot', + 'bao' => 'CRM_Booking_DAO_SubSlot', + 'localizable' => 0, + ], + ]; + CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']); } - return self::$_fields; + return Civi::$statics[__CLASS__]['fields']; } + /** - * Returns an array containing, for each field, the arary key used for that - * field in self::$_fields. + * Return a mapping from field-name to the corresponding key (as used in fields()). * - * @access public * @return array + * Array(string $name => string $uniqueName). */ - static function &fieldKeys() - { - if (!(self::$_fieldKeys)) { - self::$_fieldKeys = array( - 'id' => 'id', - 'slot_id' => 'slot_id', - 'resource_id' => 'resource_id', - 'config_id' => 'config_id', - 'time_required' => 'time_required', - 'quantity' => 'quantity', - 'note' => 'note', - 'is_cancelled' => 'is_cancelled', - 'is_deleted' => 'is_deleted', - ); + public static function &fieldKeys() { + if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) { + Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields())); } - return self::$_fieldKeys; + return Civi::$statics[__CLASS__]['fieldKeys']; } + /** - * returns the names of this table + * Returns the names of this table * - * @access public - * @static * @return string */ - static function getTableName() - { + public static function getTableName() { return self::$_tableName; } + /** - * returns if this table needs to be logged + * Returns if this table needs to be logged * - * @access public - * @return boolean + * @return bool */ - function getLog() - { + public function getLog() { return self::$_log; } + /** - * returns the list of fields that can be imported + * Returns the list of fields that can be imported * - * @access public - * return array - * @static + * @param bool $prefix + * + * @return array */ - static function &import($prefix = false) - { - if (!(self::$_import)) { - self::$_import = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('import', $field)) { - if ($prefix) { - self::$_import['booking_sub_slot'] = & $fields[$name]; - } else { - self::$_import[$name] = & $fields[$name]; - } - } - } - } - return self::$_import; + public static function &import($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'booking_sub_slot', $prefix, []); + return $r; } + /** - * returns the list of fields that can be exported + * Returns the list of fields that can be exported + * + * @param bool $prefix * - * @access public - * return array - * @static + * @return array */ - static function &export($prefix = false) - { - if (!(self::$_export)) { - self::$_export = array(); - $fields = self::fields(); - foreach($fields as $name => $field) { - if (CRM_Utils_Array::value('export', $field)) { - if ($prefix) { - self::$_export['booking_sub_slot'] = & $fields[$name]; - } else { - self::$_export[$name] = & $fields[$name]; - } - } - } - } - return self::$_export; + public static function &export($prefix = FALSE) { + $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'booking_sub_slot', $prefix, []); + return $r; + } + + /** + * Returns the list of indices + * + * @param bool $localize + * + * @return array + */ + public static function indices($localize = TRUE) { + $indices = [ + 'index_is_cancelled' => [ + 'name' => 'index_is_cancelled', + 'field' => [ + 0 => 'is_cancelled', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_sub_slot::0::is_cancelled', + ], + 'index_is_deleted' => [ + 'name' => 'index_is_deleted', + 'field' => [ + 0 => 'is_deleted', + ], + 'localizable' => FALSE, + 'sig' => 'civicrm_booking_sub_slot::0::is_deleted', + ], + ]; + return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices; } + } diff --git a/CRM/Booking/Form/AddSubResource.php b/CRM/Booking/Form/AddSubResource.php index 8043072b..5c0e6656 100644 --- a/CRM/Booking/Form/AddSubResource.php +++ b/CRM/Booking/Form/AddSubResource.php @@ -1,21 +1,17 @@ _id = $this->get('id'); $config = CRM_Core_Config::singleton(); - $currencySymbols = ""; - if(!empty($config->currencySymbols)){ + if (!empty($config->currencySymbols)) { $currencySymbols = $config->currencySymbols; - }else{ + } + else { $currencySymbols = $config->defaultCurrencySymbol; } $this->assign('currencySymbols', $currencySymbols); - + $this->assign('currency', \Civi::settings()->get('defaultCurrency')); + //Control the flexibility of time configuration for unlimited resource $bookingConfig = CRM_Booking_BAO_BookingConfig::getConfig(); $this->assign('timeconfig', CRM_Utils_Array::value('unlimited_resource_time_config', $bookingConfig)); $selectResourcePage = $this->controller->exportValues('SelectResource'); - $selectedResources = json_decode($selectResourcePage['resources'], true); + $selectedResources = json_decode($selectResourcePage['resources'], true) ?? []; $this->assign('resources', $selectedResources); foreach ($selectedResources as $key => $resource) { @@ -54,42 +50,37 @@ function preProcess(){ } $this->_total = $this->_subTotal; - require_once 'CRM/Booking/Utils/DateTime.php'; $this->assign('timeOptions', CRM_Booking_Utils_DateTime::getTimeRange()); // get all custom groups sorted by weight - $items = array(); + $items = []; $bao = new CRM_Booking_BAO_AdhocChargesItem(); $bao->orderBy('weight'); $bao->is_active = 1; $bao->is_deleted = 0; $bao->find(); while ($bao->fetch()) { - $items[$bao->id] = array(); + $items[$bao->id] = []; CRM_Core_DAO::storeValues($bao, $items[$bao->id]); $items[$bao->id]['name'] = preg_replace('/[^\p{L}\p{N}\s]/u', '_', $items[$bao->id]['name']); } - //$days = CRM_Booking_Utils_DateTime::getDays(); - //$months = CRM_Utils_Date::getFullMonthNames(); - //$years = CRM_Booking_Utils_DateTime::getYears(); - - $this->assign('items', $items); - + $baoUnlimResource = new CRM_Booking_BAO_Resource(); $baoUnlimResource->is_active = 1; $baoUnlimResource->is_deleted = 0; $baoUnlimResource->is_unlimited = 1; $unlimitedResourceCount = $baoUnlimResource->count(); - + $this->assign('unlimited_resource_count', $unlimitedResourceCount); - - if($this->_id && $this->_action == CRM_Core_Action::UPDATE){ + + if ($this->_id && $this->_action == CRM_Core_Action::UPDATE) { $title = CRM_Core_DAO::getFieldValue('CRM_Booking_BAO_Booking', $this->_id, 'title', 'id'); CRM_Utils_System::setTitle(E::ts('Edit Booking') . " - $title"); - }else{ - CRM_Utils_System::setTitle(E::ts('New Booking') ); + } + else { + CRM_Utils_System::setTitle(E::ts('New Booking')); } /** @@ -103,50 +94,46 @@ function preProcess(){ $this->assign('dateFormat', $this->crmDateFormat); self::registerScripts(); - } - /** + /** * This function sets the default values for the form. * - * @access public - * - * @return None + * @return array */ - function setDefaultValues() { - $defaults = array( ); - if($this->_id){ - $result = civicrm_api3('Booking', 'get', array('id' => $this->_id)); + public function setDefaultValues() { + $defaults = []; + if ($this->_id) { + $result = civicrm_api3('Booking', 'get', ['id' => $this->_id]); $booking = $result['values'][$result['id']]; - $subResources['sub_resources'] = array(); + $subResources['sub_resources'] = []; $subResources['resources'] = $this->_resourcesPrice; - $slots = civicrm_api3('Slot', 'get', array('booking_id' => $this->_id, 'is_deleted' => 0)); + $slots = civicrm_api3('Slot', 'get', ['booking_id' => $this->_id, 'is_deleted' => 0]); $unitPriceList = CRM_Booking_BAO_ResourceConfigOption::buildOptions('unit_id', 'create'); foreach ($slots['values'] as $key => $slot) { - $subSlots = civicrm_api3('SubSlot', 'get', array('slot_id' => $slot['id'], 'is_deleted' => 0)); + $subSlots = civicrm_api3('SubSlot', 'get', ['slot_id' => $slot['id'], 'is_deleted' => 0]); foreach ($subSlots['values'] as $subSlot) { - $subResources['sub_resources'][$subSlot['id']] = array( + $subResources['sub_resources'][$subSlot['id']] = [ "parent_ref_id" => $slot['id'], "ref_id" => $subSlot['id'], "quantity" => CRM_Utils_Array::value('quantity', $subSlot), - "time_required" => "2013-10-21 09:50", "time_required" => CRM_Utils_Array::value('time_required', $subSlot), "note" => CRM_Utils_Array::value('note', $subSlot), - ); - $resourceResult = civicrm_api3('Resource', 'get', array('id' => $subSlot['resource_id'])); + ]; + $resourceResult = civicrm_api3('Resource', 'get', ['id' => $subSlot['resource_id']]); $resource = $resourceResult['values'][$subSlot['resource_id']]; - $subResources['sub_resources'][$subSlot['id']]['resource'] = array( + $subResources['sub_resources'][$subSlot['id']]['resource'] = [ "id" => $resource['id'], "label" => $resource['label'] - ); - $configOptionResult = civicrm_api3('ResourceConfigOption', 'get', array('id' => $subSlot['config_id'])); + ]; + $configOptionResult = civicrm_api3('ResourceConfigOption', 'get', ['id' => $subSlot['config_id']]); $configOption = $configOptionResult['values'][$subSlot['config_id']]; $unit = $unitPriceList[$configOption['unit_id']]; - $subResources['sub_resources'][$subSlot['id']]['configuration'] = array( + $subResources['sub_resources'][$subSlot['id']]['configuration'] = [ "id" => $configOption['id'], "label" => $configOption['label'] . ' - ' . $configOption['price'] . ' / ' . $unit, "price" => $configOption['price'], - ); + ]; $priceEstimate = $configOption['price'] * CRM_Utils_Array::value('quantity', $subSlot); $subResources['sub_resources'][$subSlot['id']]['price_estimate'] = $priceEstimate; $resourceTotalPrice = $subResources['resources'][$slot['id']] + $priceEstimate; @@ -157,31 +144,30 @@ function setDefaultValues() { foreach ($subResources['resources'] as $price) { $subTotal += $price; } - $addhocCharges = array("items" => array(), "note" => CRM_Utils_Array::value('adhoc_charges_note', $booking), "total" => 0); - $addhocChargesResult = civicrm_api3('AdhocCharges', 'get', array('booking_id' => $this->_id, 'is_deleted' => 0)); + $addhocCharges = ["items" => [], "note" => CRM_Utils_Array::value('adhoc_charges_note', $booking), "total" => 0]; + $addhocChargesResult = civicrm_api3('AdhocCharges', 'get', ['booking_id' => $this->_id, 'is_deleted' => 0]); foreach ($addhocChargesResult['values'] as $key => $charge) { - $itemResult = civicrm_api3('AdhocChargesItem', 'get', array('id' => $charge['item_id'], 'is_deleted' => 0)); - if(empty($itemResult['values'])){ //make sure we do not process deleted item + $itemResult = civicrm_api3('AdhocChargesItem', 'get', ['id' => $charge['item_id'], 'is_deleted' => 0]); + if (empty($itemResult['values'])) { //make sure we do not process deleted item continue; } $item = $itemResult['values'][$charge['item_id']]; $totalPrice = $item['price'] * $charge['quantity']; - $addhocCharges['items'][$charge['item_id']] = array( + $addhocCharges['items'][$charge['item_id']] = [ "item_id" => $charge['item_id'], "name" => $item['name'], "price" => $totalPrice, "quantity" => $charge['quantity'], "item_price" => $item['price'] - ); + ]; $addhocCharges['total'] += $totalPrice; } - - + $defaults['sub_total'] = $subTotal; $defaults['adhoc_charge'] = $addhocCharges['total']; $defaults['discount_amount']= CRM_Utils_Array::value('discount_amount', $booking); $defaults['discount_amount_dummy']= CRM_Utils_Array::value('discount_amount', $booking); - + $subResources['sub_total'] = $subTotal; $subResources['adhoc_charges'] = $addhocCharges; $total = ($subTotal - $defaults['discount_amount']) + $addhocCharges['total']; @@ -189,7 +175,8 @@ function setDefaultValues() { // force JSON to encode empty array as object if there is empty array in $subResources $defaults['sub_resources'] = json_encode($subResources,JSON_FORCE_OBJECT); $defaults['total_price'] = $total; - }else{ + } + else { $defaults['sub_total'] = $this->_subTotal; $defaults['adhoc_charge'] = 0; $defaults['discount_amount']= 0; @@ -198,79 +185,80 @@ function setDefaultValues() { return $defaults; } - function buildQuickForm() { + public function buildQuickForm() { parent::buildQuickForm(); $this->addElement('text', - 'sub_total', - E::ts('Sub total')); + 'sub_total', + E::ts('Sub total')); $this->addElement('text', - 'total_price', - E::ts('Total')); + 'total_price', + E::ts('Total')); $this->addElement('text', - 'discount_amount', - E::ts('Discount amount')); + 'discount_amount', + E::ts('Discount amount')); //for discount amount calculation $this->addElement('text', - 'discount_amount_dummy', - E::ts('Discount amount')); + 'discount_amount_dummy', + E::ts('Discount amount')); $this->addElement('text', - 'adhoc_charge', - E::ts('Ad-hoc charges')); + 'adhoc_charge', + E::ts('Ad-hoc charges')); $this->add('textarea', - 'sub_resources', - E::ts('Unlimited Resource(s)'), - FALSE); + 'sub_resources', + E::ts('Unlimited Resource(s)'), + FALSE); - $buttons = array( - array('type' => 'back', + $buttons = [ + [ + 'type' => 'back', 'name' => E::ts('<< Previous'), - ), - array( + ], + [ 'type' => 'next', 'name' => E::ts('Next >>'), 'spacing' => '                 ', 'isDefault' => TRUE, - ), - ); + ], + ]; $this->addButtons($buttons); - + $this->addRule("discount_amount_dummy", E::ts('Please enter a valid amount.'), 'money'); - - $this->addFormRule( array( 'CRM_Booking_Form_AddSubResource', 'formRule' ), $this ); + + $this->addFormRule( ['CRM_Booking_Form_AddSubResource', 'formRule'], $this ); } - + //set the validation rule for the discount field - static function formRule($params, $files, $context) - { + public static function formRule($params, $files, $context) { $values = $context->exportValues(); + empty($values['discount_amount']) ? $values['discount_amount'] = 0 : NULL; + empty($values['sub_total']) ? $values['sub_total'] = 0 : NULL; $numValidate = is_numeric($values['discount_amount']); - $emptyValidate = $values['discount_amount']==''; $finalSubtotal = $values['sub_total'] + $values['adhoc_charge']; - $rangeValidate = $values['discount_amount']>=0 && $values['discount_amount']<=$finalSubtotal; - if(!$numValidate && !$emptyValidate){ - return array('discount_amount' => 'Please enter a valid number.'); - }elseif(!$rangeValidate){ - return array('discount_amount' => 'Please enter a number in the valid range.'); - }else{ + $rangeValidate = ($values['discount_amount'] >= 0) && ($values['discount_amount'] <= $finalSubtotal); + if (!$numValidate) { + return ['discount_amount' => 'Please enter a valid number.']; + } + elseif (!$rangeValidate) { + return ['discount_amount' => 'Please enter a number in the valid range.']; + } + else { return TRUE; } } - function postProcess() { - $values = $this->exportValues(); - + public function postProcess() { parent::postProcess(); } - static function registerScripts() { + public static function registerScripts() { static $loaded = FALSE; if ($loaded) { return; @@ -279,33 +267,32 @@ static function registerScripts() { CRM_Core_Resources::singleton() - ->addStyleFile('uk.co.compucorp.civicrm.booking', 'css/booking.css', 92, 'page-header') - + ->addStyleFile(E::LONG_NAME, 'css/booking.css', 92, 'page-header') + ->addScriptFile('civicrm', 'packages/backbone/json2.js', 100, 'html-header', FALSE) - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'packages/underscore.js', 110, 'html-header', FALSE) + ->addScriptFile(E::LONG_NAME, 'packages/underscore.js', 110, 'html-header', FALSE) ->addScriptFile('civicrm', 'packages/backbone/backbone.js', 120, 'html-header') ->addScriptFile('civicrm', 'packages/backbone/backbone.marionette.js', 125, 'html-header', FALSE) ->addScriptFile('civicrm', 'packages/backbone/backbone.modelbinder.js', 125, 'html-header', FALSE) ->addScriptFile('civicrm', 'js/crm.backbone.js', 130, 'html-header', FALSE) - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'js/vendor/moment.min.js', 120, 'html-header', FALSE) + ->addScriptFile(E::LONG_NAME, 'js/vendor/moment.min.js', 120, 'html-header', FALSE) - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'js/booking/civicrm-moment-strftime.js', 140, 'html-header', FALSE) - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'js/booking/add-sub-resource/app.js', 150, 'html-header') - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'js/booking/common/views.js', 151, 'html-header', FALSE) - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'js/booking/utils.js', 151, 'html-header', FALSE) - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'js/booking/add-sub-resource/entities.js', 160, 'html-header') - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'js/booking/add-sub-resource/view.js', 170, 'html-header'); + ->addScriptFile(E::LONG_NAME, 'js/booking/civicrm-moment-strftime.js', 140, 'html-header', FALSE) + ->addScriptFile(E::LONG_NAME, 'js/booking/add-sub-resource/app.js', 150, 'html-header') + ->addScriptFile(E::LONG_NAME, 'js/booking/common/views.js', 151, 'html-header', FALSE) + ->addScriptFile(E::LONG_NAME, 'js/booking/utils.js', 151, 'html-header', FALSE) + ->addScriptFile(E::LONG_NAME, 'js/booking/add-sub-resource/entities.js', 160, 'html-header') + ->addScriptFile(E::LONG_NAME, 'js/booking/add-sub-resource/view.js', 170, 'html-header'); - $templateDir = CRM_Extension_System::singleton()->getMapper()->keyToBasePath('uk.co.compucorp.civicrm.booking') . '/templates/'; + $templateDir = CRM_Extension_System::singleton()->getMapper()->keyToBasePath(E::LONG_NAME) . '/templates/'; $region = CRM_Core_Region::instance('page-header'); foreach (glob($templateDir . 'CRM/Booking/tpl/add-sub-resource/*.tpl') as $file) { $fileName = substr($file, strlen($templateDir)); - $region->add(array( + $region->add([ 'template' => $fileName, - )); + ]); } - $region->add(array('template' => 'CRM/Booking/tpl/select-option.tpl' )); - + $region->add(['template' => 'CRM/Booking/tpl/select-option.tpl']); } } diff --git a/CRM/Booking/Form/Booking/Base.php b/CRM/Booking/Form/Booking/Base.php index 8b23a28e..1e0ede1f 100644 --- a/CRM/Booking/Form/Booking/Base.php +++ b/CRM/Booking/Form/Booking/Base.php @@ -1,38 +1,5 @@ addRule("total_amount", E::ts('Please enter a valid amount.'), 'money'); - + $this->add('select', 'financial_type_id', E::ts('Financial Type'), array('' => E::ts('- select -')) + CRM_Contribute_PseudoConstant::financialType() @@ -234,7 +201,7 @@ public function buildQuickForm() { ); $this->add('text', 'check_number', E::ts('Check Number')); - + $this->add('text', 'trxn_id', E::ts('Transaction ID')); $this->add('select', 'contribution_status_id', @@ -395,7 +362,7 @@ function postProcess(){ } $sendConfirmation = CRM_Utils_Array::value('send_confirmation', $bookingInfo); - if($sendConfirmation){ //check sending email parameter + if ($sendConfirmation) { //check sending email parameter $values = array(); $fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address'); $values['from_email_address'] = CRM_Utils_Array::value(CRM_Utils_Array::value('from_email_address', $bookingInfo), $fromEmailAddress); diff --git a/CRM/Booking/Form/Booking/Info.php b/CRM/Booking/Form/Booking/Info.php index 61a7f7ed..e3de301f 100644 --- a/CRM/Booking/Form/Booking/Info.php +++ b/CRM/Booking/Form/Booking/Info.php @@ -1,15 +1,36 @@ 'id-source', 'file' => 'CRM/Contact/Form/Contact']] + * - template - use a field specific template to render this field + * - required + * @var array + */ + protected $entityFields = []; + + /** + * Explicitly declare the entity api name. + */ + public function getDefaultEntity() { + return 'Booking'; + } + /** * Return a descriptive name for the page, used in wizard header * @@ -20,49 +41,48 @@ public function getTitle() { return E::ts('Booking Information'); } - - function preProcess(){ + public function preProcess() { $this->_id = $this->get('id'); - if($this->_id && $this->_action == CRM_Core_Action::UPDATE){ + if ($this->_id && $this->_action == CRM_Core_Action::UPDATE) { parent::preProcess(); } - if($this->_id && $this->_action == CRM_Core_Action::UPDATE){ + if ($this->_id && $this->_action == CRM_Core_Action::UPDATE) { $title = CRM_Core_DAO::getFieldValue('CRM_Booking_BAO_Booking', $this->_id, 'title', 'id'); CRM_Utils_System::setTitle(E::ts('Edit Booking') . " - $title"); - }else{ - CRM_Utils_System::setTitle(E::ts('New Booking') ); + } + else { + CRM_Utils_System::setTitle(E::ts('New Booking')); } self::registerScripts(); } - function buildQuickForm() { + public function buildQuickForm() { + self::buildQuickEntityForm(); parent::buildQuickForm(); - $this->addEntityRef("primary_contact_id", E::ts('Primary contact'), array('create' => TRUE), TRUE ); - - $this->addEntityRef("secondary_contact_id", E::ts('Secondary contact'), array('create' => TRUE)); - + $this->addEntityRef("primary_contact_id", E::ts('Primary contact'), ['create' => TRUE], TRUE ); + $this->addEntityRef("secondary_contact_id", E::ts('Secondary contact'), ['create' => TRUE]); $this->add('text', 'po_no', E::ts('Purchase order number')); $bookingStatus = CRM_Booking_BAO_Booking::buildOptions('status_id', 'create'); $result = civicrm_api3( 'OptionValue', 'get', - array( + [ 'option_group_name' => CRM_Booking_Utils_Constants::OPTION_BOOKING_STATUS, 'name' => CRM_Booking_Utils_Constants::OPTION_VALUE_CANCELLED, - ) + ] ); $this->_cancelStatusId = CRM_Utils_Array::value('value', CRM_Utils_Array::value($result['id'], $result['values'])); unset($bookingStatus[$this->_cancelStatusId]); $this->add('select', 'booking_status', E::ts('Booking status'), - array('' => E::ts('- select -')) + $bookingStatus, + ['' => E::ts('- select -')] + $bookingStatus, TRUE, - array() + [] ); - $this->add('text', 'title', E::ts('Title'), array('size' => 50, 'maxlength' => 255), TRUE); - $this->addDate('event_start_date', E::ts('Date booking made'), TRUE, array('formatType' => 'activityDateTime')); + $this->add('text', 'title', E::ts('Title'), ['size' => 50, 'maxlength' => 255], TRUE); + $this->add('datepicker', 'event_start_date', E::ts('Date booking made'), ['formatType' => 'activityDateTime'], TRUE); $this->add('textarea', 'description', E::ts('Description')); $this->add('textarea', 'note', E::ts('Note')); @@ -71,33 +91,32 @@ function buildQuickForm() { $this->addElement('hidden', "resources"); - $buttons = array( - array('type' => 'back', + $buttons = [ + [ + 'type' => 'back', 'name' => E::ts('<< Back'), - ), - array( + ], + [ 'type' => 'submit', 'name' => E::ts('Complete and Save'), - ), - ); + ], + ]; $this->addButtons($buttons); - - $this->addFormRule( array( 'CRM_Booking_Form_Booking_Info', 'formRule' ), $this ); - - $this->add('text', 'currencySymbol', E::ts('Currency'), array( 'disabled' => 'disabled' )); + $this->addFormRule(['CRM_Booking_Form_Booking_Info', 'formRule'], $this); + $this->add('text', 'currencySymbol', E::ts('Currency'), ['disabled' => 'disabled']); } - static function formRule($params, $files, $context) { + public static function formRule($params, $files, $context) { $errors = parent::rules($params, $files, $context); - //make sure primary contact is selected + // make sure primary contact is selected $contactId = CRM_Utils_Array::value('primary_contact_id', $params); - if(!is_numeric($contactId)){ + if (!is_numeric($contactId)) { $errors['primary_contact_id'] = E::ts('This field is required.'); } $selectResource = $context->controller->exportValues('SelectResource'); - $resources = json_decode($selectResource['resources'], true); - $resourcesToValidate['resources'] = array(); + $resources = json_decode($selectResource['resources'], true) ?? []; + $resourcesToValidate['resources'] = []; foreach ($resources as $key => $resource) { $resource['start'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('start_date', $resource)); $resource['end'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('end_date', $resource)); @@ -105,72 +124,67 @@ static function formRule($params, $files, $context) { } $result = civicrm_api3('Slot', 'validate', $resourcesToValidate); $values = $result['values']; - if(!$values['is_valid']){ + if (!$values['is_valid']) { $errors['resources'] = E::ts('Unfortunately one or more of your booking slots are clashing with another booking. You will need to edit your booking times to resolve this before you can save your booking. Please go back to the first page to edit your booking slots.'); } return empty($errors) ? TRUE : $errors; } - - function setDefaultValues() { - // prevent quickforms from filling total_amount with value submitted by + public function setDefaultValues() { + // prevent quickforms from filling total_amount with value submitted by // Back action - default value, which is filled correctly will be used instead unset($this->_submitValues['total_amount']); $defaults = parent::setDefaultValues(); - if($this->_id && $this->_action == CRM_Core_Action::UPDATE){ + if ($this->_id && $this->_action == CRM_Core_Action::UPDATE) { $defaults['primary_contact_id'] = CRM_Utils_Array::value('primary_contact_id', $this->_values); - $defaults['secondary_contact_id'] = CRM_Utils_Array::value('secondary_contact_id', $this->_values); $defaults['title'] = CRM_Utils_Array::value('title', $this->_values); $defaults['po_no'] = CRM_Utils_Array::value('po_number', $this->_values); $defaults['booking_status'] = CRM_Utils_Array::value('booking_status_id', $this->_values); $defaults['event_start_date'] = CRM_Utils_Array::value('booking_date', $this->_values); - list($defaults['event_start_date'], $defaults['event_start_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['event_start_date'], 'activityDateTime'); $defaults['description'] = CRM_Utils_Array::value('description', $this->_values); $defaults['note'] = CRM_Utils_Array::value('note', $this->_values); $defaults['enp'] = CRM_Utils_Array::value('participants_estimate', $this->_values); $defaults['fnp'] = CRM_Utils_Array::value('participants_actual', $this->_values); - }else{ - list($defaults['event_start_date'], $defaults['event_start_date_time']) = CRM_Utils_Date::setDateDefaults(date("Y-m-d H:i:s"), 'activityDateTime'); - + } + else { + $defaults['event_start_date'] = date('Y-m-d H:i:s'); } $addSubResourcePage = $this->controller->exportValues('AddSubResource'); $defaults['total_amount'] = $addSubResourcePage['total_price']; //use the amount that passing from the form $amountToFloat = floatval($defaults['total_amount']); $defaults['total_amount'] = round( $amountToFloat, 2, PHP_ROUND_HALF_UP); $config = CRM_Core_Config::singleton(); - $currencySymbol = ""; - if(!empty($config->currencySymbols)){ + if (!empty($config->currencySymbols)) { $currencySymbol = $config->currencySymbols; - }else{ + } + else { $currencySymbol = $config->defaultCurrencySymbol; } $defaults['currencySymbol'] = $currencySymbol; return $defaults; } - function postProcess() { + public function postProcess() { $bookingInfo = $this->exportValues(); $selectResource = $this->controller->exportValues('SelectResource'); $addSubResource = $this->controller->exportValues('AddSubResource'); - $resourcesValue = json_decode($selectResource['resources'], true); + $resourcesValue = json_decode($selectResource['resources'], true) ?? []; $subResourcesValue = json_decode($addSubResource['sub_resources'], true); $subResources = $subResourcesValue['sub_resources']; //Build resources array for passing to Booking APIs - $resources = array(); + $resources = []; foreach ($resourcesValue as $key => $resource) { //Remove element that used in DTHMLX as we do not need them. unset($resource['id']); unset($resource['label']); unset($resource['text']); unset($resource['readonly']); - $resource['start_date'] = $resource['start_date']; - $resource['end_date'] = $resource['end_date']; - $resource['sub_resources'] = array(); + $resource['sub_resources'] = []; if(isset($subResources)){ - foreach ($subResources as $subKey => $subResource) { + foreach ($subResources as $subKey => $subResource) { if($key == $subResource['parent_ref_id']){ $subResourceTmp['resource_id'] = $subResource['resource']['id']; $subResourceTmp['configuration_id'] = $subResource['configuration']['id']; @@ -186,9 +200,15 @@ function postProcess() { array_push($resources, $resource); } + if (empty($resources)) { + $qfKey = CRM_Utils_Request::retrieveValue('qfKey', 'String'); + $redirectUrl = CRM_Utils_System::url('civicrm/booking/add', ['qfKey' => $qfKey]); + CRM_Core_Error::statusBounce(E::ts('You must select a time for at least one resource to make a booking.'), $redirectUrl, E::ts('No resources selected!')); + } + $adhocCharges = CRM_Utils_Array::value('adhoc_charges', $subResourcesValue); - $booking = array(); + $booking = []; if($this->_id && $this->_action == CRM_Core_Action::UPDATE){ $booking['id'] = $this->_id; } @@ -200,14 +220,7 @@ function postProcess() { $booking['title'] = CRM_Utils_Array::value('title', $bookingInfo); $booking['description'] = CRM_Utils_Array::value('description', $bookingInfo); $booking['note'] = CRM_Utils_Array::value('note', $bookingInfo); - - - - $booking['booking_date'] = CRM_Utils_Date::processDate( - CRM_Utils_Array::value('event_start_date', $bookingInfo), - CRM_Utils_Array::value('event_start_date_time', $bookingInfo) - ); - + $booking['booking_date'] = CRM_Utils_Array::value('event_start_date', $bookingInfo); $booking['discount_amount'] = CRM_Utils_Array::value('discount_amount', $addSubResource); $booking['total_amount'] = CRM_Utils_Array::value('total_price', $addSubResource); $amountToFloat = floatval($booking['total_amount']); @@ -218,31 +231,28 @@ function postProcess() { $booking['participants_estimate'] = CRM_Utils_Array::value('enp', $bookingInfo); $booking['participants_actual'] = CRM_Utils_Array::value('fnp', $bookingInfo); - $now = date('YmdHis'); - $session =& CRM_Core_Session::singleton( ); - $booking['created_by'] = $session->get( 'userID' ); - $booking['created_date'] = $now; - $booking['updated_by'] = $session->get( 'userID' ); - $booking['updated_date'] = $now; + $booking['created_by'] = $booking['updated_by'] = CRM_Core_Session::getLoggedInContactID(); + $booking['created_date'] = $booking['updated_date'] = date('YmdHis'); + foreach ($bookingInfo as $key => $value) { + if (substr($key, 0, 7) === 'custom_') { + $booking[$key] = $value; + } + } //retrieve booking_start_date, booking_end_date from all slots - $dates = array(); + $dates = []; foreach ($resources as $key => $slot) { - array_push($dates, CRM_Utils_Array::value('start_date', $slot)); - array_push($dates, CRM_Utils_Array::value('end_date', $slot)); + array_push($dates, CRM_Utils_Array::value('start_date', $slot)); + array_push($dates, CRM_Utils_Array::value('end_date', $slot)); } sort($dates); - $bookingStartDate = $dates[0]; - $bookingEndDate = $dates[count($dates)-1]; - - - $booking['booking_start_date'] = CRM_Utils_Date::processDate($bookingStartDate); - $booking['booking_end_date'] = CRM_Utils_Date::processDate($bookingEndDate); + $booking['booking_start_date'] = reset($dates); + $booking['booking_end_date'] = end($dates); //make sure we create everything in one transaction, not too nice but it does the job $transaction = new CRM_Core_Transaction(); - try{ + try { $result = civicrm_api3('Booking', 'Create', $booking); $bookingID = CRM_Utils_Array::value('id', $result); $booking = CRM_Utils_Array::value($bookingID, CRM_Utils_Array::value('values', $result)); @@ -250,13 +260,13 @@ function postProcess() { $this->_values = $booking; //Now we process slots/subslots and adhoc charges - if($this->_action == CRM_Core_Action::UPDATE){ //booking id was passed from the form so we are on edit mode - $currentSlots = CRM_Booking_BAO_Slot::getBookingSlot($bookingID); + if ($this->_action == CRM_Core_Action::UPDATE) { //booking id was passed from the form so we are on edit mode + $currentSlots = CRM_Booking_BAO_Slot::getBookingSlot($bookingID); } - $newSlotIds = array(); - $newSubSlotIds = array(); + $newSlotIds = []; + $newSubSlotIds = []; foreach ($resources as $key => $resource) { - $slot = array( + $slot = [ 'booking_id' => $bookingID, 'config_id' => CRM_Utils_Array::value('configuration_id', $resource), 'start' => CRM_Utils_Date::processDate(CRM_Utils_Array::value('start_date', $resource)), @@ -264,10 +274,10 @@ function postProcess() { 'resource_id' => CRM_Utils_Array::value('resource_id', $resource), 'quantity' => CRM_Utils_Array::value('quantity', $resource), 'note' => CRM_Utils_Array::value('note', $resource), - ); - if($this->_action == CRM_Core_Action::UPDATE){ + ]; + if ($this->_action == CRM_Core_Action::UPDATE) { list($isExist, $currentID) = CRM_Booking_BAO_Slot::findExistingSlot($slot, $currentSlots); - if($isExist){ + if ($isExist) { $slot['id'] = $currentID; } } @@ -275,22 +285,22 @@ function postProcess() { $slotID = CRM_Utils_Array::value('id', $slotResult); array_push($newSlotIds, $slotID); - if($this->_action == CRM_Core_Action::UPDATE){ + if ($this->_action == CRM_Core_Action::UPDATE) { $currentSubSlots = CRM_Booking_BAO_SubSlot::getSubSlotSlot($slotID); } $subResources = $resource['sub_resources']; - foreach($subResources as $subKey => $subResource){ - $subSlot = array( + foreach ($subResources as $subKey => $subResource) { + $subSlot = [ 'resource_id' => CRM_Utils_Array::value('resource_id', $subResource), 'slot_id' => $slotID, 'config_id' => CRM_Utils_Array::value('configuration_id', $subResource), 'time_required' => CRM_Utils_Date::processDate(CRM_Utils_Array::value('time_required', $subResource)), 'quantity' => CRM_Utils_Array::value('quantity', $subResource), 'note' => CRM_Utils_Array::value('note', $subResource), - ); - if($this->_action == CRM_Core_Action::UPDATE){ - list($isExist, $currentSubSlotId) = CRM_Booking_BAO_SubSlot::findExistingSubSlot($subSlot, $currentSubSlots); - if($isExist){ + ]; + if ($this->_action == CRM_Core_Action::UPDATE) { + list($isExist, $currentSubSlotId) = CRM_Booking_BAO_SubSlot::findExistingSubSlot($subSlot, $currentSubSlots); + if ($isExist) { $subSlot['id'] = $currentSubSlotId; } } @@ -298,50 +308,50 @@ function postProcess() { $subSlotID = CRM_Utils_Array::value('id', $subSlotResult); array_push($newSubSlotIds, $subSlotID); } - if($this->_action == CRM_Core_Action::UPDATE){ //remove subslots that have been removed - $subSlotsToBeRemoved = array(); + if ($this->_action == CRM_Core_Action::UPDATE) { //remove subslots that have been removed + $subSlotsToBeRemoved = []; foreach ($currentSubSlots as $key => $currentSubSlot) { - if(!in_array($key, $newSubSlotIds)){ + if (!in_array($key, $newSubSlotIds)) { $subSlotsToBeRemoved[$key] = $currentSubSlot; } } - if(!empty($subSlotsToBeRemoved)){ + if (!empty($subSlotsToBeRemoved)) { foreach ($subSlotsToBeRemoved as $key => $slot) { - civicrm_api3('SubSlot', 'delete', array('id' => $key)); + civicrm_api3('SubSlot', 'delete', ['id' => $key]); } } } } - if($this->_action == CRM_Core_Action::UPDATE){ //remove all slots that have been removed - $slotsToBeRemoved = array(); - foreach ($currentSlots as $key => $currentSlot) { - if(!in_array($key, $newSlotIds)){ - $slotsToBeRemoved[$key] = $currentSlot; - } + if ($this->_action == CRM_Core_Action::UPDATE) { //remove all slots that have been removed + $slotsToBeRemoved = []; + foreach ($currentSlots as $key => $currentSlot) { + if(!in_array($key, $newSlotIds)){ + $slotsToBeRemoved[$key] = $currentSlot; } - if(!empty($slotsToBeRemoved)){ + } + if (!empty($slotsToBeRemoved)) { foreach ($slotsToBeRemoved as $key => $slot) { - civicrm_api3('Slot', 'delete', array('id' => $key)); + civicrm_api3('Slot', 'delete', ['id' => $key]); } } } - if($adhocCharges){ - if($this->_action == CRM_Core_Action::UPDATE){ - $result = civicrm_api3('AdhocCharges', 'get', array('booking_id' => $bookingID, 'is_deleted' => 0)); + if ($adhocCharges) { + if ($this->_action == CRM_Core_Action::UPDATE) { + $result = civicrm_api3('AdhocCharges', 'get', ['booking_id' => $bookingID, 'is_deleted' => 0]); $currentAdhocCharges = $result['values']; } // fixed bug of CVB-94 // Ad-hoc charges - cannot save - if(!is_null(CRM_Utils_Array::value('items', $adhocCharges))){ + if (!is_null(CRM_Utils_Array::value('items', $adhocCharges))) { $items = array_filter(CRM_Utils_Array::value('items', $adhocCharges)); - $newAdhocChargesIds = array(); - foreach ($items as $key => $item) { - $params = array( + $newAdhocChargesIds = []; + foreach ($items as $key => $item) { + $params = [ 'booking_id' => $bookingID, 'item_id' => CRM_Utils_Array::value('item_id', $item), 'quantity' => CRM_Utils_Array::value('quantity', $item), - ); - if($this->_action == CRM_Core_Action::UPDATE){ + ]; + if ($this->_action == CRM_Core_Action::UPDATE) { list($isExist, $currentAdhocChargesId) = CRM_Booking_BAO_AdhocCharges::findExistingAdhocCharges($params, $currentAdhocCharges); if($isExist){ $params['id'] = $currentAdhocChargesId; @@ -353,16 +363,16 @@ function postProcess() { } } - if($this->_action == CRM_Core_Action::UPDATE){ //remove adhoc charges that have been removed - $adhocChargesToBeRemoved = array(); + if ($this->_action == CRM_Core_Action::UPDATE) { //remove adhoc charges that have been removed + $adhocChargesToBeRemoved = []; foreach ($currentAdhocCharges as $key => $adc) { - if(!in_array($key, $newAdhocChargesIds)){ + if (!in_array($key, $newAdhocChargesIds)) { $adhocChargesToBeRemoved[$key] = $adc; } } - if(!empty($adhocChargesToBeRemoved)){ + if (!empty($adhocChargesToBeRemoved)) { foreach ($adhocChargesToBeRemoved as $key => $adc) { - civicrm_api3('AdhocCharges', 'delete', array('id' => $key)); + civicrm_api3('AdhocCharges', 'delete', ['id' => $key]); } } } @@ -374,10 +384,10 @@ function postProcess() { $cid = CRM_Utils_Array::value('primary_contact_id', $bookingInfo); // user context $url = CRM_Utils_System::url('civicrm/contact/view/booking', - "reset=1&id=$bookingID&cid=$cid&action=view" + "reset=1&id=$bookingID&cid=$cid&action=view" ); CRM_Core_Session::setStatus($booking['title'], E::ts('Saved'), 'success'); - CRM_Utils_System::redirect( $url); + CRM_Utils_System::redirect($url); } catch (CiviCRM_API3_Exception $e) { $transaction->rollback(); @@ -389,7 +399,7 @@ function postProcess() { } } - static function registerScripts() { + public static function registerScripts() { static $loaded = FALSE; if ($loaded) { return; @@ -398,27 +408,25 @@ static function registerScripts() { CRM_Core_Resources::singleton() - ->addStyleFile('uk.co.compucorp.civicrm.booking', 'css/booking.css', 92, 'page-header') + ->addStyleFile(E::LONG_NAME, 'css/booking.css', 92, 'page-header') ->addScriptFile('civicrm', 'packages/backbone/json2.js', 100, 'html-header', FALSE) - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'packages/underscore.js', 110, 'html-header', FALSE) + ->addScriptFile(E::LONG_NAME, 'packages/underscore.js', 110, 'html-header', FALSE) ->addScriptFile('civicrm', 'packages/backbone/backbone.js', 120, 'html-header') ->addScriptFile('civicrm', 'packages/backbone/backbone.marionette.js', 125, 'html-header', FALSE) ->addScriptFile('civicrm', 'packages/backbone/backbone.modelbinder.js', 125, 'html-header', FALSE) ->addScriptFile('civicrm', 'js/crm.backbone.js', 130, 'html-header', FALSE) - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'js/booking/booking-info/app.js', 150, 'html-header') - ->addScriptFile('uk.co.compucorp.civicrm.booking', 'js/booking/booking-info/view.js', 170, 'html-header'); + ->addScriptFile(E::LONG_NAME, 'js/booking/booking-info/app.js', 150, 'html-header') + ->addScriptFile(E::LONG_NAME, 'js/booking/booking-info/view.js', 170, 'html-header'); - $templateDir = CRM_Extension_System::singleton()->getMapper()->keyToBasePath('uk.co.compucorp.civicrm.booking') . '/templates/'; + $templateDir = CRM_Extension_System::singleton()->getMapper()->keyToBasePath(E::LONG_NAME) . '/templates/'; $region = CRM_Core_Region::instance('page-header'); foreach (glob($templateDir . 'CRM/Booking/tpl/booking-info/*.tpl') as $file) { $fileName = substr($file, strlen($templateDir)); - $region->add(array( + $region->add([ 'template' => $fileName, - )); + ]); } - } - } diff --git a/CRM/Booking/Form/Booking/View.php b/CRM/Booking/Form/Booking/View.php index 49985831..395a9240 100644 --- a/CRM/Booking/Form/Booking/View.php +++ b/CRM/Booking/Form/Booking/View.php @@ -1,38 +1,5 @@ 'id-source', 'file' => 'CRM/Contact/Form/Contact']] + * - template - use a field specific template to render this field + * - required + * @var array + */ + protected $entityFields = []; + + /** + * Explicitly declare the entity api name. + */ + public function getDefaultEntity() { + return 'Booking'; + } + + /** + * Function to set variables up before form is built */ public function preProcess() { parent::preProcess(); @@ -81,7 +70,11 @@ public function preProcess() { CRM_Utils_System::setTitle(E::ts('View Booking for') . ' ' . $displayName); self::registerScripts($this); + } + public function buildQuickForm() { + self::buildQuickEntityForm(); + return parent::buildQuickForm(); } static function registerScripts($ctx) { @@ -94,9 +87,9 @@ static function registerScripts($ctx) { $snippet = CRM_Utils_Request::retrieve('snippet', 'Positive', $ctx, FALSE, 0 ); - if($snippet == 2){ + if ($snippet == 2) { CRM_Core_Resources::singleton() - ->addStyleFile('uk.co.compucorp.civicrm.booking', 'css/booking.print.css', 10, 'page-header'); + ->addStyleFile(E::LONG_NAME, 'css/booking.print.css', 10, 'page-header'); } } diff --git a/CRM/Booking/Form/SelectResource.php b/CRM/Booking/Form/SelectResource.php index dd177186..c4f0f309 100644 --- a/CRM/Booking/Form/SelectResource.php +++ b/CRM/Booking/Form/SelectResource.php @@ -1,29 +1,15 @@ assign('bookingId', $this->_id); - + $config = CRM_Core_Config::singleton(); /** * [dateformatDatetime] => %B %E%f, %Y %l:%M %P @@ -53,10 +39,10 @@ public function preProcess() { $this->assign('years', $years); $config = CRM_Core_Config::singleton(); - $currencySymbols = ""; - if(!empty($config->currencySymbols)){ + if (!empty($config->currencySymbols)) { $currencySymbols = $config->currencySymbols; - }else{ + } + else { $currencySymbols = $config->defaultCurrencySymbol; } @@ -69,8 +55,9 @@ public function preProcess() { $resources[$rTypekey]['child'] = $result; } - $this->assign('resources', $resources);; + $this->assign('resources', $resources); $this->assign('currencySymbols', $currencySymbols); + $this->assign('currency', \Civi::settings()->get('defaultCurrency')); $config = CRM_Booking_BAO_BookingConfig::getConfig(); $this->assign('colour', CRM_Utils_Array::value('slot_new_colour', $config)); @@ -78,16 +65,17 @@ public function preProcess() { $this->assign('xStart', $xStart); $this->assign('xSize', $xSize); $this->assign('xStep', $xStep); - - CRM_Core_Resources::singleton()->addVars('booking', + + CRM_Core_Resources::singleton()->addVars('booking', array('edit_mode' => $this->_action & CRM_Core_Action::UPDATE ? 1 : 0)); $this->assign('timeOptions', CRM_Booking_Utils_DateTime::getTimeRange()); - if($this->_id && $this->_action == CRM_Core_Action::UPDATE){ + if ($this->_id && $this->_action == CRM_Core_Action::UPDATE) { $title = CRM_Core_DAO::getFieldValue('CRM_Booking_BAO_Booking', $this->_id, 'title', 'id'); CRM_Utils_System::setTitle(E::ts('Edit Booking') . " - $title"); - }else{ - CRM_Utils_System::setTitle(E::ts('New Booking') ); + } + else { + CRM_Utils_System::setTitle(E::ts('New Booking')); } self::registerScripts(); } @@ -96,18 +84,15 @@ public function preProcess() { * This function sets the default values for the form. * the default values are retrieved from the database * - * @access public - * - * @return None + * @return array */ - function setDefaultValues() { - + public function setDefaultValues() { $defaults = array(); - if($this->_id){ - $params = array( + if ($this->_id) { + $params = array( 'id' => $this->_id, ); - + CRM_Booking_BAO_Booking::retrieve($params, $booking); $result = civicrm_api3('Slot', 'get', array('booking_id' => $this->_id, 'is_deleted' => 0)); $config = CRM_Booking_BAO_BookingConfig::getConfig(); @@ -119,14 +104,14 @@ function setDefaultValues() { $displayQuantity = CRM_Utils_Array::value('quantity', $value) .' x '.CRM_Utils_Array::value('unit_id',$configOptItem) .' ('.CRM_Utils_Array::value('price',$configOptItem).')'; - + $slots[$key] = array( 'id' => CRM_Utils_Array::value('id', $value), 'resource_id' => CRM_Utils_Array::value('resource_id', $value), - + 'start_date' => CRM_Utils_Array::value('start', $value) , 'end_date' => CRM_Utils_Array::value('end', $value) , - + 'label' => CRM_Core_DAO::getFieldValue( 'CRM_Booking_BAO_Resource', CRM_Utils_Array::value('resource_id', $value), @@ -151,12 +136,12 @@ function setDefaultValues() { ); } $firstSlot = reset($slots); - if($firstSlot){ + if ($firstSlot) { $slotStartDate = $firstSlot['start_date']; $this->assign('bookingSlotDate', $slotStartDate); } $this->assign('bookingId', $this->_id); - + $defaults['resources'] = json_encode($slots); } return $defaults; diff --git a/CRM/Booking/Upgrader.php b/CRM/Booking/Upgrader.php index 1bb5a1b9..269e355a 100755 --- a/CRM/Booking/Upgrader.php +++ b/CRM/Booking/Upgrader.php @@ -1,5 +1,5 @@ 3, + $params = [ 'sequential' => 1, 'label' => 'Booking', 'name' => CRM_Booking_Utils_Constants::ACTIVITY_TYPE, - ); - //chcck if it exist in case of re-installation - $optionValue = civicrm_api3('OptionValue', 'get',$params); - if($optionValue['count'] == 0){ + ]; + //chcck if it exist in case of re-installation + $optionValue = civicrm_api3('OptionValue', 'get', $params); + if ($optionValue['count'] == 0) { $params['weight'] = 1; $params['is_reserved'] = 1; $params['is_active'] = 1; - $result = civicrm_api('ActivityType', 'create', $params); + civicrm_api3('ActivityType', 'create', $params); } //create new activity type for sending email confirmation :CVB-95 - $params = array( - 'version' => 3, + $params = [ 'sequential' => 1, 'label' => 'Send booking confirmation', 'name' => CRM_Booking_Utils_Constants::ACTIVITY_TYPE_SEND_EMAIL, - ); - //chcck if it exist in case of re-installation - $optionValue = civicrm_api3('OptionValue', 'get',$params); - if($optionValue['count'] == 0){ + ]; + //chcck if it exist in case of re-installation + $optionValue = civicrm_api3('OptionValue', 'get', $params); + if ($optionValue['count'] == 0) { $params['weight'] = 1; $params['is_reserved'] = 1; $params['is_active'] = 1; - $result = civicrm_api('ActivityType', 'create', $params); + civicrm_api3('ActivityType', 'create', $params); } - $result = civicrm_api('OptionGroup', 'getsingle', array( - 'version' => 3, - 'sequential' => 1, - 'name' => 'msg_tpl_workflow_booking') + $result = civicrm_api3('OptionGroup', 'getsingle', [ + 'sequential' => 1, + 'name' => 'msg_tpl_workflow_booking' + ] ); - if(isset($result['id'])){ - $params = array( - 'version' => 3, + if (isset($result['id'])) { + $params = [ 'sequential' => 1, 'option_group_id' => $result['id'], - ); - $opvResult = civicrm_api('OptionValue', 'get', $params); - if(isset($opvResult['values']) && !empty($opvResult['values'])){ - foreach ($opvResult['values'] as $value) { + ]; + $opvResult = civicrm_api3('OptionValue', 'get', $params); + if (isset($opvResult['values']) && !empty($opvResult['values'])) { + foreach ($opvResult['values'] as $value) { switch ($value['name']) { case 'booking_offline_receipt': $html = file_get_contents($this->extensionDir . '/msg_tpl/booking_offline_receipt.html', FILE_USE_INCLUDE_PATH); @@ -63,110 +60,53 @@ public function install() { $title = E::ts("Booking - Confirmation and Receipt (off-line)"); break; } - if(isset($title)){ - $params = array( - 'version' => 3, - 'sequential' => 1, + if (isset($title)) { + $params = [ 'msg_title' => $title, - 'msg_subject' => E::ts("Booking - Confirmation Receipt").' - '.ts("Booking Status:").'{$booking_status}', + 'msg_subject' => E::ts("Booking - Confirmation Receipt") . ' - ' . E::ts("Booking Status:") . '{$booking_status}', 'msg_text' => $text, 'msg_html' => $html, 'is_active' => 1, 'workflow_id' => $value['id'], 'is_default' => 1, 'is_reserved' => 0, - ); - $result = civicrm_api('MessageTemplate', 'create', $params); + ]; + civicrm_api3('MessageTemplate', 'create', $params); $params['is_default'] = 0; $params['is_reserved'] = 1; //re-created another template - $result = civicrm_api('MessageTemplate', 'create', $params); + civicrm_api3('MessageTemplate', 'create', $params); } } } } $this->executeSqlFile('sql/civibooking_default.sql'); - $this->upgrade_1101(); + // Enable booking custom data + $this->upgrade_1102(); } /** * Example: Run an external SQL script when the module is uninstalled */ public function uninstall() { - $this->removeNavigationMenus(); - } - - /** - * Removes menu items added by this extension. - */ - private function removeNavigationMenus() { - $menuItems = $this->buildBookingSubMenusParameters(); - - foreach ($menuItems as $item) { - $this->removeNav($item['name']); - } - - CRM_Core_BAO_Navigation::resetNavigation(); } /** * Example: Run a simple query when a module is enabled * -*/ + */ public function enable() { - $this->executeSqlFile('sql/civibooking_enable.sql'); - $this->toggleIsActiveMenuItems(true); + $this->executeSqlFile('sql/civibooking_enable.sql'); } /** * Example: Run a simple query when a module is disabled * - */ + */ public function disable() { //TODO:: Disable the message template $this->executeSqlFile('sql/civibooking_disable.sql'); - $this->toggleIsActiveMenuItems(false); - } - - /** - * Sets is_active parameter for menu items created by this extension. - * - * @param $isActive - */ - private function toggleIsActiveMenuItems($isActive) { - $sortedItems = array(); - $menuItems = $this->buildBookingSubMenusParameters(); - $isActive = (int) $isActive; - foreach ($menuItems as $item) { - $parent = CRM_Utils_Array::value('parent_name', $item, '_noparent_'); - $sortedItems[$parent][] = $item['name']; - } - - foreach ($sortedItems as $parent => $items) { - $params = array( - 'sequential' => 1, - 'name' => array('IN' => $items), - 'parent_id' => $parent, - 'api.Navigation.create' => array('id' => '$value.id', 'is_active' => $isActive), - ); - - if ($parent === '_noparent_') { - $params['parent_id'] = array('IS NULL' => 1); - } - - $versionNum = $this->versionSwitcher(); - if ($versionNum >= 470){ - civicrm_api3('Navigation', 'get', $params); - } - else { - $items = implode("','", $items); - $query = "UPDATE civicrm_navigation SET is_active = {$isActive} WHERE name IN ('{$items}')"; - CRM_Core_DAO::executeQuery($query); - } - } - - CRM_Core_BAO_Navigation::resetNavigation(); } // By convention, functions that look like "function upgrade_NNNN()" are @@ -174,190 +114,189 @@ private function toggleIsActiveMenuItems($isActive) { public function upgrade_1100() { $this->ctx->log->info('Applying update 1100'); - $this->executeSqlFile('sql/update_1100.sql'); + if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_booking_config', 'unlimited_resource_time_config')) { + $this->executeSqlFile('sql/upgrade_1100.sql'); + } return TRUE; } /** - * This upgrade builds navigation menus for the extension. + * This upgrade used to build navigation menus but is no longer required */ public function upgrade_1101() { - $administerMenuId = $this->getAdministerMenuID(); + return TRUE; + } - // skip adding menu if there is no administer menu - if ($administerMenuId) { - $bookingSubMenus = $this->buildBookingSubMenusParameters(); + public function upgrade_1102() { + Civi::log()->info('Enabling Booking custom data'); + self::enableBookingCustomData(); + return TRUE; + } - foreach ($bookingSubMenus as $menuItem) { - $this->addNav($menuItem); - } + public static function enableBookingCustomData() { + // Enable Booking custom data + $optionValue = [ + 'name' => 'civicrm_booking', + 'label' => 'Booking', + 'value' => 'Booking', + ]; + $optionValues = civicrm_api3('OptionValue', 'get', [ + 'option_group_id' => 'cg_extend_objects', + 'name' => $optionValue['name'], + ]); + if (!$optionValues['count']) { + civicrm_api3('OptionValue', 'create', [ + 'option_group_id' => 'cg_extend_objects', + 'name' => $optionValue['name'], + 'label' => $optionValue['label'], + 'value' => $optionValue['value'], + ]); } - - CRM_Core_BAO_Navigation::resetNavigation(); - - return TRUE; } + /** * Builds array with parameters to create menu items for the extension. * * @return array */ - private function buildBookingSubMenusParameters() { - $bookingStatusGid = $this->getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_BOOKING_STATUS); - $resourceTypeGid = $this->getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_RESOURCE_TYPE); - $resourceLocationGId = $this->getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_RESOURCE_LOCATION); - $sizeUnitGid = $this->getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_SIZE_UNIT); - $cancellationChargesGid = $this->getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_CANCELLATION_CHARGES); - - $menus = array( - array( + public static function getMenuItems() { + $bookingStatusGid = self::getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_BOOKING_STATUS); + $resourceTypeGid = self::getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_RESOURCE_TYPE); + $resourceLocationGId = self::getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_RESOURCE_LOCATION); + $sizeUnitGid = self::getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_SIZE_UNIT); + $cancellationChargesGid = self::getOptionGroupID(CRM_Booking_Utils_Constants::OPTION_CANCELLATION_CHARGES); + + $menus = [ + [ 'label' => ts('CiviBooking'), 'name' => 'admin_booking', 'url' => '#', 'permission' => 'administer CiviBooking', - 'operator' => null, + 'operator' => NULL, 'separator' => 1, 'parent_name' => 'Administer', - ), - array( + ], + [ 'label' => ts('Resource Configuration Set'), 'name' => 'resource_config_set', 'url' => CRM_Utils_System::url('civicrm/admin/resource/config_set', "reset=1", TRUE), - 'permission' => null, - 'operator' => null, + 'permission' => NULL, + 'operator' => NULL, 'separator' => 0, - 'parent_name' => 'admin_booking', - ), - array( + 'parent_name' => 'Administer/admin_booking', + ], + [ 'label' => ts('Manage Resources'), 'name' => 'manage_resources', 'url' => CRM_Utils_system::url('civicrm/admin/resource', "reset=1", TRUE), - 'permission' => null, - 'operator' => null, + 'permission' => NULL, + 'operator' => NULL, 'separator' => 0, - 'parent_name' => 'admin_booking', - ), - array( + 'parent_name' => 'Administer/admin_booking', + ], + [ 'label' => ts('Additional Charges Item'), 'name' => 'adhoc_charges_item', 'url' => CRM_Utils_system::url('civicrm/admin/adhoc_charges_item', "reset=1", TRUE), - 'permission' => null, - 'operator' => null, + 'permission' => NULL, + 'operator' => NULL, 'separator' => 0, - 'parent_name' => 'admin_booking', - ), - array( + 'parent_name' => 'Administer/admin_booking', + ], + [ 'label' => ts('Booking Status'), 'name' => 'booking_status', - 'url' => CRM_Utils_system::url('civicrm/admin/options', array('gid' => $bookingStatusGid, 'reset' => 1), TRUE), - 'permission' => null, - 'operator' => null, + 'url' => CRM_Utils_system::url('civicrm/admin/options', ['gid' => $bookingStatusGid, 'reset' => 1], TRUE), + 'permission' => NULL, + 'operator' => NULL, 'separator' => 0, - 'parent_name' => 'admin_booking', - ), - array( + 'parent_name' => 'Administer/admin_booking', + ], + [ 'label' => ts('Resource Type'), 'name' => 'resource_type', - 'url' => CRM_Utils_system::url('civicrm/admin/options', array('gid' => $resourceTypeGid, 'reset' => 1), TRUE), - 'permission' => null, - 'operator' => null, + 'url' => CRM_Utils_system::url('civicrm/admin/options', ['gid' => $resourceTypeGid, 'reset' => 1], TRUE), + 'permission' => NULL, + 'operator' => NULL, 'separator' => 0, - 'parent_name' => 'admin_booking', - ), - array( + 'parent_name' => 'Administer/admin_booking', + ], + [ 'label' => ts('Size Unit'), 'name' => 'size_unit', - 'url' => CRM_Utils_system::url('civicrm/admin/options', array('gid' => $sizeUnitGid, 'reset' => 1), TRUE), - 'permission' => null, - 'operator' => null, + 'url' => CRM_Utils_system::url('civicrm/admin/options', ['gid' => $sizeUnitGid, 'reset' => 1], TRUE), + 'permission' => NULL, + 'operator' => NULL, 'separator' => 0, - 'parent_name' => 'admin_booking', - ), - array( + 'parent_name' => 'Administer/admin_booking', + ], + [ 'label' => ts('Cancellation Charges'), 'name' => 'cancellation_charges', - 'url' => CRM_Utils_system::url('civicrm/admin/options', array('gid' => $cancellationChargesGid,'reset' => 1), TRUE), - 'permission' => null, - 'operator' => null, + 'url' => CRM_Utils_system::url('civicrm/admin/options', ['gid' => $cancellationChargesGid,'reset' => 1], TRUE), + 'permission' => NULL, + 'operator' => NULL, 'separator' => 0, - 'parent_name' => 'admin_booking', - ), - array( + 'parent_name' => 'Administer/admin_booking', + ], + [ 'label' => ts('Booking Component Settings'), 'name' => 'booking_component_settings', 'url' => CRM_Utils_system::url('civicrm/admin/setting/preferences/booking', "reset=1", TRUE), - 'permission' => null, - 'operator' => null, + 'permission' => NULL, + 'operator' => NULL, 'separator' => 0, - 'parent_name' => 'admin_booking', - ), - array( + 'parent_name' => 'Administer/admin_booking', + ], + [ 'label' => ts('Resource Location'), 'name' => 'resource_location', - 'url' => CRM_Utils_system::url('civicrm/admin/options', array('gid' => $resourceLocationGId,'reset' => 1), TRUE), - 'permission' => null, - 'operator' => null, + 'url' => CRM_Utils_system::url('civicrm/admin/options', ['gid' => $resourceLocationGId,'reset' => 1], TRUE), + 'permission' => NULL, + 'operator' => NULL, 'separator' => 0, - 'parent_name' => 'admin_booking', - ), - array( + 'parent_name' => 'Administer/admin_booking', + ], + [ 'label' => ts('Find Bookings'), 'name' => 'find_booking', 'url' => CRM_Utils_system::url('civicrm/booking/search', "reset=1", TRUE), 'permission' => 'administer CiviBooking,create and update bookings,view all bookings', - 'operator' => null, + 'operator' => NULL, 'separator' => 0, - ), - array( + ], + [ 'label' => ts('Booking'), 'name' => 'booking', - 'url' => null, + 'url' => NULL, 'permission' => 'administer CiviBooking,create and update bookings,view all bookings', - 'operator' => null, - 'separator' => null, - ), - array( + 'operator' => NULL, + 'separator' => NULL, + ], + [ 'label' => ts('New Booking'), 'name' => 'new_booking', 'url' => CRM_Utils_system::url('civicrm/booking/add', "reset=1", TRUE), 'permission' => 'administer CiviBooking,create and update bookings', - 'operator' => null, + 'operator' => NULL, 'separator' => 0, 'parent_name' => 'booking', - ), - array( + ], + [ 'label' => ts('Day View'), 'name' => 'day_view', 'url' => CRM_Utils_system::url('civicrm/booking/day-view', "reset=1", TRUE), 'permission' => 'administer CiviBooking,create and update bookings,view all bookings', - 'operator' => null, + 'operator' => NULL, 'separator' => 0, 'parent_name' => 'booking', - ), - ); + ], + ]; return $menus; } - /** - * Obtains ID of Administer menu. - * - * @return null|string - */ - private function getAdministerMenuID() { - $domain_id = CRM_Core_Config::domainID(); - - $administerMenuId = CRM_Core_DAO::singleValueQuery(" - SELECT id - FROM civicrm_navigation - WHERE name = 'Administer' - AND domain_id = $domain_id - "); - - return $administerMenuId; - } - /** * Obtains an option group's ID given its name. * @@ -365,139 +304,13 @@ private function getAdministerMenuID() { * * @return int */ - private function getOptionGroupID($name) { - $result = civicrm_api3('OptionGroup', 'getsingle', array('name' => $name)); - - if($result['id']){ - return $result['id']; + private static function getOptionGroupID($name) { + try { + return civicrm_api3('OptionGroup', 'getsingle', ['name' => $name])['id']; } - - return 0; - } - - /** - * Adds given menu item to CiviCRM navigation. - * - * @param array $menuItem - */ - private function addNav($menuItem) { - if (isset($menuItem['parent_name'])) { - $menuItem['parent_id'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Navigation', $menuItem['parent_name'], 'id', 'name'); - unset($menuItem['parent_name']); + catch (Exception $e) { + return 0; } - - $menuItem['is_active'] = 1; - - CRM_Core_BAO_Navigation::add($menuItem); } - /** - * Removes navigation item identified by $name from CiviCRM navigation. - * - * @param string $name - */ - private function removeNav($name) { - $versionNum = $this->versionSwitcher(); - if ($versionNum >= 470){ - civicrm_api3('Navigation', 'get', array( - 'sequential' => 1, - 'name' => $name, - 'api.Navigation.delete' => array('id' => '$value.id'), - )); - } - else { - $query = "DELETE FROM civicrm_navigation WHERE name = '{$name}'"; - CRM_Core_DAO::executeQuery($query); - } - } - - /** - * Get civicrm version. - * - * @return $versionNum - */ - private function versionSwitcher() { - $version = CRM_Utils_System::version(); - preg_match('/[0-9]\.[0-9]\.[0-9]/', $version, $matches); - $versionNum = str_replace(".","",array_pop($matches)); - - return $versionNum; - } - - /** - * Example: Run a couple simple queries - * - * @return TRUE on success - * @throws Exception - * - public function upgrade_4200() { - $this->ctx->log->info('Applying update 4200'); - CRM_Core_DAO::executeQuery('UPDATE foo SET bar = "whiz"'); - CRM_Core_DAO::executeQuery('DELETE FROM bang WHERE willy = wonka(2)'); - return TRUE; - } // */ - - - /** - * Example: Run an external SQL script - * - * @return TRUE on success - * @throws Exception - public function upgrade_4201() { - $this->ctx->log->info('Applying update 4201'); - // this path is relative to the extension base dir - $this->executeSqlFile('sql/upgrade_4201.sql'); - return TRUE; - } // */ - - - /** - * Example: Run a slow upgrade process by breaking it up into smaller chunk - * - * @return TRUE on success - * @throws Exception - public function upgrade_4202() { - $this->ctx->log->info('Planning update 4202'); // PEAR Log interface - - $this->addTask(E::ts('Process first step'), 'processPart1', $arg1, $arg2); - $this->addTask(E::ts('Process second step'), 'processPart2', $arg3, $arg4); - $this->addTask(E::ts('Process second step'), 'processPart3', $arg5); - return TRUE; - } - public function processPart1($arg1, $arg2) { sleep(10); return TRUE; } - public function processPart2($arg3, $arg4) { sleep(10); return TRUE; } - public function processPart3($arg5) { sleep(10); return TRUE; } - // */ - - - /** - * Example: Run an upgrade with a query that touches many (potentially - * millions) of records by breaking it up into smaller chunks. - * - * @return TRUE on success - * @throws Exception - public function upgrade_4203() { - $this->ctx->log->info('Planning update 4203'); // PEAR Log interface - - $minId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_contribution'); - $maxId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_contribution'); - for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) { - $endId = $startId + self::BATCH_SIZE - 1; - $title = E::ts('Upgrade Batch (%1 => %2)', array( - 1 => $startId, - 2 => $endId, - )); - $sql = ' - UPDATE civicrm_contribution SET foobar = whiz(wonky()+wanker) - WHERE id BETWEEN %1 and %2 - '; - $params = array( - 1 => array($startId, 'Integer'), - 2 => array($endId, 'Integer'), - ); - $this->addTask($title, 'executeSql', $sql, $params); - } - return TRUE; - } // */ - } diff --git a/CRM/Booking/Upgrader/Base.php b/CRM/Booking/Upgrader/Base.php index ae54f2ff..ea4e385f 100644 --- a/CRM/Booking/Upgrader/Base.php +++ b/CRM/Booking/Upgrader/Base.php @@ -1,7 +1,7 @@ extensionDir . '/' . $relativePath; - require_once 'CRM/Utils/Migrate/Import.php'; + return $this->executeCustomDataFileByAbsPath($xml_file); + } + + /** + * Run a CustomData file + * + * @param string $xml_file the CustomData XML file path (absolute path) + * + * @return bool + */ + protected static function executeCustomDataFileByAbsPath($xml_file) { $import = new CRM_Utils_Migrate_Import(); $import->run($xml_file); return TRUE; } /** - * Run a SQL file + * Run a SQL file. * * @param string $relativePath the SQL file path (relative to this extension's dir) + * * @return bool */ public function executeSqlFile($relativePath) { CRM_Utils_File::sourceSQLFile( CIVICRM_DSN, - $this->extensionDir . '/' . $relativePath + $this->extensionDir . DIRECTORY_SEPARATOR . $relativePath + ); + return TRUE; + } + + /** + * @param string $tplFile + * The SQL file path (relative to this extension's dir). + * Ex: "sql/mydata.mysql.tpl". + * @return bool + */ + public function executeSqlTemplate($tplFile) { + // Assign multilingual variable to Smarty. + $upgrade = new CRM_Upgrade_Form(); + + $tplFile = CRM_Utils_File::isAbsolute($tplFile) ? $tplFile : $this->extensionDir . DIRECTORY_SEPARATOR . $tplFile; + $smarty = CRM_Core_Smarty::singleton(); + $smarty->assign('domainID', CRM_Core_Config::domainID()); + CRM_Utils_File::sourceSQLFile( + CIVICRM_DSN, $smarty->fetch($tplFile), NULL, TRUE ); return TRUE; } /** - * Run one SQL query + * Run one SQL query. * * This is just a wrapper for CRM_Core_DAO::executeSql, but it * provides syntatic sugar for queueing several tasks that @@ -110,13 +146,14 @@ public function executeSqlFile($relativePath) { */ public function executeSql($query, $params = array()) { // FIXME verify that we raise an exception on error - CRM_Core_DAO::executeSql($query, $params); + CRM_Core_DAO::executeQuery($query, $params); return TRUE; } /** - * Syntatic sugar for enqueuing a task which calls a function - * in this class. The task is weighted so that it is processed + * Syntatic sugar for enqueuing a task which calls a function in this class. + * + * The task is weighted so that it is processed * as part of the currently-pending revision. * * After passing the $funcName, you can also pass parameters that will go to @@ -136,7 +173,7 @@ public function addTask($title) { // ******** Revision-tracking helpers ******** /** - * Determine if there are any pending revisions + * Determine if there are any pending revisions. * * @return bool */ @@ -155,7 +192,7 @@ public function hasPendingRevisions() { } /** - * Add any pending revisions to the queue + * Add any pending revisions to the queue. */ public function enqueuePendingRevisions(CRM_Queue_Queue $queue) { $this->queue = $queue; @@ -163,7 +200,7 @@ public function enqueuePendingRevisions(CRM_Queue_Queue $queue) { $currentRevision = $this->getCurrentRevision(); foreach ($this->getRevisions() as $revision) { if ($revision > $currentRevision) { - $title = E::ts('Upgrade %1 to revision %2', array( + $title = ts('Upgrade %1 to revision %2', array( 1 => $this->extensionName, 2 => $revision, )); @@ -188,12 +225,12 @@ public function enqueuePendingRevisions(CRM_Queue_Queue $queue) { } /** - * Get a list of revisions + * Get a list of revisions. * * @return array(revisionNumbers) sorted numerically */ public function getRevisions() { - if (! is_array($this->revisions)) { + if (!is_array($this->revisions)) { $this->revisions = array(); $clazz = new ReflectionClass(get_class($this)); @@ -210,47 +247,103 @@ public function getRevisions() { } public function getCurrentRevision() { - // return CRM_Core_BAO_Extension::getSchemaVersion($this->extensionName); + $revision = CRM_Core_BAO_Extension::getSchemaVersion($this->extensionName); + if (!$revision) { + $revision = $this->getCurrentRevisionDeprecated(); + } + return $revision; + } + + private function getCurrentRevisionDeprecated() { $key = $this->extensionName . ':version'; - return CRM_Core_BAO_Setting::getItem('Extension', $key); + if ($revision = CRM_Core_BAO_Setting::getItem('Extension', $key)) { + $this->revisionStorageIsDeprecated = TRUE; + } + return $revision; } public function setCurrentRevision($revision) { - // We call this during hook_civicrm_install, but the underlying SQL - // UPDATE fails because the extension record hasn't been INSERTed yet. - // Instead, track revisions in our own namespace. - // CRM_Core_BAO_Extension::setSchemaVersion($this->extensionName, $revision); - - $key = $this->extensionName . ':version'; - CRM_Core_BAO_Setting::setItem($revision, 'Extension', $key); + CRM_Core_BAO_Extension::setSchemaVersion($this->extensionName, $revision); + // clean up legacy schema version store (CRM-19252) + $this->deleteDeprecatedRevision(); return TRUE; } + private function deleteDeprecatedRevision() { + if ($this->revisionStorageIsDeprecated) { + $setting = new CRM_Core_BAO_Setting(); + $setting->name = $this->extensionName . ':version'; + $setting->delete(); + CRM_Core_Error::debug_log_message("Migrated extension schema revision ID for {$this->extensionName} from civicrm_setting (deprecated) to civicrm_extension.\n"); + } + } + // ******** Hook delegates ******** + /** + * @see https://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install + */ public function onInstall() { - foreach (glob($this->extensionDir . '/sql/*_install.sql') as $file) { - CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $file); + $files = glob($this->extensionDir . '/sql/*_install.sql'); + if (is_array($files)) { + foreach ($files as $file) { + CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $file); + } + } + $files = glob($this->extensionDir . '/sql/*_install.mysql.tpl'); + if (is_array($files)) { + foreach ($files as $file) { + $this->executeSqlTemplate($file); + } + } + $files = glob($this->extensionDir . '/xml/*_install.xml'); + if (is_array($files)) { + foreach ($files as $file) { + $this->executeCustomDataFileByAbsPath($file); + } } if (is_callable(array($this, 'install'))) { $this->install(); } + } + + /** + * @see https://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_postInstall + */ + public function onPostInstall() { $revisions = $this->getRevisions(); if (!empty($revisions)) { $this->setCurrentRevision(max($revisions)); } + if (is_callable(array($this, 'postInstall'))) { + $this->postInstall(); + } } + /** + * @see https://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall + */ public function onUninstall() { + $files = glob($this->extensionDir . '/sql/*_uninstall.mysql.tpl'); + if (is_array($files)) { + foreach ($files as $file) { + $this->executeSqlTemplate($file); + } + } if (is_callable(array($this, 'uninstall'))) { $this->uninstall(); } - foreach (glob($this->extensionDir . '/sql/*_uninstall.sql') as $file) { - CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $file); + $files = glob($this->extensionDir . '/sql/*_uninstall.sql'); + if (is_array($files)) { + foreach ($files as $file) { + CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $file); + } } - $this->setCurrentRevision(NULL); } + /** + * @see https://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable + */ public function onEnable() { // stub for possible future use if (is_callable(array($this, 'enable'))) { @@ -258,6 +351,9 @@ public function onEnable() { } } + /** + * @see https://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_disable + */ public function onDisable() { // stub for possible future use if (is_callable(array($this, 'disable'))) { @@ -266,12 +362,15 @@ public function onDisable() { } public function onUpgrade($op, CRM_Queue_Queue $queue = NULL) { - switch($op) { + switch ($op) { case 'check': return array($this->hasPendingRevisions()); + case 'enqueue': return $this->enqueuePendingRevisions($queue); + default: } } + } diff --git a/api/v3/Booking.php b/api/v3/Booking.php index 99255ffb..0639deb6 100644 --- a/api/v3/Booking.php +++ b/api/v3/Booking.php @@ -27,9 +27,7 @@ function _civicrm_api3_booking_create_spec(&$spec) { * @throws API_Exception */ function civicrm_api3_booking_create($params) { - $bookingBAO = CRM_Booking_BAO_Booking::create($params); - _civicrm_api3_object_to_array($bookingBAO, $bookingArray[$bookingBAO->id]); - return civicrm_api3_create_success($bookingArray, $params, 'Booking', 'create'); + return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Booking'); } diff --git a/booking.civix.php b/booking.civix.php index e6bd993c..f2a898ac 100644 --- a/booking.civix.php +++ b/booking.civix.php @@ -6,7 +6,6 @@ * The ExtensionUtil class provides small stubs for accessing resources of this * extension. */ - class CRM_Booking_ExtensionUtil { const SHORT_NAME = "booking"; const LONG_NAME = "uk.co.compucorp.civicrm.booking"; @@ -77,33 +76,43 @@ public static function findClass($suffix) { } } + +use CRM_Booking_ExtensionUtil as E; + /** - * (Delegated) Implementation of hook_civicrm_config + * (Delegated) Implements hook_civicrm_config(). + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config */ function _booking_civix_civicrm_config(&$config = NULL) { static $configured = FALSE; - if ($configured) return; + if ($configured) { + return; + } $configured = TRUE; $template =& CRM_Core_Smarty::singleton(); - $extRoot = dirname( __FILE__ ) . DIRECTORY_SEPARATOR; + $extRoot = dirname(__FILE__) . DIRECTORY_SEPARATOR; $extDir = $extRoot . 'templates'; - if ( is_array( $template->template_dir ) ) { - array_unshift( $template->template_dir, $extDir ); - } else { - $template->template_dir = array( $extDir, $template->template_dir ); + if (is_array($template->template_dir)) { + array_unshift($template->template_dir, $extDir); + } + else { + $template->template_dir = array($extDir, $template->template_dir); } - $include_path = $extRoot . PATH_SEPARATOR . get_include_path( ); - set_include_path( $include_path ); + $include_path = $extRoot . PATH_SEPARATOR . get_include_path(); + set_include_path($include_path); } /** - * (Delegated) Implementation of hook_civicrm_xmlMenu + * (Delegated) Implements hook_civicrm_xmlMenu(). * * @param $files array(string) + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_xmlMenu */ function _booking_civix_civicrm_xmlMenu(&$files) { foreach (_booking_civix_glob(__DIR__ . '/xml/Menu/*.xml') as $file) { @@ -112,57 +121,82 @@ function _booking_civix_civicrm_xmlMenu(&$files) { } /** - * Implementation of hook_civicrm_install + * Implements hook_civicrm_install(). + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install */ function _booking_civix_civicrm_install() { _booking_civix_civicrm_config(); if ($upgrader = _booking_civix_upgrader()) { - return $upgrader->onInstall(); + $upgrader->onInstall(); + } +} + +/** + * Implements hook_civicrm_postInstall(). + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_postInstall + */ +function _booking_civix_civicrm_postInstall() { + _booking_civix_civicrm_config(); + if ($upgrader = _booking_civix_upgrader()) { + if (is_callable(array($upgrader, 'onPostInstall'))) { + $upgrader->onPostInstall(); + } } } /** - * Implementation of hook_civicrm_uninstall + * Implements hook_civicrm_uninstall(). + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall */ function _booking_civix_civicrm_uninstall() { _booking_civix_civicrm_config(); if ($upgrader = _booking_civix_upgrader()) { - return $upgrader->onUninstall(); + $upgrader->onUninstall(); } } /** - * (Delegated) Implementation of hook_civicrm_enable + * (Delegated) Implements hook_civicrm_enable(). + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable */ function _booking_civix_civicrm_enable() { _booking_civix_civicrm_config(); if ($upgrader = _booking_civix_upgrader()) { if (is_callable(array($upgrader, 'onEnable'))) { - return $upgrader->onEnable(); + $upgrader->onEnable(); } } } /** - * (Delegated) Implementation of hook_civicrm_disable + * (Delegated) Implements hook_civicrm_disable(). + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_disable + * @return mixed */ function _booking_civix_civicrm_disable() { _booking_civix_civicrm_config(); if ($upgrader = _booking_civix_upgrader()) { if (is_callable(array($upgrader, 'onDisable'))) { - return $upgrader->onDisable(); + $upgrader->onDisable(); } } } /** - * (Delegated) Implementation of hook_civicrm_upgrade + * (Delegated) Implements hook_civicrm_upgrade(). * * @param $op string, the type of operation being performed; 'check' or 'enqueue' * @param $queue CRM_Queue_Queue, (for 'enqueue') the modifiable list of pending up upgrade tasks * * @return mixed based on op. for 'check', returns array(boolean) (TRUE if upgrades are pending) * for 'enqueue', returns void + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_upgrade */ function _booking_civix_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) { if ($upgrader = _booking_civix_upgrader()) { @@ -170,10 +204,14 @@ function _booking_civix_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) { } } +/** + * @return CRM_Booking_Upgrader + */ function _booking_civix_upgrader() { - if (!file_exists(__DIR__.'/CRM/Booking/Upgrader.php')) { + if (!file_exists(__DIR__ . '/CRM/Booking/Upgrader.php')) { return NULL; - } else { + } + else { return CRM_Booking_Upgrader_Base::instance(); } } @@ -206,7 +244,8 @@ function _booking_civix_find_files($dir, $pattern) { while (FALSE !== ($entry = readdir($dh))) { $path = $subdir . DIRECTORY_SEPARATOR . $entry; if ($entry{0} == '.') { - } elseif (is_dir($path)) { + } + elseif (is_dir($path)) { $todos[] = $path; } } @@ -216,23 +255,83 @@ function _booking_civix_find_files($dir, $pattern) { return $result; } /** - * (Delegated) Implementation of hook_civicrm_managed + * (Delegated) Implements hook_civicrm_managed(). * * Find any *.mgd.php files, merge their content, and return. + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_managed */ function _booking_civix_civicrm_managed(&$entities) { $mgdFiles = _booking_civix_find_files(__DIR__, '*.mgd.php'); + sort($mgdFiles); foreach ($mgdFiles as $file) { $es = include $file; foreach ($es as $e) { if (empty($e['module'])) { - $e['module'] = 'uk.co.compucorp.civicrm.booking'; + $e['module'] = E::LONG_NAME; + } + if (empty($e['params']['version'])) { + $e['params']['version'] = '3'; } $entities[] = $e; } } } +/** + * (Delegated) Implements hook_civicrm_caseTypes(). + * + * Find any and return any files matching "xml/case/*.xml" + * + * Note: This hook only runs in CiviCRM 4.4+. + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_caseTypes + */ +function _booking_civix_civicrm_caseTypes(&$caseTypes) { + if (!is_dir(__DIR__ . '/xml/case')) { + return; + } + + foreach (_booking_civix_glob(__DIR__ . '/xml/case/*.xml') as $file) { + $name = preg_replace('/\.xml$/', '', basename($file)); + if ($name != CRM_Case_XMLProcessor::mungeCaseType($name)) { + $errorMessage = sprintf("Case-type file name is malformed (%s vs %s)", $name, CRM_Case_XMLProcessor::mungeCaseType($name)); + CRM_Core_Error::fatal($errorMessage); + // throw new CRM_Core_Exception($errorMessage); + } + $caseTypes[$name] = array( + 'module' => E::LONG_NAME, + 'name' => $name, + 'file' => $file, + ); + } +} + +/** + * (Delegated) Implements hook_civicrm_angularModules(). + * + * Find any and return any files matching "ang/*.ang.php" + * + * Note: This hook only runs in CiviCRM 4.5+. + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_angularModules + */ +function _booking_civix_civicrm_angularModules(&$angularModules) { + if (!is_dir(__DIR__ . '/ang')) { + return; + } + + $files = _booking_civix_glob(__DIR__ . '/ang/*.ang.php'); + foreach ($files as $file) { + $name = preg_replace(':\.ang\.php$:', '', basename($file)); + $module = include $file; + if (empty($module['ext'])) { + $module['ext'] = E::LONG_NAME; + } + $angularModules[$name] = $module; + } +} + /** * Glob wrapper which is guaranteed to return an array. * @@ -241,7 +340,7 @@ function _booking_civix_civicrm_managed(&$entities) { * result for an empty match is sometimes array() and sometimes FALSE. * This wrapper provides consistency. * - * @see http://php.net/glob + * @link http://php.net/glob * @param string $pattern * @return array, possibly empty */ @@ -251,40 +350,112 @@ function _booking_civix_glob($pattern) { } /** - * Inserts a navigation menu item at a given place in the hierarchy + * Inserts a navigation menu item at a given place in the hierarchy. * - * $menu - menu hierarchy - * $path - path where insertion should happen (ie. Administer/System Settings) - * $item - menu you need to insert (parent/child attributes will be filled for you) - * $parentId - used internally to recurse in the menu structure + * @param array $menu - menu hierarchy + * @param string $path - path to parent of this item, e.g. 'my_extension/submenu' + * 'Mailing', or 'Administer/System Settings' + * @param array $item - the item to insert (parent/child attributes will be + * filled for you) */ -function _booking_civix_insert_navigation_menu(&$menu, $path, $item, $parentId = NULL) { - static $navId; - +function _booking_civix_insert_navigation_menu(&$menu, $path, $item) { // If we are done going down the path, insert menu if (empty($path)) { - if (!$navId) $navId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_navigation"); - $navId ++; - $menu[$navId] = array ( - 'attributes' => array_merge($item, array( + $menu[] = array( + 'attributes' => array_merge(array( 'label' => CRM_Utils_Array::value('name', $item), 'active' => 1, - 'parentID' => $parentId, - 'navID' => $navId, - )) + ), $item), ); - return true; - } else { + return TRUE; + } + else { // Find an recurse into the next level down - $found = false; + $found = FALSE; $path = explode('/', $path); $first = array_shift($path); foreach ($menu as $key => &$entry) { if ($entry['attributes']['name'] == $first) { - if (!$entry['child']) $entry['child'] = array(); + if (!isset($entry['child'])) { + $entry['child'] = array(); + } $found = _booking_civix_insert_navigation_menu($entry['child'], implode('/', $path), $item, $key); } } return $found; } } + +/** + * (Delegated) Implements hook_civicrm_navigationMenu(). + */ +function _booking_civix_navigationMenu(&$nodes) { + if (!is_callable(array('CRM_Core_BAO_Navigation', 'fixNavigationMenu'))) { + _booking_civix_fixNavigationMenu($nodes); + } +} + +/** + * Given a navigation menu, generate navIDs for any items which are + * missing them. + */ +function _booking_civix_fixNavigationMenu(&$nodes) { + $maxNavID = 1; + array_walk_recursive($nodes, function($item, $key) use (&$maxNavID) { + if ($key === 'navID') { + $maxNavID = max($maxNavID, $item); + } + }); + _booking_civix_fixNavigationMenuItems($nodes, $maxNavID, NULL); +} + +function _booking_civix_fixNavigationMenuItems(&$nodes, &$maxNavID, $parentID) { + $origKeys = array_keys($nodes); + foreach ($origKeys as $origKey) { + if (!isset($nodes[$origKey]['attributes']['parentID']) && $parentID !== NULL) { + $nodes[$origKey]['attributes']['parentID'] = $parentID; + } + // If no navID, then assign navID and fix key. + if (!isset($nodes[$origKey]['attributes']['navID'])) { + $newKey = ++$maxNavID; + $nodes[$origKey]['attributes']['navID'] = $newKey; + $nodes[$newKey] = $nodes[$origKey]; + unset($nodes[$origKey]); + $origKey = $newKey; + } + if (isset($nodes[$origKey]['child']) && is_array($nodes[$origKey]['child'])) { + _booking_civix_fixNavigationMenuItems($nodes[$origKey]['child'], $maxNavID, $nodes[$origKey]['attributes']['navID']); + } + } +} + +/** + * (Delegated) Implements hook_civicrm_alterSettingsFolders(). + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_alterSettingsFolders + */ +function _booking_civix_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) { + static $configured = FALSE; + if ($configured) { + return; + } + $configured = TRUE; + + $settingsDir = __DIR__ . DIRECTORY_SEPARATOR . 'settings'; + if (is_dir($settingsDir) && !in_array($settingsDir, $metaDataFolders)) { + $metaDataFolders[] = $settingsDir; + } +} + +/** + * (Delegated) Implements hook_civicrm_entityTypes(). + * + * Find any *.entityType.php files, merge their content, and return. + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_entityTypes + */ + +function _booking_civix_civicrm_entityTypes(&$entityTypes) { + $entityTypes = array_merge($entityTypes, array ( + )); +} diff --git a/booking.php b/booking.php index 0842c99c..4692bdde 100755 --- a/booking.php +++ b/booking.php @@ -1,29 +1,25 @@ 'booking', - 'count' => $count, - 'title' => 'Bookings', - 'weight' => 0, //we are at first tab - ); - $tab['url'] = CRM_Utils_System::url('civicrm/contact/view/booking', "reset=1&cid={$cid}&snippet=1&force=1", false, null, false); - $tabs[] = $tab; - + $count = CRM_Booking_BAO_Booking::getBookingContactCount($cid); //TODO Count number of booking and show on the tab + $tab = [ + 'id' => 'booking', + 'count' => $count, + 'title' => 'Bookings', + 'weight' => 0, //we are at first tab + ]; + $tab['url'] = CRM_Utils_System::url('civicrm/contact/view/booking', "reset=1&cid={$cid}&snippet=1&force=1", false, null, false); + $tabs[] = $tab; } - /** * Implementation of hook_civicrm_config */ @@ -48,41 +44,28 @@ function booking_civicrm_xmlMenu(&$files) { * Implementation of hook_civicrm_install */ function booking_civicrm_install() { - - require_once 'CRM/Utils/Migrate/Import.php'; - $import = new CRM_Utils_Migrate_Import( ); - - $extRoot = dirname( __FILE__ ) . DIRECTORY_SEPARATOR; - - $op = $extRoot . 'xml' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'OptionGroups.xml'; - - $import->run( $op ); - - return _booking_civix_civicrm_install(); + _booking_civix_civicrm_install(); } /** * Implementation of hook_civicrm_uninstall */ function booking_civicrm_uninstall() { - return _booking_civix_civicrm_uninstall(); + _booking_civix_civicrm_uninstall(); } /** * Implementation of hook_civicrm_enable */ function booking_civicrm_enable() { - // rebuild the menu so our path is picked up - require_once 'CRM/Core/Invoke.php'; - CRM_Core_Invoke::rebuildMenuAndCaches( ); - return _booking_civix_civicrm_enable(); + _booking_civix_civicrm_enable(); } /** * Implementation of hook_civicrm_disable */ function booking_civicrm_disable() { - return _booking_civix_civicrm_disable(); + _booking_civix_civicrm_disable(); } /** @@ -105,7 +88,7 @@ function booking_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) { * is installed, disabled, uninstalled. */ function booking_civicrm_managed(&$entities) { - return _booking_civix_civicrm_managed($entities); + _booking_civix_civicrm_managed($entities); } /** @@ -115,15 +98,14 @@ function booking_civicrm_queryObjects(&$queryObjects, $type) { if ($type == 'Contact') { $queryObjects[] = new CRM_Booking_BAO_Query(); } - elseif ($type == 'Report') {} } /** * Implementation of hook_civicrm_postProcess */ -function booking_civicrm_post( $op, $objectName, $objectId, &$objectRef ) { - if($objectName == 'Contribution'){ - if($op == 'delete'){ +function booking_civicrm_post($op, $objectName, $objectId, &$objectRef) { + if ($objectName == 'Contribution') { + if ($op == 'delete') { CRM_Core_DAO::executeQuery("DELETE FROM civicrm_booking_payment WHERE contribution_id = $objectId"); } } @@ -133,64 +115,70 @@ function booking_civicrm_post( $op, $objectName, $objectId, &$objectRef ) { * Implementation of hook_civicrm_entityTypes */ function booking_civicrm_entityTypes(&$entityTypes) { - $entityTypes[] = array( + $entityTypes[] = [ 'name' => 'AdhocCharges', 'class' => 'CRM_Booking_DAO_AdhocCharges', 'table' => 'civicrm_booking_adhoc_charges', - ); - $entityTypes[] = array( + ]; + $entityTypes[] = [ 'name' => 'AdhocChargesItem', 'class' => 'CRM_Booking_DAO_AdhocChargesItem', 'table' => 'civicrm_booking_adhoc_charges_item', - ); - $entityTypes[] = array( + ]; + $entityTypes[] = [ 'name' => 'Booking', 'class' => 'CRM_Booking_DAO_Booking', 'table' => 'civicrm_booking', - ); - $entityTypes[] = array( + ]; + $entityTypes[] = [ 'name' => 'BookingPayment', 'class' => 'CRM_Booking_DAO_Payment', 'table' => 'civicrm_booking_payment', - ); - $entityTypes[] = array( + ]; + $entityTypes[] = [ 'name' => 'Resource', 'class' => 'CRM_Booking_DAO_Resource', 'table' => 'civicrm_booking_resource', - ); - $entityTypes[] = array( + ]; + $entityTypes[] = [ 'name' => 'ResourceConfigOption', 'class' => 'CRM_Booking_DAO_ResourceConfigOption', 'table' => 'civicrm_booking_resource_config_option', - ); - $entityTypes[] = array( + ]; + $entityTypes[] = [ 'name' => 'ResourceConfigSet', 'class' => 'CRM_Booking_DAO_ResourceConfigSet', 'table' => 'civicrm_booking_resource_config_set', - ); - $entityTypes[] = array( + ]; + $entityTypes[] = [ 'name' => 'Slot', 'class' => 'CRM_Booking_DAO_Slot', 'table' => 'civicrm_booking_slot', - ); - $entityTypes[] = array( + ]; + $entityTypes[] = [ 'name' => 'SubSlot', 'class' => 'CRM_Booking_DAO_SubSlot', 'table' => 'civicrm_booking_sub_slot', - ); - $entityTypes[] = array( + ]; + $entityTypes[] = [ 'name' => 'Cancellation', 'class' => 'CRM_Booking_DAO_Cancellation', 'table' => 'civicrm_booking_cancellation' - ); + ]; } /** - * Implementation of hook_civicrm_merge + * Implements hook_civicrm_alterSettingsFolders(). */ -function booking_civicrm_merge ( $type, &$data, $mainId = NULL, $otherId = NULL, $tables = NULL ){ -if (!empty($mainId) && !empty($otherId) && $type == 'sqls'){ +function booking_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) { + _booking_civix_civicrm_alterSettingsFolders($metaDataFolders); +} +/** + * Implementation of hook_civicrm_merge + */ +function booking_civicrm_merge ($type, &$data, $mainId = NULL, $otherId = NULL, $tables = NULL) { + if (!empty($mainId) && !empty($otherId) && $type == 'sqls') { $query1 = " UPDATE civicrm_booking SET primary_contact_id=$mainId @@ -202,24 +190,13 @@ function booking_civicrm_merge ( $type, &$data, $mainId = NULL, $otherId = NULL, WHERE secondary_contact_id=$otherId; "; - require_once('CRM/Core/DAO.php'); - $dao = CRM_Core_DAO::executeQuery( $query1 ); - $dao = CRM_Core_DAO::executeQuery( $query2 ); - - } -} + $dao = CRM_Core_DAO::executeQuery($query1); + $dao = CRM_Core_DAO::executeQuery($query2); -function civibooking_getMenuKeyMax($menuArray) { - $max = array(max(array_keys($menuArray))); - foreach($menuArray as $v) { - if (!empty($v['child'])) { - $max[] = civibooking_getMenuKeyMax($v['child']); - } } - return max($max); } -function booking_civicrm_permission(&$permissions){ +function booking_civicrm_permission(&$permissions) { $prefix = E::ts('CiviBooking') . ': '; $permissions['administer CiviBooking'] = $prefix . E::ts('administer CiviBooking'); $permissions['create and update bookings'] = $prefix . E::ts('create and update bookings'); @@ -231,40 +208,40 @@ function booking_civicrm_permission(&$permissions){ * @see function _civicrm_api3_permissions for mentioned uppercase issue */ function booking_civicrm_alterAPIPermissions($entity, $action, &$params, &$permissions) { - $commonBookingAPIPermissions = array( - 'create' => array( + $commonBookingAPIPermissions = [ + 'create' => [ 'administer CiviBooking', - ), - 'delete' => array( + ], + 'delete' => [ 'administer CiviBooking', - ), - 'get' => array( - array( + ], + 'get' => [ + [ 'administer CiviBooking', 'create and update bookings', 'view all bookings', - ) - ), - 'update' => array( + ] + ], + 'update' => [ 'administer CiviBooking', - ), - ); + ], + ]; - $bookingEntities = array( + $bookingEntities = [ 'BookingPayment', 'Booking', 'Cancellation', 'Slot', 'SubSlot' - ); + ]; - $configEntities = array( + $configEntities = [ 'AdhocChargesItem', 'AdhocCharges', 'ResourceConfigOption', 'ResourceConfigSet', 'Resource', - ); + ]; // set common permissions foreach (array_merge($bookingEntities, $configEntities) as $entityName) { @@ -274,7 +251,7 @@ function booking_civicrm_alterAPIPermissions($entity, $action, &$params, &$permi //add custom permissions for create/update role foreach ($bookingEntities as $entityName) { - $permissionArray = array(array('administer CiviBooking', 'create and update bookings')); + $permissionArray = [['administer CiviBooking', 'create and update bookings']]; // permissions implementation needs lowercase entities $entityName = _civicrm_api_get_entity_name_from_camel($entityName); $permissions[$entityName]['create'] = $permissionArray; @@ -294,3 +271,14 @@ function booking_civicrm_apiWrappers(&$wrappers, $apiRequest) { $wrappers[] = new CRM_Booking_APIWrapper(); } } + +/** + * Implements hook_civicrm_navigationMenu(). + */ +function booking_civicrm_navigationMenu(&$menu) { + $menuItems = CRM_Booking_Upgrader::getMenuItems(); + foreach ($menuItems as $item) { + _booking_civix_insert_navigation_menu($menu, $item['parent_name'], $item); + } + _booking_civix_navigationMenu($menu); +} diff --git a/js/booking/add-sub-resource/app.js b/js/booking/add-sub-resource/app.js index e73dd956..20348746 100644 --- a/js/booking/add-sub-resource/app.js +++ b/js/booking/add-sub-resource/app.js @@ -1,5 +1,6 @@ CRM.BookingApp = new Backbone.Marionette.Application(); + // see http://lostechies.com/derickbailey/2012/04/17/managing-a-modal-dialog-with-backbone-and-marionette/ var ModalRegion = Backbone.Marionette.Region.extend({ el: "#crm-booking-dialog", diff --git a/js/booking/add-sub-resource/view.js b/js/booking/add-sub-resource/view.js index a8ced7a1..fffc419b 100755 --- a/js/booking/add-sub-resource/view.js +++ b/js/booking/add-sub-resource/view.js @@ -1,85 +1,85 @@ -(function ($, ts){ - -/* - * View classes belong to the second wizard screen of create/edit booking - */ -CRM.BookingApp.module('AddSubResource', function(AddSubResource, BookingApp, Backbone, Marionette, $, _) { - - var startDate; - var endDate; - var unlimitedTimeConfig; - var resourceTotal = new Array(); - var priceCache = new Array(); - - CRM.BookingApp.vent.on("update:resources", function(model) { - $('#sub_resources').val(JSON.stringify(model.toJSON())); - }); - - CRM.BookingApp.vent.on("render:price", function(model) { - $("#total_price").val(model.attributes.total_price); - var totalText = model.attributes.total_price; - try{ - if(model.attributes.total_price>=0){ - var totalText = model.attributes.total_price.toFixed(2); - } - }catch(err){} - $("#total-price-summary").text(totalText); - - $("#discount_amount").val(model.attributes.discount_amount); - $('#discount_amount_dummy').val(model.attributes.discount_amount); - - $("#sub_total").val(model.attributes.sub_total); - var subtotalText = model.attributes.sub_total; - try{ - var subtotalText = model.attributes.sub_total.toFixed(2); - }catch(err){} - $("#sub-total-summary").text(subtotalText); - - $('#adhoc_charge').val(model.attributes.adhoc_charges.total); - $('#ad-hoc-charge-summary').html(model.attributes.adhoc_charges.total); - }); - - CRM.BookingApp.vent.on("render:options", function(options) { - var select = options.context.$el.find(options.element); - if (select.is('[disabled]')) { - select.prop('disabled', false); - } - select.html(options.template({ - options : options.list, - first_option : options.first_option - })); - }); - - //Resource table view - AddSubResource.ResourceTableView = Backbone.Marionette.ItemView.extend({ - template: '#resource-table-template', - - initialize: function(){ - if ($.trim($("#sub_resources").val())) { - this.model.attributes = JSON.parse($.trim($("#sub_resources").val())); +(function ($, ts){ + + /* + * View classes belong to the second wizard screen of create/edit booking + */ + CRM.BookingApp.module('AddSubResource', function(AddSubResource, BookingApp, Backbone, Marionette, $, _) { + + var startDate; + var endDate; + var unlimitedTimeConfig; + var resourceTotal = []; + var priceCache = []; + + CRM.BookingApp.vent.on("update:resources", function(model) { + $('#sub_resources').val(JSON.stringify(model.toJSON())); + }); + + CRM.BookingApp.vent.on("render:price", function(model) { + $("#total_price").val(model.attributes.total_price); + var totalText = model.attributes.total_price; + try{ + if(model.attributes.total_price>=0){ + totalText = model.attributes.total_price.toFixed(2); + } + }catch(err){} + $("#total-price-summary").text(totalText); + + $("#discount_amount").val(model.attributes.discount_amount); + $('#discount_amount_dummy').val(model.attributes.discount_amount); + + $("#sub_total").val(model.attributes.sub_total); + var subtotalText = model.attributes.sub_total; + try{ + subtotalText = model.attributes.sub_total.toFixed(2); + }catch(err){} + $("#sub-total-summary").text(subtotalText); + + $('#adhoc_charge').val(model.attributes.adhoc_charges.total); + $('#ad-hoc-charge-summary').html(model.attributes.adhoc_charges.total); + }); + + CRM.BookingApp.vent.on("render:options", function(options) { + var select = options.context.$el.find(options.element); + if (select.is('[disabled]')) { + select.prop('disabled', false); } - this.model.attributes.total_price = $("#total_price").val(); - this.model.attributes.sub_total = $("#sub_total").val(); - //this.model.attributes.adhoc_charges = $("#adhoc_charge").val(); - this.model.attributes.discount_amount = $("#discount_amount").val(); - }, - - onRender: function(){ - var subtotal = 0; - var self = this; - //init the current price for each resource - this.$el.find("span[id^='resource-price-']").each(function(){ - var el = $(this); - self.model.attributes.resources[el.data('ref')] = el.text(); - }); - var items = []; - var template = _.template($('#sub-resource-row-template').html()); - _.each(this.model.get('sub_resources'), function (item, key){ - self.$el.find("#crm-booking-sub-resource-table-" + item.parent_ref_id).append(template(item)); - priceCache[item.ref_id] = item.price_estimate; - items.push(item); - }); - //if($.trim($("#sub_resources").val())) { + select.html(options.template({ + options : options.list, + first_option : options.first_option + })); + }); + + //Resource table view + AddSubResource.ResourceTableView = Backbone.Marionette.ItemView.extend({ + template: '#resource-table-template', + + initialize: function(){ + if ($.trim($("#sub_resources").val())) { + this.model.attributes = JSON.parse($.trim($("#sub_resources").val())); + } + this.model.attributes.total_price = $("#total_price").val(); + this.model.attributes.sub_total = $("#sub_total").val(); + //this.model.attributes.adhoc_charges = $("#adhoc_charge").val(); + this.model.attributes.discount_amount = $("#discount_amount").val(); + }, + + onRender: function(){ + var subtotal = 0; + var self = this; + //init the current price for each resource + this.$el.find("span[id^='resource-price-']").each(function(){ + var el = $(this); + self.model.attributes.resources[el.data('ref')] = el.text(); + }); + var items = []; + var template = _.template($('#sub-resource-row-template').html()); + _.each(this.model.get('sub_resources'), function (item, key){ + self.$el.find("#crm-booking-sub-resource-table-" + item.parent_ref_id).append(template(item)); + priceCache[item.ref_id] = item.price_estimate; + items.push(item); + }); + //if($.trim($("#sub_resources").val())) { this.$el.find("span[id^='resource-total-price-']").each(function(){ var el = $(this);/////////////////////////// var resourceTotalPrice = parseFloat(el.data('price')); @@ -88,7 +88,7 @@ CRM.BookingApp.module('AddSubResource', function(AddSubResource, BookingApp, Bac if(parseInt(item.parent_ref_id) === parseInt(el.data('ref'))){ resourceTotalPrice += parseFloat(item.price_estimate); } - + }); if(resourceTotalPrice != null){ subtotal += resourceTotalPrice; @@ -97,514 +97,506 @@ CRM.BookingApp.module('AddSubResource', function(AddSubResource, BookingApp, Bac self.$el.find('#crm-booking-sub-resource-row-' + el.data('ref')).show(); } }); - //} - this.model.attributes.sub_total = subtotal; - this.model.attributes.total_price = (subtotal - + parseFloat(this.model.get("adhoc_charges").total)) - - parseFloat(this.model.get("discount_amount")); - this.model.attributes.discount_amount = this.model.get("discount_amount"); - - unlimitedTimeConfig = timeConfig; - - var subTotalText = this.model.get('sub_total'); - var adhocText = this.model.get('adhoc_charges').total; - var discountText = this.model.get('discount_amount'); - var totalText = this.model.get('total_price'); - this.$el.find("#sub-total-summary").text(subTotalText.toFixed(2)); - this.$el.find("#ad-hoc-charge-summary").text(adhocText); - try{ - this.$el.find("#ad-hoc-charge-summary").text(adhocText,toFixed(2)); - }catch(err){} - this.$el.find("#discount_amount_dummy").val(discountText); - this.$el.find("#total-price-summary").text(totalText.toFixed(2)); - }, - events: { - 'click .add-sub-resource': 'addSubResource', - 'click .edit-sub-resource': 'editSubResource', - 'click .edit-adhoc-charge': 'editAdhocCharge', - 'click .collapsed' : 'toggleHiddenElement', - 'click .remove-sub-resource': 'removeSubResource', - //'keypress #discount_amount_dummy': 'addDiscountAmount', - 'keyup #discount_amount_dummy': 'addDiscountAmount', - //'keydown #discount_amount_dummy': 'addDiscountAmount' - }, - - addSubResource: function(e){ - var ref = $(e.currentTarget).data('ref');///////////////// - //resourceTotal[ref] = 0; - endDate = $(e.currentTarget).data('edate'); - startDate = $(e.currentTarget).data('sdate'); - var model = new CRM.BookingApp.Entities.AddSubResource({parent_ref_id:ref, time_required:startDate}); - var view = new AddSubResource.AddSubResourceModal({model: model, is_new: true}); - view.title = ts('Add Unlimited Resource'); - CRM.BookingApp.modal.show(view); - }, - - addDiscountAmount: function(e){ - var currentSubTotal = parseFloat(this.model.get('sub_total')); - var currentAdhocCharges = parseFloat(this.model.get('adhoc_charges').total); - - // Get the discount amount stripping out non-numeric characters - var sDiscountAmount = $(e.currentTarget).val().replace(/[^\d.-]/g, ''); - var fDiscountAmount = parseFloat(sDiscountAmount); - if (!_.isNumber(fDiscountAmount) || _.isNaN(fDiscountAmount)) { + //} + this.model.attributes.sub_total = subtotal; + var discountAmount = parseFloat(this.model.get("discount_amount")); + if (isNaN(discountAmount)) { discountAmount = 0; } + this.model.attributes.total_price = + (subtotal + parseFloat(this.model.get("adhoc_charges").total) - discountAmount); + this.model.attributes.discount_amount = this.model.get("discount_amount"); + + unlimitedTimeConfig = timeConfig; + + var subTotalText = this.model.get('sub_total'); + var adhocText = this.model.get('adhoc_charges').total; + var discountText = this.model.get('discount_amount'); + var totalText = this.model.get('total_price'); + this.$el.find("#sub-total-summary").text(subTotalText.toFixed(2)); + this.$el.find("#ad-hoc-charge-summary").text(adhocText); + try{ + this.$el.find("#ad-hoc-charge-summary").text(adhocText,toFixed(2)); + }catch(err){} + this.$el.find("#discount_amount_dummy").val(discountText); + this.$el.find("#total-price-summary").text(totalText.toFixed(2)); + }, + events: { + 'click .add-sub-resource': 'addSubResource', + 'click .edit-sub-resource': 'editSubResource', + 'click .edit-adhoc-charge': 'editAdhocCharge', + 'click .collapsed' : 'toggleHiddenElement', + 'click .remove-sub-resource': 'removeSubResource', + //'keypress #discount_amount_dummy': 'addDiscountAmount', + 'keyup #discount_amount_dummy': 'addDiscountAmount', + //'keydown #discount_amount_dummy': 'addDiscountAmount' + }, + + addSubResource: function(e){ + var ref = $(e.currentTarget).data('ref');///////////////// + //resourceTotal[ref] = 0; + endDate = $(e.currentTarget).data('edate'); + startDate = $(e.currentTarget).data('sdate'); + var model = new CRM.BookingApp.Entities.AddSubResource({parent_ref_id:ref, time_required:startDate}); + var view = new AddSubResource.AddSubResourceModal({model: model, is_new: true}); + view.title = ts('Add Unlimited Resource'); + CRM.BookingApp.modal.show(view); + }, + + addDiscountAmount: function(e){ + var currentSubTotal = parseFloat(this.model.get('sub_total')); + var currentAdhocCharges = parseFloat(this.model.get('adhoc_charges').total); + + // Get the discount amount stripping out non-numeric characters + var sDiscountAmount = $(e.currentTarget).val().replace(/[^\d.-]/g, ''); + var fDiscountAmount = parseFloat(sDiscountAmount); + if (!_.isNumber(fDiscountAmount) || _.isNaN(fDiscountAmount)) { fDiscountAmount = 0; sDiscountAmount = ''; - } + } - var newTotal = (currentSubTotal + currentAdhocCharges) - fDiscountAmount; - try{newTotal = newTotal.toFixed(2); }catch(err){} - this.model.set("total_price", newTotal); - this.model.set("discount_amount", sDiscountAmount); - CRM.BookingApp.vent.trigger('render:price', this.model ); - - }, - - editAdhocCharge: function(e) { - var model = new CRM.BookingApp.Entities.AdhocCharges({ - items : this.model.get('adhoc_charges').items, - note : this.model.get('adhoc_charges').note, - total : this.model.get('adhoc_charges').total - }); - var view = new AddSubResource.EditAdhocChargesModal({ - model : model - }); - view.title = ts('Edit Additional Charges'); - CRM.BookingApp.modal.show(view); - }, - - toggleHiddenElement: function(e){ - var row = $(e.currentTarget).data('ref'); - $('#crm-booking-sub-resource-row-' + row).toggle(); - }, - removeSubResource: function(e){ - var ref = $(e.currentTarget).data('ref'); - var parentRef = $(e.currentTarget).data('parent-ref'); - var price = $(e.currentTarget).data('price'); - $('#crm-booking-sub-resource-individual-row-' + ref).remove(); - delete this.model.attributes.sub_resources[ref]; - - var newResourcePrice = parseFloat(this.model.get("resources")[parentRef]) - parseFloat(price); - - this.model.attributes.resources[parentRef] = newResourcePrice; - resourceTotal[parentRef] -= parseFloat(price); - try{resourceTotal[parentRef] = resourceTotal[parentRef].toFixed(2);}catch(err){} - $("#resource-total-price-" + parentRef).text(resourceTotal[parentRef]); - var currentSubTotal = this.model.get('sub_total'); - var newSubTotal = parseFloat(this.model.get('sub_total') - parseFloat(price)); - var currentTotal = this.model.get('total_price'); - var newTotal = parseFloat(currentTotal) - parseFloat(price); - - this.model.set("sub_total", newSubTotal); - this.model.set("total_price", newTotal); - - CRM.BookingApp.vent.trigger('render:price', this.model , parentRef ); - CRM.BookingApp.vent.trigger('update:resources', this.model); - CRM.alert(ts(''), ts('Unlimited resource removed'), 'success'); - }, - - //when edit sub resource - editSubResource: function(e) { - var refId = $(e.currentTarget).data('ref'); //retrieve id from attribute data-ref - var parentRef = $(e.currentTarget).data('parent-ref'); //retrieve id from attribute data-parent-ref - var timeRequired = $(e.currentTarget).data('time-required'); //retrieve datetime from attribute data-time-required - selectedItem = this.model.attributes.sub_resources[refId]; - - //create backbone model form json object - var model = new CRM.BookingApp.Entities.AddSubResource({ - parent_ref_id : parentRef, - ref_id : refId, - resource: {id : selectedItem.resource.id, label :selectedItem.resource.label}, - configuration: selectedItem.configuration, - quantity: selectedItem.quantity, - time_required: timeRequired, - note: selectedItem.note, - price_estimate: selectedItem.price_estimate, - }); - //create backbone view - var view = new AddSubResource.AddSubResourceModal({ - model : model, - is_new: false - }); - view.title = ts('Edit unlimited resource'); - CRM.BookingApp.modal.show(view); - } + var newTotal = (currentSubTotal + currentAdhocCharges) - fDiscountAmount; + try{newTotal = newTotal.toFixed(2); }catch(err){} + this.model.set("total_price", newTotal); + this.model.set("discount_amount", sDiscountAmount); + CRM.BookingApp.vent.trigger('render:price', this.model ); - }); + }, - //Sub(Unlimited) resource dialog view - AddSubResource.AddSubResourceModal = BookingApp.Common.Views.BookingProcessModal.extend({ - template: "#add-sub-resource-template", - initialize: function(options){ - this.isNew = options.is_new; - }, - events: { - 'click #add-to-basket': 'addSubResource', - 'change #resource_select': 'getConfigurations', - 'change #configuration_select': 'updatePriceEstmate', - 'keypress #quantity': 'updatePriceEstmate', - 'keyup #quantity': 'updatePriceEstmate', - 'keydown #quantity': 'updatePriceEstmate', - }, - onRender: function(){ - BookingApp.Common.Views.BookingProcessModal.prototype.onRender.apply(this, arguments); - - var thisView = this; //set 'this' object for calling inside callback function - this.$el.find('#loading').show(); - - - - var initsdate = moment(this.model.get('time_required'), "YYYY-MM-DD HH:mm:ss"); - var timeTxt = [initsdate.hours() < 10 ? '0' + initsdate.hours() : initsdate.hours(), ":", initsdate.minute() < 10 ? '0' + initsdate.minute() : initsdate.minute()].join(""); - - //set the formatted months - var month=new Array(); - month[0]="01"; - month[1]="02"; - month[2]="03"; - month[3]="04"; - month[4]="05"; - month[5]="06"; - month[6]="07"; - month[7]="08"; - month[8]="09"; - month[9]="10"; - month[10]="11"; - month[11]="12"; - var dateTxt = [ initsdate.format("DD"),"/", month[initsdate.months()],"/", initsdate.years()].join(""); - this.$el.find("#required_date").val(dateTxt); - this.$el.find("#required_time").val(timeTxt); - - CRM.api('Resource', 'get', {'sequential': 1, 'is_unlimited': 1, 'is_deleted': 0, 'is_active': 1}, - {success: function(data) { - thisView.template = _.template($('#add-sub-resource-template').html()); - //var configValue = CRM_Booking_BAO_BookingConfig::getConfig(); - - thisView.$el.find("#required_date").datepicker({changeMonth: true, changeYear: true, dateFormat: 'dd/mm/yy'}); - thisView.$el.find('#required_time').timeEntry({show24Hours: true}).change(function() { - var log = $('#log'); - log.val(log.val() + ($('#defaultEntry').val() || 'blank') + '\n'); - }); + editAdhocCharge: function(e) { + var model = new CRM.BookingApp.Entities.AdhocCharges({ + items : this.model.get('adhoc_charges').items, + note : this.model.get('adhoc_charges').note, + total : this.model.get('adhoc_charges').total + }); + var view = new AddSubResource.EditAdhocChargesModal({ + model : model + }); + view.title = ts('Edit Additional Charges'); + CRM.BookingApp.modal.show(view); + }, + + toggleHiddenElement: function(e){ + var row = $(e.currentTarget).data('ref'); + $('#crm-booking-sub-resource-row-' + row).toggle(); + }, + removeSubResource: function(e){ + var ref = $(e.currentTarget).data('ref'); + var parentRef = $(e.currentTarget).data('parent-ref'); + var price = $(e.currentTarget).data('price'); + $('#crm-booking-sub-resource-individual-row-' + ref).remove(); + delete this.model.attributes.sub_resources[ref]; + + var newResourcePrice = parseFloat(this.model.get("resources")[parentRef]) - parseFloat(price); + this.model.attributes.resources[parentRef] = newResourcePrice; + + resourceTotal[parentRef] -= parseFloat(price); + try{resourceTotal[parentRef] = resourceTotal[parentRef].toFixed(2);}catch(err){} + $("#resource-total-price-" + parentRef).text(resourceTotal[parentRef]); + var currentSubTotal = this.model.get('sub_total'); + var newSubTotal = parseFloat(this.model.get('sub_total') - parseFloat(price)); + var currentTotal = this.model.get('total_price'); + var newTotal = parseFloat(currentTotal) - parseFloat(price); + + this.model.set("sub_total", newSubTotal); + this.model.set("total_price", newTotal); + + CRM.BookingApp.vent.trigger('render:price', this.model , parentRef ); + CRM.BookingApp.vent.trigger('update:resources', this.model); + CRM.alert(ts(''), ts('Unlimited resource removed'), 'success'); + }, + + //when edit sub resource + editSubResource: function(e) { + var refId = $(e.currentTarget).data('ref'); //retrieve id from attribute data-ref + var parentRef = $(e.currentTarget).data('parent-ref'); //retrieve id from attribute data-parent-ref + var timeRequired = $(e.currentTarget).data('time-required'); //retrieve datetime from attribute data-time-required + selectedItem = this.model.attributes.sub_resources[refId]; + + //create backbone model form json object + var model = new CRM.BookingApp.Entities.AddSubResource({ + parent_ref_id : parentRef, + ref_id : refId, + resource: {id : selectedItem.resource.id, label :selectedItem.resource.label}, + configuration: selectedItem.configuration, + quantity: selectedItem.quantity, + time_required: timeRequired, + note: selectedItem.note, + price_estimate: selectedItem.price_estimate, + }); + //create backbone view + var view = new AddSubResource.AddSubResourceModal({ + model : model, + is_new: false + }); + view.title = ts('Edit unlimited resource'); + CRM.BookingApp.modal.show(view); + } + + }); + + //Sub(Unlimited) resource dialog view + AddSubResource.AddSubResourceModal = BookingApp.Common.Views.BookingProcessModal.extend({ + template: "#add-sub-resource-template", + initialize: function(options){ + this.isNew = options.is_new; + }, + events: { + 'click #add-to-basket': 'addSubResource', + 'change #resource_select': 'getConfigurations', + 'change #configuration_select': 'updatePriceEstmate', + 'keypress #quantity': 'updatePriceEstmate', + 'keyup #quantity': 'updatePriceEstmate', + 'keydown #quantity': 'updatePriceEstmate', + }, + onRender: function(){ + BookingApp.Common.Views.BookingProcessModal.prototype.onRender.apply(this, arguments); + + var thisView = this; //set 'this' object for calling inside callback function + this.$el.find('#loading').show(); + + + + var initsdate = moment(this.model.get('time_required'), "YYYY-MM-DD HH:mm:ss"); + var timeTxt = [initsdate.hours() < 10 ? '0' + initsdate.hours() : initsdate.hours(), ":", initsdate.minute() < 10 ? '0' + initsdate.minute() : initsdate.minute()].join(""); + + //set the formatted months + var month=new ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']; + var dateTxt = [ initsdate.format("DD"),"/", month[initsdate.months()],"/", initsdate.years()].join(""); + this.$el.find("#required_date").val(dateTxt); + this.$el.find("#required_time").val(timeTxt); + + CRM.api3('Resource', 'get', {'sequential': 1, 'is_unlimited': 1, 'is_deleted': 0, 'is_active': 1}, + {success: function(data) { + thisView.template = _.template($('#add-sub-resource-template').html()); + //var configValue = CRM_Booking_BAO_BookingConfig::getConfig(); + + thisView.$el.find("#required_date").datepicker({changeMonth: true, changeYear: true, dateFormat: 'dd/mm/yy'}); + thisView.$el.find('#required_time').timeEntry({show24Hours: true}).change(function() { + var log = $('#log'); + log.val(log.val() + ($('#defaultEntry').val() || 'blank') + '\n'); + }); - //thisView.resources = data.values; - var tpl = _.template($('#select-option-template').html()); - var params = { + //thisView.resources = data.values; + var tpl = _.template($('#select-option-template').html()); + var params = { context: thisView, template: tpl, list: data.values, element: "#resource_select", first_option: ['- ', ts('select resource'), ' -'].join("") + }; + CRM.BookingApp.vent.trigger("render:options", params); + + if(thisView.isNew == false){ + //set values + thisView.$el.find("#resource_select").val(thisView.model.get('resource').id); + //set configuration option value + thisView.$el.find("#configuration_select").attr('data-selected-id',thisView.model.get('configuration').id); + thisView.getConfigurations(); //call inside callback function + thisView.$el.find("#quantity").val(thisView.model.get('quantity')); + thisView.$el.find("#sub-resource-note").val(thisView.model.get('note')); + thisView.$el.find("#price-estimate").html(thisView.model.get('price_estimate')); + + thisView.$el.find("#quantity").prop('disabled', false); //enable quantity input text + } + thisView.$el.find('#loading').hide(); + thisView.$el.find('#content').show(); } - CRM.BookingApp.vent.trigger("render:options", params); - - if(thisView.isNew == false){ - //set values - thisView.$el.find("#resource_select").val(thisView.model.get('resource').id); - //set configuration option value - thisView.$el.find("#configuration_select").attr('data-selected-id',thisView.model.get('configuration').id); - thisView.getConfigurations(); //call inside callback function - thisView.$el.find("#quantity").val(thisView.model.get('quantity')); - thisView.$el.find("#sub-resource-note").val(thisView.model.get('note')); - thisView.$el.find("#price-estimate").html(thisView.model.get('price_estimate')); - - thisView.$el.find("#quantity").prop('disabled', false); //enable quantity input text - } - thisView.$el.find('#loading').hide(); - thisView.$el.find('#content').show(); } - } - ); - }, - - beforeClose: function() {this.$('form').find("#required_date").datepicker("destroy");}, - - /** - * Define form validation rules - * - * @param View view the view for which validation rules are created - * @param Object r the validation rules for the view - */ - onValidateRulesCreate: function(view, r) { + ); + }, + + beforeClose: function() {this.$('form').find("#required_date").datepicker("destroy");}, + + /** + * Define form validation rules + * + * @param View view the view for which validation rules are created + * @param Object r the validation rules for the view + */ + onValidateRulesCreate: function(view, r) { $.validator.addMethod("withinValidTime", function(value, element) { - var dateVals = $("#required_date").val().split("/"); - var timeVals = $("#required_time").val().split(":"); - var requiredDate = new Date(dateVals[2],dateVals[1]-1,dateVals[0],timeVals[0],timeVals[1]); - var minDate = moment(startDate, "YYYY-MM-DD HH:mm:ss"); - var maxDate = moment(endDate, "YYYY-MM-DD HH:mm:ss"); - if (unlimitedTimeConfig==0){ - return true; - }else{ - var val = requiredDate>=minDate && requiredDate<=maxDate; - return val; - } + var dateVals = $("#required_date").val().split("/"); + var timeVals = $("#required_time").val().split(":"); + var requiredDate = new Date(dateVals[2],dateVals[1]-1,dateVals[0],timeVals[0],timeVals[1]); + var minDate = moment(startDate, "YYYY-MM-DD HH:mm:ss"); + var maxDate = moment(endDate, "YYYY-MM-DD HH:mm:ss"); + if (unlimitedTimeConfig==0){ + return true; + }else{ + return ((requiredDate>=minDate) && (requiredDate<=maxDate)); + } }, ts("Please select the date and time during the valid booking time.")); - _.extend(r.rules, { - resource_select: { - required: true - }, - configuration_select: { - required: true - }, - "required_date": { - required: true, + _.extend(r.rules, { + resource_select: { + required: true + }, + configuration_select: { + required: true + }, + "required_date": { + required: true, "withinValidTime": true - }, - quantity: { - required: true, - digits: true - }, - }); - }, - //calcualte price - updatePriceEstmate: function(e){ - var quantitySelector = this.$el.find('#quantity'); - if(e.type == 'change'){ - var configSelect = this.$el.find('#configuration_select'); - if(configSelect.val() !== ''){ - configSelect.find(':selected').data('price'); - var price = configSelect.find(':selected').data('price'); - this.model.set('configuration', {id: configSelect.val(), label: configSelect.find(':selected').text(), price: price}); - quantitySelector.prop('disabled', false); - }else{ - qualitySelector.prop('disabled', true); - quantitySelector.val(''); + }, + quantity: { + required: true, + digits: true + }, + }); + }, + //calcualte price + updatePriceEstmate: function(e){ + var quantitySelector = this.$el.find('#quantity'); + if(e.type === 'change'){ + var configSelect = this.$el.find('#configuration_select'); + if(configSelect.val() !== ''){ + configSelect.find(':selected').data('price'); + var price = configSelect.find(':selected').data('price'); + this.model.set('configuration', {id: configSelect.val(), label: configSelect.find(':selected').text(), price: price}); + quantitySelector.prop('disabled', false); + }else{ + qualitySelector.prop('disabled', true); + quantitySelector.val(''); + } } - } - var configPrice = this.model.get('configuration').price - var quantity = quantitySelector.val(); - if(CRM.BookingApp.Utils.isPositiveInteger(quantity)){ - var priceEstimate = quantity * configPrice; - this.model.set('quantity', quantity); - this.model.set('price_estimate', priceEstimate.toFixed(2)); - this.$el.find('#price-estimate').html(priceEstimate.toFixed(2)); - } - }, - - //render configuration options - getConfigurations: function(e){ - selectedVal = $('#resource_select').val(); - if(selectedVal !== ""){ - var params = { - id: selectedVal, - sequential: 1, - 'api.resource_config_set.get': { - id: '$value.set_id', + var configPrice = this.model.get('configuration').price; + var quantity = quantitySelector.val(); + if(CRM.BookingApp.Utils.isPositiveInteger(quantity)){ + var priceEstimate = quantity * configPrice; + this.model.set('quantity', quantity); + this.model.set('price_estimate', priceEstimate.toFixed(2)); + this.$el.find('#price-estimate').html(priceEstimate.toFixed(2)); + } + }, + + //render configuration options + getConfigurations: function(e){ + selectedVal = $('#resource_select').val(); + var params; + if(selectedVal !== ""){ + params = { + id: selectedVal, + sequential: 1, + 'api.resource_config_set.get': { + id: '$value.set_id', + is_active: 1, + is_deleted: 0, + 'api.resource_config_option.get': { + set_id: '$value.id', is_active: 1, is_deleted: 0, - 'api.resource_config_option.get': { - set_id: '$value.id', - is_active: 1, - is_deleted: 0, - 'api.option_group.get':{ - name: 'booking_size_unit', - }, - 'api.option_value.get':{ - value: '$value.unit_id', - sequential: 1, - option_group_id: '$value.api.option_group.get.id' - } + 'api.option_group.get':{ + name: 'booking_size_unit', + }, + 'api.option_value.get':{ + value: '$value.unit_id', + sequential: 1, + option_group_id: '$value.api.option_group.get.id' } } - }; - this.$el.find('#config-loading').show(); - this.$el.find('#configuration_select').hide(); - var self = this; - CRM.api('Resource', 'get', params, - { context: self, - success: function(data) { - var resource = data['values']['0']; - var configSet = data['values']['0']['api.resource_config_set.get']; - if(configSet.count !== 1){ - var url = CRM.url('civicrm/admin/resource/config_set', { - reset: 1, - action: 'update', - id: resource.id - }); - CRM.alert(ts(''), ts('Your resource configuration set is disabled.') - + ' ' + ' ' + ts('Click here to edit configuration set.') + ' ', 'error'); - } - else if(configSet['values']['0']['api.resource_config_option.get'].count < 1){ - var url = CRM.url('civicrm/admin/resource/config_set/config_option', { - reset: 1, - sid: configSet['values']['0'].id - }); - CRM.alert(ts(''), ts('Your resource configuration options are all disabled or none have been created.') - + ' ' + ' ' + ts('Click here to edit or create options.') + ' ', 'error'); } - else{ - var options = data['values']['0']['api.resource_config_set.get']['values']['0']['api.resource_config_option.get']['values']; - self.model.set('resource', {id: resource.id, label: resource.label}); - var params = { - context: self, - template: _.template($('#select-config-option-template').html()), - list: options, - element: "#configuration_select", - first_option: '- ' + ts('select configuration') + ' -' - } - CRM.BookingApp.vent.trigger("render:options", params); - //set configuration options for edit mode of subresource view - var configSelectedId = this.$el.find('#configuration_select').data('selected-id'); //retrieve data from data-selected-id attribute - if(configSelectedId != 'undefined'){ - this.$el.find('#configuration_select').val(configSelectedId); + }; + this.$el.find('#config-loading').show(); + this.$el.find('#configuration_select').hide(); + var self = this; + CRM.api3('Resource', 'get', params, + { context: self, + success: function(data) { + var resource = data['values']['0']; + var configSet = data['values']['0']['api.resource_config_set.get']; + var url = ''; + if(configSet.count !== 1){ + url = CRM.url('civicrm/admin/resource/config_set', { + reset: 1, + action: 'update', + id: resource.id + }); + CRM.alert(ts(''), ts('Your resource configuration set is disabled.') + + ' ' + ' ' + ts('Click here to edit configuration set.') + ' ', 'error'); + } + else if(configSet['values']['0']['api.resource_config_option.get'].count < 1){ + url = CRM.url('civicrm/admin/resource/config_set/config_option', { + reset: 1, + sid: configSet['values']['0'].id + }); + CRM.alert(ts(''), ts('Your resource configuration options are all disabled or none have been created.') + + ' ' + ' ' + ts('Click here to edit or create options.') + ' ', 'error'); + } + else{ + var options = data['values']['0']['api.resource_config_set.get']['values']['0']['api.resource_config_option.get']['values']; + self.model.set('resource', {id: resource.id, label: resource.label}); + var params = { + context: self, + template: _.template($('#select-config-option-template').html()), + list: options, + element: "#configuration_select", + first_option: '- ' + ts('select configuration') + ' -' + }; + CRM.BookingApp.vent.trigger("render:options", params); + //set configuration options for edit mode of subresource view + var configSelectedId = this.$el.find('#configuration_select').data('selected-id'); //retrieve data from data-selected-id attribute + if(configSelectedId !== 'undefined'){ + this.$el.find('#configuration_select').val(configSelectedId); + } + this.$el.find('#config-loading').hide(); + this.$el.find('#configuration_select').show(); + } } - this.$el.find('#config-loading').hide(); - this.$el.find('#configuration_select').show(); - } - } - }); - }else{ - var params = { - context:this, - template: _.template($('#select-config-option-template').html()), - list: new Array(), - element: "#configuration_select", - first_option: '- ' + ts('select configuration') + ' -'} - CRM.BookingApp.vent.trigger("render:options", params); - this.$el.find('#configuration_select').prop('disabled', true); - } - }, - - //save sub-resource - addSubResource: function(e){ - e.preventDefault(); - if (!this.$('form').valid()) { - var errors = this.$('form').validate().errors(); - this.onRenderError(errors); - return false; - } - this.$('form').find("#required_date").datepicker("destroy"); - this.model.set('note', this.$el.find('#sub-resource-note').val()); - var dateVals = this.$el.find("#required_date").val().split("/"); - var timeVals = this.$el.find("#required_time").val().split(":"); - var requiredDate = new Date(dateVals[2],dateVals[1]-1,dateVals[0],timeVals[0],timeVals[1]); - var timeRequired = moment(requiredDate).format("YYYY-M-D HH:mm"); - this.model.set('time_required', timeRequired); - - var parentRefId = this.model.get('parent_ref_id'); - - var refId = null; - if(this.isNew){ - refId = CRM.BookingApp.Utils.getCurrentUnixTimstamp(); - this.model.set('ref_id', refId); - }else{ - refId = this.model.get('ref_id'); - } + }); + }else{ + params = { + context:this, + template: _.template($('#select-config-option-template').html()), + list: [], + element: "#configuration_select", + first_option: '- ' + ts('select configuration') + ' -'}; + CRM.BookingApp.vent.trigger("render:options", params); + this.$el.find('#configuration_select').prop('disabled', true); + } + }, + + //save sub-resource + addSubResource: function(e){ + e.preventDefault(); + if (!this.$('form').valid()) { + var errors = this.$('form').validate().errors(); + this.onRenderError(errors); + return false; + } + this.$('form').find("#required_date").datepicker("destroy"); + this.model.set('note', this.$el.find('#sub-resource-note').val()); + var dateVals = this.$el.find("#required_date").val().split("/"); + var timeVals = this.$el.find("#required_time").val().split(":"); + var requiredDate = new Date(dateVals[2],dateVals[1]-1,dateVals[0],timeVals[0],timeVals[1]); + var timeRequired = moment(requiredDate).format("YYYY-M-D HH:mm"); + this.model.set('time_required', timeRequired); - var template = _.template($('#sub-resource-row-template').html()); + var parentRefId = this.model.get('parent_ref_id'); - //ui update - if(this.isNew){ - $('#crm-booking-sub-resource-table-' + parentRefId).find('tbody').append(template(this.model.toJSON())); - }else{ - $('#crm-booking-sub-resource-individual-row-'+refId).replaceWith(template(this.model.toJSON())); - } - $('#crm-booking-sub-resource-row-' + parentRefId).show(); - var resourceRefId = this.model.get("parent_ref_id"); - var priceEstimate = this.model.get("price_estimate"); - var subResourceRefId = this.model.get("ref_id"); - - var subResourceModel = CRM.BookingApp.main.currentView.model; - subResourceModel.attributes.sub_resources[refId] = this.model.toJSON(); - - var currentSubTotal = subResourceModel.get('sub_total'); - var newSubTotal = parseFloat(priceEstimate) + parseFloat(subResourceModel.get('sub_total')); - subResourceModel.set("sub_total", newSubTotal); - - var currentTotal = subResourceModel.get('total_price'); - var newTotal = (parseFloat(currentTotal) - parseFloat(currentSubTotal)) + parseFloat(newSubTotal); - subResourceModel.set("total_price", newTotal); - - var currentResourceTotal = resourceTotal[resourceRefId]; - - - if(this.isNew){ - var resourceTotalPrice = parseFloat(currentResourceTotal) + parseFloat(priceEstimate); - priceCache[subResourceRefId] = parseFloat(priceEstimate); - }else{ - var resourceTotalPrice = parseFloat(currentResourceTotal) + parseFloat(priceEstimate) - priceCache[subResourceRefId]; - subResourceModel.attributes.sub_total = subResourceModel.attributes.sub_total - priceCache[subResourceRefId]; - subResourceModel.attributes.total_price = subResourceModel.attributes.total_price - priceCache[subResourceRefId]; - priceCache[subResourceRefId] = parseFloat(priceEstimate); - } - resourceTotal[resourceRefId] = resourceTotalPrice; - subResourceModel.attributes.resources[resourceRefId] = resourceTotalPrice.toFixed(2); - //set total price for resource row - $("#resource-total-price-" + resourceRefId).text(subResourceModel.attributes.resources[resourceRefId]); - CRM.BookingApp.vent.trigger('render:price', subResourceModel, resourceRefId ); - CRM.BookingApp.vent.trigger('update:resources', subResourceModel); - CRM.BookingApp.modal.close(this); - }, + var refId = null; + if(this.isNew){ + refId = CRM.BookingApp.Utils.getCurrentUnixTimstamp(); + this.model.set('ref_id', refId); + }else{ + refId = this.model.get('ref_id'); + } - }); + var template = _.template($('#sub-resource-row-template').html()); - //Additaional charges dialog view - AddSubResource.EditAdhocChargesModal = BookingApp.Common.Views.BookingProcessModal.extend({ - template: "#edit-adhoc-charges-template", - className: "modal-dialog", - onRender: function(){ - var thisView = this; - _.each(this.model.get('items'), function(item){ - thisView.$el.find('#' + item.name).html(item.item_price); - thisView.$el.find('input[name="' + item.name + '"]').val(item.quantity); - }); - this.$el.find('#adhoc-charges-note').val(this.model.get('note')); - this.$el.find('#total-adhoc-charges').html(this.model.get('total')); - BookingApp.Common.Views.BookingProcessModal.prototype.onRender.apply(this, arguments); - }, - events: { - 'keypress .item': 'updatePrice', - 'keyup .item': 'updatePrice', - 'keydown .item': 'updatePrice', - 'click #update-adhoc-charges': 'updateAdhocCharges', - }, - updatePrice: function(e){ - var el = $(e.currentTarget); - var itemId = el.data('id'); - var price = el.data('price'); - var quantity = el.val(); - var name = el.attr('name'); - if(CRM.BookingApp.Utils.isPositiveInteger(quantity)){ - var itemPrice = parseFloat(price) * parseFloat(quantity); - this.$el.find('#'+ name).html(parseFloat(itemPrice).toFixed(2)); - var item = {item_id: itemId, name: name, price: price, quantity: quantity, item_price: itemPrice} - this.model.attributes.items[itemId] = item; - }else{ - this.$el.find('#'+ name).html(0); - this.$el.find('input[name="'+ name + '"]').val(''); - delete this.model.attributes.items[itemId]; - } - var items = this.model.get('items'); - var total = 0.0; - _.each(items,function(item){ - total = parseFloat(total) + parseFloat(item.item_price); - }); - this.$el.find('#total-adhoc-charges').html(total.toFixed(2)); - this.model.set('total', total.toFixed(2)); - }, - updateAdhocCharges: function(e){ - e.preventDefault(); - var subResourceModel = CRM.BookingApp.main.currentView.model; - this.model.set('note',this.$el.find('#adhoc-charges-note').val() ); - var adhocChargesTotal = this.model.get('total'); - //console.log(adhocChargesTotal); - subResourceModel.set('adhoc_charges', this.model.attributes); - var currentTotal = subResourceModel.get('sub_total'); - var discountAmount = subResourceModel.get('discount_amount'); - if(CRM.BookingApp.Utils.isPositiveNumber(discountAmount)){ - var newTotal = (parseFloat(adhocChargesTotal) + parseFloat(currentTotal)) - parseFloat(discountAmount); - }else{ - var newTotal = (parseFloat(adhocChargesTotal) + parseFloat(currentTotal)) - 0; + //ui update + if(this.isNew){ + $('#crm-booking-sub-resource-table-' + parentRefId).find('tbody').append(template(this.model.toJSON())); + }else{ + $('#crm-booking-sub-resource-individual-row-'+refId).replaceWith(template(this.model.toJSON())); + } + $('#crm-booking-sub-resource-row-' + parentRefId).show(); + var resourceRefId = this.model.get("parent_ref_id"); + var priceEstimate = this.model.get("price_estimate"); + var subResourceRefId = this.model.get("ref_id"); + + var subResourceModel = CRM.BookingApp.main.currentView.model; + subResourceModel.attributes.sub_resources[refId] = this.model.toJSON(); + + var currentSubTotal = subResourceModel.get('sub_total'); + var newSubTotal = parseFloat(priceEstimate) + parseFloat(subResourceModel.get('sub_total')); + subResourceModel.set("sub_total", newSubTotal); + + var currentTotal = subResourceModel.get('total_price'); + var newTotal = (parseFloat(currentTotal) - parseFloat(currentSubTotal)) + parseFloat(newSubTotal); + subResourceModel.set("total_price", newTotal); + + var currentResourceTotal = resourceTotal[resourceRefId]; + + + var resourceTotalPrice = 0; + if(this.isNew){ + resourceTotalPrice = parseFloat(currentResourceTotal) + parseFloat(priceEstimate); + priceCache[subResourceRefId] = parseFloat(priceEstimate); + }else{ + resourceTotalPrice = parseFloat(currentResourceTotal) + parseFloat(priceEstimate) - priceCache[subResourceRefId]; + subResourceModel.attributes.sub_total = subResourceModel.attributes.sub_total - priceCache[subResourceRefId]; + subResourceModel.attributes.total_price = subResourceModel.attributes.total_price - priceCache[subResourceRefId]; + priceCache[subResourceRefId] = parseFloat(priceEstimate); + } + resourceTotal[resourceRefId] = resourceTotalPrice; + subResourceModel.attributes.resources[resourceRefId] = resourceTotalPrice.toFixed(2); + //set total price for resource row + $("#resource-total-price-" + resourceRefId).text(subResourceModel.attributes.resources[resourceRefId]); + CRM.BookingApp.vent.trigger('render:price', subResourceModel, resourceRefId ); + CRM.BookingApp.vent.trigger('update:resources', subResourceModel); + CRM.BookingApp.modal.close(this); + }, + + }); + + //Additaional charges dialog view + AddSubResource.EditAdhocChargesModal = BookingApp.Common.Views.BookingProcessModal.extend({ + template: "#edit-adhoc-charges-template", + className: "modal-dialog", + onRender: function(){ + var thisView = this; + _.each(this.model.get('items'), function(item){ + thisView.$el.find('#' + item.name).html(item.item_price); + thisView.$el.find('input[name="' + item.name + '"]').val(item.quantity); + }); + this.$el.find('#adhoc-charges-note').val(this.model.get('note')); + this.$el.find('#total-adhoc-charges').html(this.model.get('total')); + BookingApp.Common.Views.BookingProcessModal.prototype.onRender.apply(this, arguments); + }, + events: { + 'keypress .item': 'updatePrice', + 'keyup .item': 'updatePrice', + 'keydown .item': 'updatePrice', + 'click #update-adhoc-charges': 'updateAdhocCharges', + }, + updatePrice: function(e){ + var el = $(e.currentTarget); + var itemId = el.data('id'); + var price = el.data('price'); + var quantity = el.val(); + var name = el.attr('name'); + if(CRM.BookingApp.Utils.isPositiveInteger(quantity)){ + var itemPrice = parseFloat(price) * parseFloat(quantity); + this.$el.find('#'+ name).html(parseFloat(itemPrice).toFixed(2)); + var item = {item_id: itemId, name: name, price: price, quantity: quantity, item_price: itemPrice}; + this.model.attributes.items[itemId] = item; + }else{ + this.$el.find('#'+ name).html(0); + this.$el.find('input[name="'+ name + '"]').val(''); + delete this.model.attributes.items[itemId]; + } + var items = this.model.get('items'); + var total = 0.0; + _.each(items,function(item){ + total = parseFloat(total) + parseFloat(item.item_price); + }); + this.$el.find('#total-adhoc-charges').html(total.toFixed(2)); + this.model.set('total', total.toFixed(2)); + }, + updateAdhocCharges: function(e){ + e.preventDefault(); + var subResourceModel = CRM.BookingApp.main.currentView.model; + this.model.set('note',this.$el.find('#adhoc-charges-note').val() ); + var adhocChargesTotal = this.model.get('total'); + //console.log(adhocChargesTotal); + subResourceModel.set('adhoc_charges', this.model.attributes); + var currentTotal = subResourceModel.get('sub_total'); + var discountAmount = subResourceModel.get('discount_amount'); + var newTotal = 0; + if(CRM.BookingApp.Utils.isPositiveNumber(discountAmount)){ + newTotal = (parseFloat(adhocChargesTotal) + parseFloat(currentTotal)) - parseFloat(discountAmount); + }else{ + newTotal = (parseFloat(adhocChargesTotal) + parseFloat(currentTotal)) - 0; + } + subResourceModel.set("total_price", parseFloat(newTotal).toFixed(2)); + CRM.BookingApp.vent.trigger('render:price', subResourceModel); + CRM.BookingApp.vent.trigger('update:resources', subResourceModel); + //console.log(subResourceModel.attributes); + CRM.BookingApp.modal.close(this); } - subResourceModel.set("total_price", parseFloat(newTotal).toFixed(2)); - CRM.BookingApp.vent.trigger('render:price', subResourceModel); - CRM.BookingApp.vent.trigger('update:resources', subResourceModel); - //console.log(subResourceModel.attributes); - CRM.BookingApp.modal.close(this); - } - }); + }); -}); + }); }(CRM.$, CRM.ts('uk.co.compucorp.civicrm.booking'))); diff --git a/sql/civibooking_install.sql b/sql/auto_install.sql similarity index 62% rename from sql/civibooking_install.sql rename to sql/auto_install.sql index 45fa3160..f6eea20e 100644 --- a/sql/civibooking_install.sql +++ b/sql/auto_install.sql @@ -1,22 +1,94 @@ +-- +--------------------------------------------------------------------+ +-- | Copyright CiviCRM LLC. All rights reserved. | +-- | | +-- | This work is published under the GNU AGPLv3 license with some | +-- | permitted exceptions and without any warranty. For full license | +-- | and copyright information, see https://civicrm.org/licensing | +-- +--------------------------------------------------------------------+ +-- +-- Generated from schema.tpl +-- DO NOT EDIT. Generated by CRM_Core_CodeGen +-- + + +-- +--------------------------------------------------------------------+ +-- | Copyright CiviCRM LLC. All rights reserved. | +-- | | +-- | This work is published under the GNU AGPLv3 license with some | +-- | permitted exceptions and without any warranty. For full license | +-- | and copyright information, see https://civicrm.org/licensing | +-- +--------------------------------------------------------------------+ +-- +-- Generated from drop.tpl +-- DO NOT EDIT. Generated by CRM_Core_CodeGen +-- +-- /******************************************************* +-- * +-- * Clean up the exisiting tables +-- * +-- *******************************************************/ + SET FOREIGN_KEY_CHECKS=0; -DROP TABLE IF EXISTS `civicrm_booking_payment`; DROP TABLE IF EXISTS `civicrm_booking_sub_slot`; DROP TABLE IF EXISTS `civicrm_booking_slot`; DROP TABLE IF EXISTS `civicrm_booking_resource_criteria`; +DROP TABLE IF EXISTS `civicrm_booking_resource_config_set`; DROP TABLE IF EXISTS `civicrm_booking_resource_config_option`; DROP TABLE IF EXISTS `civicrm_booking_resource`; -DROP TABLE IF EXISTS `civicrm_booking_adhoc_charges`; -DROP TABLE IF EXISTS `civicrm_booking_resource_config_set`; +DROP TABLE IF EXISTS `civicrm_booking_payment`; DROP TABLE IF EXISTS `civicrm_booking_cancellation`; DROP TABLE IF EXISTS `civicrm_booking_config`; DROP TABLE IF EXISTS `civicrm_booking`; DROP TABLE IF EXISTS `civicrm_booking_adhoc_charges_item`; - +DROP TABLE IF EXISTS `civicrm_booking_adhoc_charges`; SET FOREIGN_KEY_CHECKS=1; +-- /******************************************************* +-- * +-- * Create new tables +-- * +-- *******************************************************/ + +-- /******************************************************* +-- * +-- * civicrm_booking +-- * +-- *******************************************************/ +CREATE TABLE `civicrm_booking` ( + `id` int unsigned NOT NULL AUTO_INCREMENT , + `primary_contact_id` int unsigned NOT NULL COMMENT 'FK to Contact ID', + `secondary_contact_id` int unsigned NULL COMMENT 'FK to Contact ID', + `title` varchar(255) NOT NULL , + `status_id` int unsigned NOT NULL COMMENT 'The status associated with this booking. Implicit FK to option_value row in booking status option_group.', + `booking_date` datetime NOT NULL , + `start_date` datetime NOT NULL , + `end_date` datetime NOT NULL , + `po_number` varchar(255) NOT NULL , + `total_amount` decimal(20,2) NOT NULL COMMENT 'Total amount of this booking calculated from slots,sub slots, ad-hoc charges and discount amount', + `description` varchar(255) , + `note` text , + `adhoc_charges_note` text , + `participants_estimate` varchar(255) , + `participants_actual` varchar(255) , + `discount_amount` decimal(20,2) , + `is_deleted` tinyint DEFAULT 0 , + `created_by` int unsigned NOT NULL , + `created_date` datetime NOT NULL , + `updated_by` int unsigned NOT NULL , + `updated_date` datetime NOT NULL + , + PRIMARY KEY (`id`) + + , INDEX `index_is_deleted`( + is_deleted + ) + + , CONSTRAINT FK_civicrm_booking_primary_contact_id FOREIGN KEY (`primary_contact_id`) REFERENCES `civicrm_contact`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_secondary_contact_id FOREIGN KEY (`secondary_contact_id`) REFERENCES `civicrm_contact`(`id`) ON DELETE CASCADE +) ; + -- /******************************************************* -- * -- * civicrm_booking_adhoc_charges_item @@ -33,7 +105,7 @@ CREATE TABLE `civicrm_booking_adhoc_charges_item` ( `is_active` tinyint DEFAULT 1 , `is_deleted` tinyint DEFAULT 0 , - PRIMARY KEY ( `id` ) + PRIMARY KEY (`id`) , INDEX `index_is_active`( is_active @@ -43,46 +115,34 @@ CREATE TABLE `civicrm_booking_adhoc_charges_item` ( ) -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +) ; -- /******************************************************* -- * --- * civicrm_booking +-- * civicrm_booking_adhoc_charges -- * -- *******************************************************/ -CREATE TABLE `civicrm_booking` ( +CREATE TABLE `civicrm_booking_adhoc_charges` ( - `id` int unsigned NOT NULL AUTO_INCREMENT , - `primary_contact_id` int unsigned NOT NULL COMMENT 'FK to Contact ID', - `secondary_contact_id` int unsigned NULL COMMENT 'FK to Contact ID', - `title` varchar(255) NOT NULL , - `status_id` int unsigned NOT NULL COMMENT 'The status associated with this booking. Implicit FK to option_value row in booking status option_group.', - `booking_date` datetime NOT NULL , - `start_date` datetime NOT NULL , - `end_date` datetime NOT NULL , - `po_number` varchar(255) NOT NULL , - `total_amount` decimal(20,2) NOT NULL COMMENT 'Total amount of this booking calculated from slots,sub slots, ad-hoc charges and discount amount', - `description` varchar(255) , - `note` text , - `adhoc_charges_note` text , - `participants_estimate` varchar(255) , - `participants_actual` varchar(255) , - `discount_amount` decimal(20,2) , - `is_deleted` tinyint DEFAULT 0 , - `created_by` int unsigned NOT NULL , - `created_date` datetime NOT NULL , - `updated_by` int unsigned NOT NULL , - `updated_date` datetime NOT NULL -, - PRIMARY KEY ( `id` ) + `id` int unsigned NOT NULL AUTO_INCREMENT , + `booking_id` int unsigned NOT NULL COMMENT 'FK to Booking ID', + `item_id` int unsigned NOT NULL COMMENT 'FK to Item ID', + `quantity` int NOT NULL , + `is_cancelled` tinyint DEFAULT 0 , + `is_deleted` tinyint DEFAULT 0 + , + PRIMARY KEY (`id`) + , INDEX `index_is_cancelled`( + is_cancelled + ) , INDEX `index_is_deleted`( - is_deleted - ) + is_deleted + ) -, CONSTRAINT FK_civicrm_booking_primary_contact_id FOREIGN KEY (`primary_contact_id`) REFERENCES `civicrm_contact`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_secondary_contact_id FOREIGN KEY (`secondary_contact_id`) REFERENCES `civicrm_contact`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; + , CONSTRAINT FK_civicrm_booking_adhoc_charges_booking_id FOREIGN KEY (`booking_id`) REFERENCES `civicrm_booking`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_adhoc_charges_item_id FOREIGN KEY (`item_id`) REFERENCES `civicrm_booking_adhoc_charges_item`(`id`) ON DELETE CASCADE +) ; -- /******************************************************* -- * @@ -107,11 +167,11 @@ CREATE TABLE `civicrm_booking_config` ( `slot_provisional_colour` varchar(10) , `slot_unavailable_colour` varchar(10) , - PRIMARY KEY ( `id` ) + PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +) ; -- /******************************************************* -- * @@ -128,65 +188,55 @@ CREATE TABLE `civicrm_booking_cancellation` ( `additional_fee` decimal(20,2) , `comment` text , - PRIMARY KEY ( `id` ) + PRIMARY KEY (`id`) , CONSTRAINT FK_civicrm_booking_cancellation_booking_id FOREIGN KEY (`booking_id`) REFERENCES `civicrm_booking`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +) ; -- /******************************************************* -- * --- * civicrm_booking_resource_config_set +-- * civicrm_booking_payment -- * -- *******************************************************/ -CREATE TABLE `civicrm_booking_resource_config_set` ( +CREATE TABLE `civicrm_booking_payment` ( `id` int unsigned NOT NULL AUTO_INCREMENT , - `title` varchar(255) NOT NULL , - `weight` int unsigned NOT NULL , - `is_active` tinyint DEFAULT 1 , - `is_deleted` tinyint DEFAULT 0 + `booking_id` int unsigned NOT NULL COMMENT 'Foreign key to the booking id for this payment.', + `contribution_id` int unsigned NOT NULL COMMENT 'Foreign key to the contribution for this payment.' , - PRIMARY KEY ( `id` ) - - , INDEX `index_is_active`( - is_active - ) - , INDEX `index_is_deleted`( - is_deleted - ) - + PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +, CONSTRAINT FK_civicrm_booking_payment_booking_id FOREIGN KEY (`booking_id`) REFERENCES `civicrm_booking`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_payment_contribution_id FOREIGN KEY (`contribution_id`) REFERENCES `civicrm_contribution`(`id`) ON DELETE CASCADE +) ; -- /******************************************************* -- * --- * civicrm_booking_adhoc_charges +-- * civicrm_booking_resource_config_set -- * -- *******************************************************/ -CREATE TABLE `civicrm_booking_adhoc_charges` ( +CREATE TABLE `civicrm_booking_resource_config_set` ( - `id` int unsigned NOT NULL AUTO_INCREMENT , - `booking_id` int unsigned NOT NULL COMMENT 'FK to Booking ID', - `item_id` int unsigned NOT NULL COMMENT 'FK to Item ID', - `quantity` int NOT NULL , - `is_cancelled` tinyint DEFAULT 0 , - `is_deleted` tinyint DEFAULT 0 -, - PRIMARY KEY ( `id` ) + `id` int unsigned NOT NULL AUTO_INCREMENT , + `title` varchar(255) NOT NULL , + `weight` int unsigned NOT NULL , + `is_active` tinyint DEFAULT 1 , + `is_deleted` tinyint DEFAULT 0 + , + PRIMARY KEY (`id`) + + , INDEX `index_is_active`( + is_active + ) + , INDEX `index_is_deleted`( + is_deleted + ) - , INDEX `index_is_cancelled`( - is_cancelled - ) - , INDEX `index_is_deleted`( - is_deleted - ) -, CONSTRAINT FK_civicrm_booking_adhoc_charges_booking_id FOREIGN KEY (`booking_id`) REFERENCES `civicrm_booking`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_adhoc_charges_item_id FOREIGN KEY (`item_id`) REFERENCES `civicrm_booking_adhoc_charges_item`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +) ; -- /******************************************************* -- * @@ -207,7 +257,7 @@ CREATE TABLE `civicrm_booking_resource` ( `is_active` tinyint DEFAULT 1 , `is_deleted` tinyint DEFAULT 0 , - PRIMARY KEY ( `id` ) + PRIMARY KEY (`id`) , INDEX `index_is_unlimited`( is_unlimited @@ -220,7 +270,7 @@ CREATE TABLE `civicrm_booking_resource` ( ) , CONSTRAINT FK_civicrm_booking_resource_set_id FOREIGN KEY (`set_id`) REFERENCES `civicrm_booking_resource_config_set`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +) ; -- /******************************************************* -- * @@ -240,7 +290,7 @@ CREATE TABLE `civicrm_booking_resource_config_option` ( `is_active` tinyint DEFAULT 1 , `is_deleted` tinyint DEFAULT 0 , - PRIMARY KEY ( `id` ) + PRIMARY KEY (`id`) , INDEX `index_is_active`( is_active @@ -250,7 +300,7 @@ CREATE TABLE `civicrm_booking_resource_config_option` ( ) , CONSTRAINT FK_civicrm_booking_resource_config_option_set_id FOREIGN KEY (`set_id`) REFERENCES `civicrm_booking_resource_config_set`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +) ; -- /******************************************************* -- * @@ -264,11 +314,11 @@ CREATE TABLE `civicrm_booking_resource_criteria` ( `resource_id` int unsigned NOT NULL COMMENT 'Foreign key to the resoure for this resource criteria.', `criteria_id` varchar(512) NOT NULL COMMENT 'Foreign key to the resource criteria option group.' , - PRIMARY KEY ( `id` ) + PRIMARY KEY (`id`) , CONSTRAINT FK_civicrm_booking_resource_criteria_resource_id FOREIGN KEY (`resource_id`) REFERENCES `civicrm_booking_resource`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +) ; -- /******************************************************* -- * @@ -289,7 +339,7 @@ CREATE TABLE `civicrm_booking_slot` ( `is_cancelled` tinyint DEFAULT 0 , `is_deleted` tinyint DEFAULT 0 , - PRIMARY KEY ( `id` ) + PRIMARY KEY (`id`) , INDEX `index_is_cancelled`( is_cancelled @@ -299,7 +349,7 @@ CREATE TABLE `civicrm_booking_slot` ( ) , CONSTRAINT FK_civicrm_booking_slot_booking_id FOREIGN KEY (`booking_id`) REFERENCES `civicrm_booking`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_slot_resource_id FOREIGN KEY (`resource_id`) REFERENCES `civicrm_booking_resource`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_slot_config_id FOREIGN KEY (`config_id`) REFERENCES `civicrm_booking_resource_config_option`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +) ; -- /******************************************************* -- * @@ -319,7 +369,7 @@ CREATE TABLE `civicrm_booking_sub_slot` ( `is_cancelled` tinyint DEFAULT 0 , `is_deleted` tinyint DEFAULT 0 , - PRIMARY KEY ( `id` ) + PRIMARY KEY (`id`) , INDEX `index_is_cancelled`( is_cancelled @@ -329,24 +379,6 @@ CREATE TABLE `civicrm_booking_sub_slot` ( ) , CONSTRAINT FK_civicrm_booking_sub_slot_slot_id FOREIGN KEY (`slot_id`) REFERENCES `civicrm_booking_slot`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_sub_slot_resource_id FOREIGN KEY (`resource_id`) REFERENCES `civicrm_booking_resource`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_sub_slot_config_id FOREIGN KEY (`config_id`) REFERENCES `civicrm_booking_resource_config_option`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- /******************************************************* --- * --- * civicrm_booking_payment --- * --- *******************************************************/ -CREATE TABLE `civicrm_booking_payment` ( - - - `id` int unsigned NOT NULL AUTO_INCREMENT , - `booking_id` int unsigned NOT NULL COMMENT 'Foreign key to the booking id for this payment.', - `contribution_id` int unsigned NOT NULL COMMENT 'Foreign key to the contribution for this payment.' -, - PRIMARY KEY ( `id` ) - - -, CONSTRAINT FK_civicrm_booking_payment_booking_id FOREIGN KEY (`booking_id`) REFERENCES `civicrm_booking`(`id`) ON DELETE CASCADE, CONSTRAINT FK_civicrm_booking_payment_contribution_id FOREIGN KEY (`contribution_id`) REFERENCES `civicrm_contribution`(`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +) ; diff --git a/sql/auto_uninstall.sql b/sql/auto_uninstall.sql new file mode 100644 index 00000000..1e1a5037 --- /dev/null +++ b/sql/auto_uninstall.sql @@ -0,0 +1,33 @@ +-- +--------------------------------------------------------------------+ +-- | Copyright CiviCRM LLC. All rights reserved. | +-- | | +-- | This work is published under the GNU AGPLv3 license with some | +-- | permitted exceptions and without any warranty. For full license | +-- | and copyright information, see https://civicrm.org/licensing | +-- +--------------------------------------------------------------------+ +-- +-- Generated from drop.tpl +-- DO NOT EDIT. Generated by CRM_Core_CodeGen +-- +-- /******************************************************* +-- * +-- * Clean up the exisiting tables +-- * +-- *******************************************************/ + +SET FOREIGN_KEY_CHECKS=0; + +DROP TABLE IF EXISTS `civicrm_booking_sub_slot`; +DROP TABLE IF EXISTS `civicrm_booking_slot`; +DROP TABLE IF EXISTS `civicrm_booking_resource_criteria`; +DROP TABLE IF EXISTS `civicrm_booking_resource_config_set`; +DROP TABLE IF EXISTS `civicrm_booking_resource_config_option`; +DROP TABLE IF EXISTS `civicrm_booking_resource`; +DROP TABLE IF EXISTS `civicrm_booking_payment`; +DROP TABLE IF EXISTS `civicrm_booking_cancellation`; +DROP TABLE IF EXISTS `civicrm_booking_config`; +DROP TABLE IF EXISTS `civicrm_booking`; +DROP TABLE IF EXISTS `civicrm_booking_adhoc_charges_item`; +DROP TABLE IF EXISTS `civicrm_booking_adhoc_charges`; + +SET FOREIGN_KEY_CHECKS=1; diff --git a/sql/civibooking_uninstall.sql b/sql/civibooking_uninstall.sql index 078b2c8a..26aa28fa 100644 --- a/sql/civibooking_uninstall.sql +++ b/sql/civibooking_uninstall.sql @@ -43,19 +43,4 @@ DELETE FROM civicrm_option_group WHERE name = 'booking_cancellation_charges'; DELETE FROM civicrm_option_group WHERE name = 'booking_size_unit'; DELETE FROM civicrm_option_group WHERE name = 'msg_tpl_workflow_booking'; - -DROP TABLE IF EXISTS `civicrm_booking_payment`; -DROP TABLE IF EXISTS `civicrm_booking_sub_slot`; -DROP TABLE IF EXISTS `civicrm_booking_slot`; -DROP TABLE IF EXISTS `civicrm_booking_resource_criteria`; -DROP TABLE IF EXISTS `civicrm_booking_resource_config_option`; -DROP TABLE IF EXISTS `civicrm_booking_resource`; -DROP TABLE IF EXISTS `civicrm_booking_adhoc_charges`; -DROP TABLE IF EXISTS `civicrm_booking_resource_config_set`; -DROP TABLE IF EXISTS `civicrm_booking_cancellation`; -DROP TABLE IF EXISTS `civicrm_booking_config`; -DROP TABLE IF EXISTS `civicrm_booking`; -DROP TABLE IF EXISTS `civicrm_booking_adhoc_charges_item`; - - SET FOREIGN_KEY_CHECKS=1; diff --git a/templates/CRM/Booking/Form/AddSubResource.tpl b/templates/CRM/Booking/Form/AddSubResource.tpl index 5f10703a..a9ee19ea 100644 --- a/templates/CRM/Booking/Form/AddSubResource.tpl +++ b/templates/CRM/Booking/Form/AddSubResource.tpl @@ -23,6 +23,7 @@ | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ *} +{include file="CRM/common/formButtons.tpl" location="top"} {* WizardHeader.tpl provides visual display of steps thru the wizard as well as title for current step *} {include file="CRM/common/WizardHeader.tpl"}
diff --git a/templates/CRM/Booking/Form/Booking/Info.tpl b/templates/CRM/Booking/Form/Booking/Info.tpl index b82f0c42..8c7bb6e4 100644 --- a/templates/CRM/Booking/Form/Booking/Info.tpl +++ b/templates/CRM/Booking/Form/Booking/Info.tpl @@ -1,29 +1,5 @@ -{crmScope extensionKey=uk.co.compucorp.civicrm.booking} -{* - +--------------------------------------------------------------------+ - | CiviCRM version 4.4 | - +--------------------------------------------------------------------+ - | Copyright CiviCRM LLC (c) 2004-2013 | - +--------------------------------------------------------------------+ - | This file is a part of CiviCRM. | - | | - | CiviCRM is free software; you can copy, modify, and distribute it | - | under the terms of the GNU Affero General Public License | - | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | - | | - | CiviCRM 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 Affero General Public License for more details. | - | | - | You should have received a copy of the GNU Affero General Public | - | License and the CiviCRM Licensing Exception along | - | with this program; if not, contact CiviCRM LLC | - | at info[AT]civicrm[DOT]org. If you have questions about the | - | GNU Affero General Public License or the licensing of CiviCRM, | - | see the CiviCRM license FAQ at http://civicrm.org/licensing | - +--------------------------------------------------------------------+ -*} +{crmScope extensionKey=uk.co.compucorp.civicrm.booking} +{include file="CRM/common/formButtons.tpl" location="top"} {* WizardHeader.tpl provides visual display of steps thru the wizard as well as title for current step *} {include file="CRM/common/WizardHeader.tpl"}
@@ -32,7 +8,7 @@
{$form.primary_contact_id.label} - +
{$form.primary_contact_id.html} @@ -41,7 +17,7 @@
{$form.secondary_contact_id.label} - +
{$form.secondary_contact_id.html} @@ -78,10 +54,9 @@
{$form.event_start_date.label} -
- {include file="CRM/common/jcalendar.tpl" elementName=event_start_date} + {$form.event_start_date.html}
@@ -123,6 +98,7 @@
{include file="CRM/Booking/Form/Booking/Common.tpl"} + {include file="CRM/common/customDataBlock.tpl"}
diff --git a/templates/CRM/Booking/Form/Booking/View.tpl b/templates/CRM/Booking/Form/Booking/View.tpl index dc66dc02..e59e04c6 100644 --- a/templates/CRM/Booking/Form/Booking/View.tpl +++ b/templates/CRM/Booking/Form/Booking/View.tpl @@ -1,52 +1,27 @@ -{crmScope extensionKey=uk.co.compucorp.civicrm.booking} -{* - +--------------------------------------------------------------------+ - | CiviCRM version 4.4 | - +--------------------------------------------------------------------+ - | Copyright CiviCRM LLC (c) 2004-2013 | - +--------------------------------------------------------------------+ - | This file is a part of CiviCRM. | - | | - | CiviCRM is free software; you can copy, modify, and distribute it | - | under the terms of the GNU Affero General Public License | - | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | - | | - | CiviCRM 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 Affero General Public License for more details. | - | | - | You should have received a copy of the GNU Affero General Public | - | License and the CiviCRM Licensing Exception along | - | with this program; if not, contact CiviCRM LLC | - | at info[AT]civicrm[DOT]org. If you have questions about the | - | GNU Affero General Public License or the licensing of CiviCRM, | - | see the CiviCRM license FAQ at http://civicrm.org/licensing | - +--------------------------------------------------------------------+ -*} -{* View existing booking record. *} -
+{crmScope extensionKey=uk.co.compucorp.civicrm.booking} + {* View existing booking record. *} +

{ts}View Booking - ID {/ts}{$id}

@@ -57,257 +32,258 @@ - + - + - + - +
{ts}Booking{/ts} - {$title} + {$title}
{ts}Associated Contact{/ts} - {$secondaryContactDisplayName} + {$secondaryContactDisplayName}
{ts}Date Booking Made{/ts} - {$booking_date|crmDate} + {$booking_date|crmDate}
{ts}Start Date{/ts} - {$start_date|crmDate} + {$start_date|crmDate}
{ts}End Date{/ts} - {$end_date|crmDate} + {$end_date|crmDate}
{ts}PO NO{/ts} - {$po_number} + {$po_number}
{ts}Booking status{/ts} - {$status} + {$status}
{ts}Payment status{/ts} - {if $payment_status eq ''} - {ts}Unpaid{/ts} - {else} - {$payment_status} - {/if} + {if $payment_status eq ''} + {ts}Unpaid{/ts} + {else} + {$payment_status} + {/if}
{ts}Description{/ts} - {$description} + {$description}
{ts}Note{/ts} - {$note} + {$note}
{ts}Participant estimated{/ts} - {$participants_estimate} + {$participants_estimate}
{ts}Participant actual{/ts} - {$participants_actual} + {$participants_actual}
{ts}Sub Total{/ts} - {$sub_total|string_format:"%.2f"} + {$sub_total|string_format:"%.2f"}
{ts}Discount amount{/ts} - {$discount_amount} + {$discount_amount}
{ts}Total{/ts} - {$total_amount} + {$total_amount}
+ {include file="CRM/common/customDataBlock.tpl"}

{ts}Resources{/ts}

- - - - - - - - - - - - {foreach from=$slots item=slot} - - - - - - - - - + + + + + + + + + - {/foreach} -
{ts}Resource{/ts}{ts}Start Date{/ts}{ts}End Date{/ts}{ts}Configuration{/ts}{ts}Note{/ts}{ts}Price Per Unit{/ts}{ts}Quantity{/ts}{ts}Total Amount{/ts}
{$slot.resource_label}{$slot.start|crmDate}{$slot.end|crmDate}{$slot.config_label}{$slot.note}{$slot.unit_price}{$slot.quantity}{$slot.total_amount|number_format:2:".":","}
{ts}Resource{/ts}{ts}Start Date{/ts}{ts}End Date{/ts}{ts}Configuration{/ts}{ts}Note{/ts}{ts}Price Per Unit{/ts}{ts}Quantity{/ts}{ts}Total Amount{/ts}
- {if $sub_slots} -

{ts}Unlimited Resources{/ts}

- - - - - - - - - - - - - - {foreach from=$sub_slots item=subSlot} - - - - - - - - - - - {/foreach} + {foreach from=$slots item=slot} + + + + + + + + + + + {/foreach}
{ts}Resource{/ts}{ts}Parent Resource{/ts}{ts}Time Required{/ts}{ts}Configuration{/ts}{ts}Note{/ts}{ts}Price Per Unit{/ts}{ts}Quantity{/ts}{ts}Total Amount{/ts}
{$subSlot.resource_label}{$subSlot.parent_resource_label}{$subSlot.time_required|crmDate}{$subSlot.config_label}{$subSlot.note}{$subSlot.unit_price}{$subSlot.quantity}{$subSlot.total_amount|number_format:2:".":","}
{$slot.resource_label}{$slot.start|crmDate}{$slot.end|crmDate}{$slot.config_label}{$slot.note}{$slot.unit_price}{$slot.quantity}{$slot.total_amount|number_format:2:".":","}
- {/if} - {if $adhoc_charges} -

{ts}Adhoc Charges Items{/ts}

- - - - - - - - - - {foreach from=$adhoc_charges item=charges} - - - - - - - {/foreach} -
{ts}Item{/ts}{ts}Price Per Unit{/ts}{ts}Quantity{/ts}{ts}Total Amount{/ts}
{$charges.item_label}{$charges.unit_price}{$charges.quantity}{$charges.total_amount|number_format:2:".":","}
- {/if} + {if $sub_slots} +

{ts}Unlimited Resources{/ts}

+ + + + + + + + + + + + + - {if $cancellation_charges} -

{ts}Cancellation{/ts}

-
{ts}Resource{/ts}{ts}Parent Resource{/ts}{ts}Time Required{/ts}{ts}Configuration{/ts}{ts}Note{/ts}{ts}Price Per Unit{/ts}{ts}Quantity{/ts}{ts}Total Amount{/ts}
- {foreach from=$cancellation_charges item=cancellation} - - - - - - - - - - - - - - - - - - - - - - - {/foreach} -
{ts}Date Cancelled{/ts} - {$cancellation.cancellation_date|crmDate} -
{ts}Booking Price{/ts} - {$cancellation.booking_price|number_format:2:".":","} -
{ts}This booking was cancelled{/ts} - {$cancellation.prior_days} day(s) before the event was intended to take place -
{ts}Cancellation Subtotal{/ts} - {$cancellation.cancellation_fee} -
{ts}Other Cancellation Charges{/ts} - {$cancellation.additional_fee} -
{ts}Description{/ts} - {$cancellation.comment} -
{ts}Cancellation Fee{/ts} - {$cancellation.cancellation_total_fee|number_format:2:".":","} -
- {/if} + {foreach from=$sub_slots item=subSlot} + + {$subSlot.resource_label} + {$subSlot.parent_resource_label} + {$subSlot.time_required|crmDate} + {$subSlot.config_label} + {$subSlot.note} + {$subSlot.unit_price} + {$subSlot.quantity} + {$subSlot.total_amount|number_format:2:".":","} + + {/foreach} + + {/if} + {if $adhoc_charges} +

{ts}Adhoc Charges Items{/ts}

+ + + + + + + + + + {foreach from=$adhoc_charges item=charges} + + + + + + + {/foreach} +
{ts}Item{/ts}{ts}Price Per Unit{/ts}{ts}Quantity{/ts}{ts}Total Amount{/ts}
{$charges.item_label}{$charges.unit_price}{$charges.quantity}{$charges.total_amount|number_format:2:".":","}
+ {/if} - {if $contribution} -

{ts}Contribution{/ts}

- - - - - - - - - - - - - - {foreach from=$contribution item=contributionItem} - - - - - - - - - - - {/foreach} -
{ts}Name{/ts}{ts}Amount{/ts}{ts}Type{/ts}{ts}Source{/ts}{ts}Received Date{/ts}{ts}Thank-you sent{/ts}{ts}Status{/ts}{ts}Premium{/ts}
{$contributionItem.sort_name}{$contributionItem.total_amount}{$contributionItem.financial_type}{$contributionItem.contribution_source}{$contributionItem.receive_date|crmDate}{$contributionItem.thankyou_date}{$contributionItem.contribution_status}{$contributionItem.product_name}
- {/if} + {if $cancellation_charges} +

{ts}Cancellation{/ts}

+ + {foreach from=$cancellation_charges item=cancellation} + + + + + + + + + + + + + + + + + + + + + + + {/foreach} +
{ts}Date Cancelled{/ts} + {$cancellation.cancellation_date|crmDate} +
{ts}Booking Price{/ts} + {$cancellation.booking_price|number_format:2:".":","} +
{ts}This booking was cancelled{/ts} + {$cancellation.prior_days} day(s) before the event was intended to take place +
{ts}Cancellation Subtotal{/ts} + {$cancellation.cancellation_fee} +
{ts}Other Cancellation Charges{/ts} + {$cancellation.additional_fee} +
{ts}Description{/ts} + {$cancellation.comment} +
{ts}Cancellation Fee{/ts} + {$cancellation.cancellation_total_fee|number_format:2:".":","} +
+ {/if} + + {if $contribution} +

{ts}Contribution{/ts}

+ + + + + + + + + + + + + + {foreach from=$contribution item=contributionItem} + + + + + + + + + + + {/foreach} +
{ts}Name{/ts}{ts}Amount{/ts}{ts}Type{/ts}{ts}Source{/ts}{ts}Received Date{/ts}{ts}Thank-you sent{/ts}{ts}Status{/ts}{ts}Premium{/ts}
{$contributionItem.sort_name}{$contributionItem.total_amount}{$contributionItem.financial_type}{$contributionItem.contribution_source}{$contributionItem.receive_date|crmDate}{$contributionItem.thankyou_date}{$contributionItem.contribution_status}{$contributionItem.product_name}
+ {/if}
{if !$is_cancelled} - {* {if call_user_func(array('CRM_Core_Permission','check'), 'edit booking')} *} + {* {if call_user_func(array('CRM_Core_Permission','check'), 'edit booking')} *} {assign var='urlParams' value="reset=1&id=$id&cid=$contact_id&action=update&context=$context&selectedChild=booking"} - {if ($context eq 'search' ) && $searchKey} - {assign var='urlParams' value="reset=1&id=$id&cid=$contact_id&action=update&context=$context&selectedChild=booking&key=$searchKey"} - {/if} -
{ts}Edit{/ts}
- {* {/if} *} + {if ($context eq 'search' ) && $searchKey} + {assign var='urlParams' value="reset=1&id=$id&cid=$contact_id&action=update&context=$context&selectedChild=booking&key=$searchKey"} + {/if} +
{ts}Edit{/ts}
+ {* {/if} *} {/if} - {* {if call_user_func(array('CRM_Core_Permission','check'), 'delete in CiviBooking')} *} - {assign var='urlParams' value="reset=1&id=$id&cid=$contact_id&action=delete&context=$context&selectedChild=booking"} - {if ($context eq 'search' ) && $searchKey} - {assign var='urlParams' value="reset=1&id=$id&cid=$contact_id&action=delete&context=$context&selectedChild=booking&key=$searchKey"} - {/if} -
{ts}Delete{/ts}
- {* {/if} *} - {include file="CRM/common/formButtons.tpl" location="top"} -
-
+ {* {if call_user_func(array('CRM_Core_Permission','check'), 'delete in CiviBooking')} *} + {assign var='urlParams' value="reset=1&id=$id&cid=$contact_id&action=delete&context=$context&selectedChild=booking"} + {if ($context eq 'search' ) && $searchKey} + {assign var='urlParams' value="reset=1&id=$id&cid=$contact_id&action=delete&context=$context&selectedChild=booking&key=$searchKey"} + {/if} +
{ts}Delete{/ts}
+ {* {/if} *} + {include file="CRM/common/formButtons.tpl" location="top"} +
+
{/crmScope} diff --git a/templates/CRM/Booking/Form/SelectResource.tpl b/templates/CRM/Booking/Form/SelectResource.tpl index ff2e44ea..cb0c38cc 100644 --- a/templates/CRM/Booking/Form/SelectResource.tpl +++ b/templates/CRM/Booking/Form/SelectResource.tpl @@ -1,4 +1,4 @@ -{crmScope extensionKey=uk.co.compucorp.civicrm.booking} +{crmScope extensionKey=uk.co.compucorp.civicrm.booking} {* +--------------------------------------------------------------------+ | CiviCRM version 4.4 | @@ -25,7 +25,7 @@ +--------------------------------------------------------------------+ *}
- +
{include file="CRM/common/formButtons.tpl" location="top"}
{* WizardHeader.tpl provides visual display of steps thru the wizard as well as title for current step *} {include file="CRM/common/WizardHeader.tpl"} {if $resources} @@ -70,17 +70,17 @@ - + - + Sub total - {$currencySymbols} + {$currencySymbols}
-
{include file="CRM/common/formButtons.tpl"}
+
{include file="CRM/common/formButtons.tpl" location="bottom"}
@@ -89,7 +89,7 @@ {literal} +
+ - - {literal} - - {/literal} + + + +{literal} + +{/literal} {/crmScope} diff --git a/xml/data/OptionGroups.xml b/xml/OptionGroups_install.xml similarity index 100% rename from xml/data/OptionGroups.xml rename to xml/OptionGroups_install.xml diff --git a/xml/schema/Booking/files.xml b/xml/schema/Booking/files.xml deleted file mode 100644 index 9139f566..00000000 --- a/xml/schema/Booking/files.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - -s - - - - - - - - - diff --git a/xml/schema/Booking/AdhocCharges.xml b/xml/schema/CRM/Booking/AdhocCharges.xml similarity index 100% rename from xml/schema/Booking/AdhocCharges.xml rename to xml/schema/CRM/Booking/AdhocCharges.xml diff --git a/xml/schema/Booking/AdhocChargesItem.xml b/xml/schema/CRM/Booking/AdhocChargesItem.xml similarity index 100% rename from xml/schema/Booking/AdhocChargesItem.xml rename to xml/schema/CRM/Booking/AdhocChargesItem.xml diff --git a/xml/schema/Booking/Booking.xml b/xml/schema/CRM/Booking/Booking.xml similarity index 100% rename from xml/schema/Booking/Booking.xml rename to xml/schema/CRM/Booking/Booking.xml diff --git a/xml/schema/Booking/BookingConfig.xml b/xml/schema/CRM/Booking/BookingConfig.xml similarity index 100% rename from xml/schema/Booking/BookingConfig.xml rename to xml/schema/CRM/Booking/BookingConfig.xml diff --git a/xml/schema/Booking/Cancellation.xml b/xml/schema/CRM/Booking/Cancellation.xml similarity index 100% rename from xml/schema/Booking/Cancellation.xml rename to xml/schema/CRM/Booking/Cancellation.xml diff --git a/xml/schema/Booking/Payment.xml b/xml/schema/CRM/Booking/Payment.xml similarity index 100% rename from xml/schema/Booking/Payment.xml rename to xml/schema/CRM/Booking/Payment.xml diff --git a/xml/schema/Booking/Resource.xml b/xml/schema/CRM/Booking/Resource.xml similarity index 100% rename from xml/schema/Booking/Resource.xml rename to xml/schema/CRM/Booking/Resource.xml diff --git a/xml/schema/Booking/ResourceConfigOption.xml b/xml/schema/CRM/Booking/ResourceConfigOption.xml similarity index 100% rename from xml/schema/Booking/ResourceConfigOption.xml rename to xml/schema/CRM/Booking/ResourceConfigOption.xml diff --git a/xml/schema/Booking/ResourceConfigSet.xml b/xml/schema/CRM/Booking/ResourceConfigSet.xml similarity index 100% rename from xml/schema/Booking/ResourceConfigSet.xml rename to xml/schema/CRM/Booking/ResourceConfigSet.xml diff --git a/xml/schema/Booking/ResourceCriteria.xml b/xml/schema/CRM/Booking/ResourceCriteria.xml similarity index 100% rename from xml/schema/Booking/ResourceCriteria.xml rename to xml/schema/CRM/Booking/ResourceCriteria.xml diff --git a/xml/schema/Booking/Slot.xml b/xml/schema/CRM/Booking/Slot.xml similarity index 100% rename from xml/schema/Booking/Slot.xml rename to xml/schema/CRM/Booking/Slot.xml diff --git a/xml/schema/Booking/SubSlot.xml b/xml/schema/CRM/Booking/SubSlot.xml similarity index 100% rename from xml/schema/Booking/SubSlot.xml rename to xml/schema/CRM/Booking/SubSlot.xml diff --git a/xml/schema/Schema.xml b/xml/schema/Schema.xml deleted file mode 100644 index 79ab8c30..00000000 --- a/xml/schema/Schema.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - -civicrm -utf8 -utf8_unicode_ci -InnoDB -Schema for CiviCRM - - - - - - - - - - - - - - - - - - - - - - - - - - - - -