library_management_system-1.0.1/library_management_system.module
library_management_system.module
<?php
/**
* @file
* Contains library_management_system.module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\library_management_system\Entity\LmsPublication;
use Drupal\library_management_system\Entity\RequestedLmsBook;
use Drupal\library_management_system\Entity\LmsBook;
use Drupal\library_management_system\Entity\IssuedLmsBook;
use Drupal\library_management_system\Entity\LmsBookAuthor;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityInterface;
use Drupal\user\Entity\User;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
/**
* Implements hook_install
* @return [type] [description]
*/
function library_management_system_install()
{
$vocabularies_array = array(
array(
'vid' => 'lmsbook_categories',
'name' => 'LMS Categories',
)
);
foreach ($vocabularies_array as $key => $vocabulary_array) {
$vocabularies = \Drupal\taxonomy\Entity\Vocabulary::loadMultiple();
if (!isset($vocabularies[$vocabulary_array['vid']])) {
$vocabulary = \Drupal\taxonomy\Entity\Vocabulary::create(array(
'vid' => $vocabulary_array['vid'],
'description' => '',
'name' => $vocabulary_array['name'],
));
$vocabulary->save();
}
}
}
/**
* Implements hook_help().
*/
function library_management_system_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.library_management_system':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The library_management_system module can be used to create simple surveys or titlenaires that display cumulative results. A library_management_system is a good way to receive feedback from site users and community members. For more information, see the online handlmsbook entry for the <a href=":library_management_system">library_management_system module</a>.', array(':library_management_system' => 'https://www.drupal.org/docs/8/modules/library_management_system')) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Creating a library_management_system') . '</dt>';
$output .= '<dd>' . t('Users can create a library_management_system by clicking on <a href=":add-library_management_system">Add a library_management_system</a> on the <a href=":library_management_systems">library_management_systems</a> page, and entering the title being posed, the answer choices, and beginning vote counts for each choice. The status (closed or active) and duration (length of time the library_management_system remains active for new votes) can also be specified.', array(':add-library_management_system' => Url::fromRoute('library_management_system.library_management_system_add')->toString(), ':library_management_systems' => Url::fromRoute('library_management_system.library_management_system_list')->toString())) . '</dd>';
$output .= '<dt>' . t('Viewing library_management_systems') . '</dt>';
$output .= '<dd>' . t('You can visit the <a href=":library_management_systems">library_management_systems</a> page to view all current library_management_systems, or alternately enable the <em>Most recent library_management_system</em> block on the <a href=":blocks">Blocks administration page</a>. To vote in or view the results of a specific library_management_system, you can click on the library_management_system itself.', array(':library_management_systems' => Url::fromRoute('library_management_system.library_management_system_list')->toString(), ':blocks' => Url::fromRoute('block.admin_display')->toString())) . '</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Implements hook_cron().
*/
function library_management_system_cron() {
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function library_management_system_form_alter(&$form, FormStateInterface $form_state, $form_id) {
switch ($form_id) {
case 'issuedlmsbook_form':
$timestamp = time();
$timestamp = strtotime('+7 days', $timestamp);
$form['returned_date']['#access'] = false;
$form['fine_price']['widget'][0]['value']['#default_value'] = '5.1';
$form['due_date']['widget'][0]['value']['#default_value'] = DrupalDateTime::createFromTimestamp($timestamp);
break;
case 'issuedlmsbook_edit_form':
$form['title']['#disabled'] = true;
$form['uid']['#disabled'] = true;
$form['lmsbook']['#disabled'] = true;
$form['due_date']['#disabled'] = true;
$form['#validate'][] = 'issuedlmsbook_validate';
break;
case 'requestedlmsbook_edit_form':
$form['uid']['#disabled'] = true;
$form['lmsbook']['#disabled'] = true;
break;
case 'lmspublication_form':
case 'lmspublication_edit_form':
case 'lmsbook_form':
case 'lmsbook_edit_form':
break;
default:
break;
}
}
/**
* Implements hook_theme().
*/
function library_management_system_theme($existing, $type, $theme, $path) {
return [
'book_reports_template' => [
'variables' => ['data' => NULL],
],
];
}
/**
* Implements hook_entity_presave().
*/
function library_management_system_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
switch ($entity->bundle()) {
// Here you modify only your day content type
case 'issuedlmsbook':
// Setting the title with the value of field_date.
$returned_date = $entity->get('returned_date')->value;
$status = 'issue';
if($returned_date) {
$status = 'returned';
}
$entity->setStatus($status);
$fine_price = $entity->get('fine_price')->value;
$fine_price = abs($fine_price);
$entity->setFinePrice($fine_price);
break;
case 'requestedlmsbook':
$issued = $entity->get('status')->value;
$title = $entity->get('title')->value;
$uid = $entity->get('uid')->value;
$lmsbook = $entity->get('lmsbook')->value;
if($issued) {
$uid_data = $entity->get('uid')->getValue();
if(isset($uid_data[0]['target_id'])) {
$uid = $uid_data[0]['target_id'];
$lmsbook_data = $entity->get('lmsbook')->getValue();
if(isset($lmsbook_data[0]['target_id'])) {
$lmsbook_id = $entity->id();
$query = \Drupal::entityQuery('issuedlmsbook')
->accessCheck(TRUE)
->condition('request_id', $lmsbook_id);
$entity_id = $query->execute();
if(empty($entity_id)) {
$lmsbook = $lmsbook_data[0]['target_id'];
$timestamp = time();
$timestamp = strtotime('+7 days', $timestamp);
$data = array(
'title' => $title,
'uid' => $uid,
'lmsbook' => $lmsbook,
'request_id' => $lmsbook_id,
'fine_price' => '44.5',
'due_date' => DrupalDateTime::createFromTimestamp($timestamp)->format('Y-m-d'),
);
$IssuedLmsBook = IssuedLmsBook::create($data);
$IssuedLmsBook->save();
} else {
$entity_id = array_key_first($entity_id);
$IssuedLmsBook = IssuedLmsBook::load($entity_id);
if($IssuedLmsBook) {
$IssuedLmsBook->setTitle($title);
$IssuedLmsBook->save();
}
}
}
}
}
break;
}
// trim the unwanted spaces from the entity title
switch ($entity->bundle()) {
case 'lmsbookauthor':
case 'lmsbook':
case 'lmspublication':
case 'issuedlmsbook':
case 'requestedlmsbook':
$title = $entity->get('title')->value;
$processed_title = trim($title);
$entity->set('title', $processed_title);
break;
}
}
/**
* Validate issued book
* @param [type] $form
* @param FormStateInterface $form_state
* @return [type]
*/
function issuedlmsbook_validate($form, FormStateInterface $form_state) {
if ($form_state->hasValue('returned_date')) {
$returned_date = $form_state->getValue('returned_date');
$returned_date_value = $returned_date[0]['value']??null;
if($returned_date_value) {
if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
$entity = $form_state->getFormObject()->getEntity();
$entity_type = $entity->bundle();
$created = $entity->created->value;
// $returned_date_timestamp = $returned_date_value->getTimestamp();
// if($returned_date_timestamp < $created) {
// $form_state->setErrorByName("returned_date", t("Please enter the valid returned date."));
// }
}
}
}
}
/**
* Implements hook_form_views_exposed_form_alter()
*/
function library_management_system_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
$view = $form_state->get('view');
switch ($view->id()) {
case 'lmsbook_admin':
break;
case 'requestedlmsbook_admin':
case 'issuedlmsbook_admin':
$form['title']['#size'] = '20';
$form['book-name']['#size'] = '20';
$form['uid']['#size'] = '30';
$date_format = 'Y-m-d';
if(isset($form['issued_from'])) {
$form['issued_from'] = [
'#type' => 'date',
'#title' => t('Start date'),
'#date_date_format' => $date_format,
'#size' => 15,
];
$form['issued_to'] = [
'#type' => 'date',
'#title' => t('Start date'),
'#date_date_format' => $date_format,
'#size' => 15,
];
}
if(isset($form['requested_from'])) {
$form['requested_from'] = [
'#type' => 'date',
'#title' => t('Start date'),
'#date_date_format' => $date_format,
'#size' => 15,
];
$form['requested_to'] = [
'#type' => 'date',
'#title' => t('Start date'),
'#date_date_format' => $date_format,
'#size' => 15,
];
}
break;
}
}
/**
* Implements hook_entity_operation().
*/
function library_management_system_entity_operation_alter(array &$operations, EntityInterface $entity) {
$entityTypeId = $entity->getEntityTypeId();
switch ($entityTypeId) {
case 'requestedlmsbook':
// add custom operation
$entity_status = $entity->getStatus();
if(!$entity_status) {
$issueUrl = Url::fromRoute('entity.requestedlmsbook.issue', ['requestedlmsbook' => $entity->id()]);
$operations['custom_operation'] = array(
'title' => t('Issue Book'),
'weight' => 20,
'url' => $issueUrl,
);
}
break;
default:
break;
}
}
/**
* Generate mapped data
* @param [type] $contentData [description]
* @param [type] $batch [description]
* @param [type] $revision [description]
* @return [type] [description]
*/
function mapped_data($contentData, $batch, $import_to, $file_extension, $update_content) {
$item = array();
if($file_extension == 'xlsx') {
$row_headings = $contentData[0];
// $get_authors_fields = get_authors_fields();
// pr($get_authors_fields, 0);
// pr($row_headings, 1);
unset($contentData[0]);
foreach ($contentData as $key => $content) {
$item = array();
foreach ($content as $content_key => $content_value) {
$item[$row_headings[$content_key]] = $content_value;
}
$records['data'] = $item;
$batch['operations'][] = [
'perform_batch_action', [$records, $import_to, $update_content]
];
}
} else {
foreach ($contentData as $key => $content) {
$records['data'] = $content;
$batch['operations'][] = [
'perform_batch_action', [$records, $import_to, $update_content]
];
}
}
return $batch;
}
/*
* Callback function once the process is finished.
*/
function batch_finished_callback($success, $results, $operations) {
if ($success) {
$results_data = (isset($results['results']))?$results['results']:[];
$count = count($results_data);
$message = \Drupal::translation()->formatPlural(
$count ,
'One record processed.', '@count records processed.'
);
\Drupal::messenger()->addMessage($message);
} else {
$message = t('Finished with an error.');
\Drupal::messenger()->addMessage($message, 'error');
}
}
/**
* Function to handle a batch process
*/
function perform_batch_action($results, $import_to, $update_content, &$context){
$title = '';
$localhost = true;
try {
$data = $results['data'];
switch ($import_to) {
case 'authors':
$content_title = $data['Name'];
$node_content = $data['Content'];
$query = \Drupal::entityQuery('lmsbookauthor')
->accessCheck(TRUE)
->range(0,1)
->condition('title', $content_title);
$results = $query->execute();
// check if result is empty or not
if(empty($results)) {
// create book author if already not exists
$book_author = LmsBookAuthor::create([
'title' =>$content_title,
'text_long' => $node_content
]);
$book_author->save();
} else if(!empty($results) && $update_content) {
// if author already exists and the update content checkbox
// checked then update the author content
$entity_id = current($results);
$book_author = LmsBookAuthor::load($entity_id);
if($book_author) {
$book_author->set('text_long', $node_content);
$book_author->save();
}
}
break;
case 'publications':
$content_title = $data['Name'];
$node_content = $data['Content'];
$query = \Drupal::entityQuery('lmspublication')
->accessCheck(TRUE)
->range(0,1)
->condition('title', $content_title);
$results = $query->execute();
// check if result is empty or not
if(empty($results)) {
// create book author if already not exists
$book_author = LmsPublication::create([
'title' =>$content_title,
'text_long' => $node_content
]);
$book_author->save();
} else if(!empty($results) && $update_content) {
// if author already exists and the update content checkbox
// checked then update the author content
$entity_id = current($results);
$book_author = LmsPublication::load($entity_id);
if($book_author) {
$book_author->set('text_long', $node_content);
$book_author->save();
}
}
break;
case 'books':
$content_title = $data['Name']??'';
$details = $data['Details']??'';
$isbn = $data['Isbn']??'';
$author = $data['Author']??'';
$publisher = $data['Publisher']??'';
$category = $data['Category']??'';
$no_of_copies = $data['NoOfCopies']??'';
$price = $data['Price']??'';
$query = \Drupal::entityQuery('lmsbook')
->accessCheck(TRUE)
->range(0,1)
->condition('isbn', $isbn);
$results = $query->execute();
if($category) {
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')
->loadByProperties(['name' => $category, 'vid' => 'lmsbook_categories']);
if($term) {
$term = reset($term);
$term_id = $term->id();
}
}
if($publisher) {
$publisher_query = \Drupal::entityQuery('lmspublication')
->accessCheck(TRUE)
->range(0,1)
->condition('title', $publisher);
$publisher_results = $publisher_query->execute();
if(!empty($publisher_results)) {
$publisher_id = current($publisher_results);
}
}
$authors_data = array();
if($author) {
$authors = array_map('trim', explode(',', $author));
foreach ($authors as $key => $author_name) {
$author_query = \Drupal::entityQuery('lmsbookauthor')
->accessCheck(TRUE)
->range(0,1)
->condition('title', $author_name);
$author_results = $author_query->execute();
if(!empty($author_results)) {
$uid = current($author_results);
$authors_data[] = $uid;
}
}
}
// check if result is empty or not
if(empty($results)) {
$book_array = array(
'title' =>$content_title,
'details' => $details,
'copies' => $no_of_copies,
'isbn' => $isbn,
'price' => $price,
);
// create book author if already not exists
$book_data = LmsBook::create($book_array);
if(!empty($authors_data)) {
foreach ($authors_data as $key => $uid) {
$multi_value[] =['target_id' => $uid];
}
$book_data->set('uid', $multi_value);
}
if(!empty($publisher_id)) {
$publisher_value =['target_id' => $publisher_id];
$book_data->set('lmspublication', $publisher_value);
}
if(isset($term_id)) {
$term_data =['target_id' => $term_id];
$book_data->set('lmsbook_category', $term_data);
}
$book_data->save();
} else if(!empty($results) && $update_content) {
// if author already exists and the update content checkbox
// checked then update the author content
$entity_id = current($results);
$book_data = LmsBook::load($entity_id);
if($book_data) {
$book_data->set('details', $details);
if(!empty($authors_data)) {
foreach ($authors_data as $key => $uid) {
$multi_value[] =['target_id' => $uid];
}
$book_data->set('uid', $multi_value);
}
if(isset($term_id)) {
$term_data =['target_id' => $term_id];
$book_data->set('lmsbook_category', $term_data);
}
if(!empty($publisher_id)) {
$publisher_value =['target_id' => $publisher_id];
$book_data->set('lmspublication', $publisher_value);
}
$book_data->save();
}
}
break;
case 'users':
$Username = $data['Username'];
$Email = $data['Email'];
$query = \Drupal::entityQuery('user')
->accessCheck(TRUE)
->range(0,1)
->condition('mail', $Email);
$results = $query->execute();
// check if result is empty or not
if(empty($results)) {
// create book author if already not exists
$user_date = User::create([
'name' =>$Username,
'mail' => $Email,
'status' => true,
]);
$user_date->save();
} else if(!empty($results) && $update_content) {
// if author already exists and the update content checkbox
// checked then update the author content
$entity_id = current($results);
$user_date = User::load($entity_id);
if($user_date) {
$user_date->set('status', true);
$user_date->save();
}
}
break;
}
$context['results']['results'][] = $content_title;
$context['message'] = t('Updated @title', array('@title' => $content_title));
} catch (Exception $e) {
$message .= $e->getMessage();
dd($message);
$type = 'error';
log_updates($logger_type, $message, $type);
}
}
/**
* Print array for debuging
* @param [type] $array
* @param [type] $die
* @return [type]
*/
function pr($array, $die) {
echo "<pre>";
print_r($array);
echo "</pre>";
if($die) {
die;
}
}
/**
* Implements hook_toolbar_alter().
*/
function library_management_system_toolbar_alter(&$items) {
$items['administration']['#attached']['library'][] = 'library_management_system/toolbar';
}
/**
* Implements hook_entity_extra_field_info().
*/
function library_management_system_entity_extra_field_info() {
$extra = [];
$extra['lmsbook']['lmsbook']['display']['field_thank_you'] = [
'label' => t('Request the book'),
'description' => t('Thank You pseudo field.'),
'weight' => 30,
'visible' => TRUE,
];
return $extra;
}
/**
* Implements hook_ENTITY_TYPE_view().
*/
function library_management_system_lmsbook_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
if ($display->getComponent('field_thank_you')) {
$current_uid = \Drupal::currentUser()->id();
$lmsbook = $entity->id();
$query = \Drupal::entityQuery('requestedlmsbook')
->accessCheck(TRUE)
->condition('uid', $current_uid)
->condition('lmsbook', $lmsbook);
$ids = $query->execute();
$disabled = '';
if(!empty($ids)) {
$disabled = ' is-disabled';
}
$options = [
'attributes' => [
'target' => '_blank',
'class' => 'button button-action button--primary button--small'.$disabled,
],
];
$url = Url::fromRoute('library_management_system.request', ['lmsbook' => 1], $options);
$link = Link::fromTextAndUrl(t('Request the book'), $url);
$build['field_thank_you']['edit_link'] = $link->toRenderable();
}
}
/**
* remove spacesa ad lowercase the string
* @param [type] $text
* @return [type]
*/
function clear_text_lms($text)
{
$text = trim($text);
$text = preg_replace('!\s+!', '', $text);
return $text;
}