Skip to content
Snippets Groups Projects
Commit 93e8ac0a authored by Max Kuzmych's avatar Max Kuzmych
Browse files

Issue #3352277: Reflect holiday day to the branch hours today data

parent 255907b5
No related branches found
No related tags found
1 merge request!10Issue #3352277: [DS-501] When today's date matches a holiday, reflect that
......@@ -12,8 +12,8 @@
* @returns {string}
*/
getDayOfWeek: function (tz) {
// ISO day of week. returns a number of day of week from 1 to 7.
return moment().tz(tz).format('E');
// ISO day of week. returns a string of day of week, e.g. Mon, Tue, etc.
return moment().tz(tz).format('DDD');
},
/**
......@@ -31,36 +31,21 @@
drupalSettings.lb_branch_hours_blocks = {};
}
var $todayHours = $('.today-hours > .today');
var hoursData = [];
var branchHours = drupalSettings.lb_branch_hours_blocks.branch_hours || [];
var $todayHours = $('.hours .today');
var hoursData = drupalSettings.lb_branch_hours_blocks.branch_hours || {};
var tz = drupalSettings.lb_branch_hours_blocks.tz || 'America/New York';
tz = tz.replace(/ /g,"_");
var keys = drupalSettings.lb_branch_hours_blocks.keys || ['branch_hours', 'center_hours', 'open_hours', 'before_school_enrichment'];
// Prioritize these arbitrary hours names first.
keys.reverse().forEach(function (name) {
if (typeof branchHours[name] != 'undefined') {
hoursData = branchHours[name];
}
});
// Fallback to the first set of hours then.
if (!hoursData.length && branchHours.length) {
hoursData = branchHours.slice(0, 1);
}
if (hoursData.length) {
if (Object.keys(hoursData).length) {
var todayString = Drupal.behaviors.today_hours.getDate(tz);
var dayOfWeek = Drupal.behaviors.today_hours.getDayOfWeek(tz);
// got a value from 1..7, but in array keys 0..6
dayOfWeek--;
var hours = hoursData;
var exceptions = []; // Holidays and other day exceptions will come later.
var exceptions = drupalSettings.lb_branch_hours_blocks.exceptions; // Holidays and other day exceptions will come later.
if (typeof exceptions[todayString] != 'undefined') {
$todayHours.text(exceptions[todayString]);
$todayHours.html(exceptions[todayString]);
}
else {
$todayHours.text(hours[dayOfWeek]);
$todayHours.html(hoursData[dayOfWeek]);
}
}
},
......@@ -73,7 +58,7 @@
*/
attach: function (context, settings) {
var $todayHours = $('.today-hours > .today');
var $todayHours = $('.hours .today');
var onceClass = 'refresh-interval-set';
// Bail out if there's already refresh action set.
......@@ -81,7 +66,7 @@
// This will ensure that if people leave the tab open or the page comes back
// into memory on a phone the hour will always be correct.
this.refreshTimer = setInterval(this.updateTodayHours, 60 * 1000);
this.refreshTimer = setInterval(this.updateTodayHours, 5 * 1000);
// Run for the first time.
this.updateTodayHours();
......
......@@ -4,5 +4,6 @@ description: 'Helper module for the custom "Branch Hours" block type'
package: 'YMCA Website Services'
core_version_requirement: ^8.7.7 || ^9 || ^10
dependencies:
- y_branch:y_branch
- y_lb
......@@ -6,7 +6,7 @@ branch_hours:
assets/css/branch-hours.css: { preprocess: true }
hours_today:
version: 1.0
version: 1.1
js:
assets/js/hours_today.js: { minified: false }
dependencies:
......
services:
lb_branch_hours_blocks.hours_today:
class: Drupal\lb_branch_hours_blocks\HoursToday
arguments: ['@config.factory', '@datetime.time']
arguments: ['@datetime.time', '@y_branch.hours_helper']
......@@ -3,10 +3,11 @@
namespace Drupal\lb_branch_hours_blocks;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;
use Drupal\y_branch\BranchHoursHelper;
/**
* Contains HoursToday class.
......@@ -16,51 +17,70 @@ class HoursToday implements TrustedCallbackInterface {
use StringTranslationTrait;
/**
* ConfigFactory service.
* System time service.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $configFactory;
protected $time;
/**
* System time service.
* Branch Hours Helper service.
*
* @var \Drupal\Component\Datetime\TimeInterface
* @var \Drupal\y_branch\BranchHoursHelper
*/
protected $time;
protected $branchHoursHelper;
public function __construct(ConfigFactoryInterface $config_factory, TimeInterface $time) {
$this->configFactory = $config_factory;
/**
* Constructs a HoursToday trusted callback.
*
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\y_branch\BranchHoursHelper $branchHoursHelper
* Branch Hours Helper service.
*/
public function __construct(TimeInterface $time, BranchHoursHelper $branch_hours_helper) {
$this->time = $time;
$this->branchHoursHelper = $branch_hours_helper;
}
/**
* Get today hours.
*
* @return array
* @param string $nid
* Node ID.
*
* @return string[]
* Renderable array of today hours.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Core\TypedData\Exception\MissingDataException
*/
public function generateHoursToday() {
$request_time = $this->time->getRequestTime();
$hours = func_get_args();
$days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
public function generateHoursToday($nid) {
$label = 'Closed';
$node = \Drupal::entityTypeManager()
->getStorage('node')
->load($nid);
if ($node instanceof NodeInterface) {
$holiday_hours = $this->branchHoursHelper->getLazyBranchHolidayHours($node);
$branch_hours = $this->branchHoursHelper->getLazyBranchHours($node);
$date = DrupalDateTime::createFromTimestamp($request_time, $this->configFactory->get('system.date')->get('timezone')['default']);
$today = $date->format('l');
$request_time = $this->time->getRequestTime();
$date = DrupalDateTime::createFromTimestamp($request_time, $this->branchHoursHelper->getTimezone());
$today_weekday = $date->format('D');
$today_date = $date->format('Y-m-d');
$idx = array_search($today, $days);
$label = !empty($hours[$idx]) ? $this->t('Open today') : $this->t('Closed today');
if (!empty($holiday_hours[$today_date])) {
$label = $holiday_hours[$today_date];
}
else {
$label = $branch_hours[$today_weekday] ?: 'Closed';
}
}
return [
'#markup' => '<div class="today">'. $label . '<br />' . $hours[array_search($today, $days)] . '</div>',
'#markup' => '<div class="today">'. $label . '</div>',
];
}
......
......@@ -2,16 +2,13 @@
namespace Drupal\lb_branch_hours_blocks\Plugin\Block;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Utility\Html;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\node\NodeInterface;
use Drupal\y_branch\BranchHoursHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
......@@ -32,16 +29,6 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
*/
class BranchHoursBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* Offset to show field before a holiday.
*/
const SHOW_BEFORE_OFFSET = 1209600;
/**
* Offset to show field after a holiday.
*/
const SHOW_AFTER_OFFSET = 86400;
/**
* The route provider.
*
......@@ -49,13 +36,6 @@ class BranchHoursBlock extends BlockBase implements ContainerFactoryPluginInterf
*/
protected $currentRouteMatch;
/**
* System time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* Location node
*
......@@ -64,11 +44,11 @@ class BranchHoursBlock extends BlockBase implements ContainerFactoryPluginInterf
protected $node;
/**
* ConfigFactory
* Branch Hours Helper service.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
* @var \Drupal\y_branch\BranchHoursHelper
*/
protected $configFactory;
protected $branchHoursHelper;
/**
* Constructs a new BranchHours instance.
......@@ -82,18 +62,15 @@ class BranchHoursBlock extends BlockBase implements ContainerFactoryPluginInterf
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
* The route provider.
* @param \Drupal\Core\Routing\CurrentRouteMatch $currentRouteMatch
* The current route match .
* @param \Drupal\y_branch\BranchHoursHelper $branchHoursHelper
* Branch Hours Helper service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition,
CurrentRouteMatch $currentRouteMatch,
ConfigFactoryInterface $configFactory,
TimeInterface $time
) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, CurrentRouteMatch $currentRouteMatch, BranchHoursHelper $branchHoursHelper) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentRouteMatch = $currentRouteMatch;
$this->configFactory = $configFactory;
$this->time = $time;
$this->branchHoursHelper = $branchHoursHelper;
}
/**
......@@ -105,8 +82,8 @@ class BranchHoursBlock extends BlockBase implements ContainerFactoryPluginInterf
$plugin_id,
$plugin_definition,
$container->get('current_route_match'),
$container->get('config.factory'),
$container->get('datetime.time')
$container->get('y_branch.hours_helper')
);
}
......@@ -143,8 +120,8 @@ class BranchHoursBlock extends BlockBase implements ContainerFactoryPluginInterf
return [];
}
$branch_hours = $this->getBranchHours();
$holiday_hours = $this->getBranchHolidayHours();
$branch_hours = $this->branchHoursHelper->getBranchHours($this->node);
$holiday_hours = $this->branchHoursHelper->getBranchHolidayHours($this->node);
$build = [
'branch_name' => [
......@@ -178,7 +155,7 @@ class BranchHoursBlock extends BlockBase implements ContainerFactoryPluginInterf
'branch_today_hours' => [
'#lazy_builder' => [
'lb_branch_hours_blocks.hours_today:generateHoursToday',
$branch_hours['lazy_hours'],
[$this->node->id()],
],
'#create_placeholder' => TRUE,
],
......@@ -207,8 +184,8 @@ class BranchHoursBlock extends BlockBase implements ContainerFactoryPluginInterf
'drupalSettings' => [
'lb_branch_hours_blocks' => [
'branch_hours' => $branch_hours['js_settings'],
'tz' => $this->configFactory->get('system.date')->get('timezone')['default'],
'keys' => array_keys($branch_hours['js_settings']),
'exceptions' => $holiday_hours['js_settings'],
'tz' => $this->branchHoursHelper->getTimezone(),
]
]
],
......@@ -231,137 +208,6 @@ class BranchHoursBlock extends BlockBase implements ContainerFactoryPluginInterf
return '';
}
/**
* Returns array with data for rendering Branch Hours.
*
* @return array
* @throws \Drupal\Core\TypedData\Exception\MissingDataException
*/
protected function getBranchHours() {
$lazy_hours = [];
$js_settings = [];
$rows = $table = [];
$label = '';
if ($this->node->hasField('field_branch_hours')) {
$branch_hours = $this->node->field_branch_hours->get(0)->getValue();
unset($branch_hours['_attributes']);
$groups = [];
foreach ($branch_hours as $key => $i_item) {
// Do not process label. Store it name for later usage.
if ($key === 'hours_label') {
$label = $i_item;
$js_key = str_ireplace('-', '_', Html::getClass($i_item));
continue;
}
$day = str_replace('hours_', '', $key);
$value = $i_item ?? $this->t('Closed');
$lazy_hours[$day] = $value;
if ($groups && end($groups)['value'] == $value) {
$array_keys = array_keys($groups);
$group = &$groups[end($array_keys)];
$group['days'][] = $day;
}
else {
$groups[] = [
'value' => $value,
'days' => [$day],
];
}
// Populate JS hours.
if (stripos($key, 'hours_') === 0) {
$js_settings[$js_key][] = $value;
}
}
$date = DrupalDateTime::createFromTimestamp($this->time->getRequestTime(), $this->configFactory->get('system.date')->get('timezone')['default']);
$today = strtolower($date->format('D'));
foreach ($groups as $group_item) {
$class = in_array($today, $group_item['days'], true) ? 'current-day' : '';
$title = sprintf('%s - %s', ucfirst(reset($group_item['days'])), ucfirst(end($group_item['days'])));
if (count($group_item['days']) == 1) {
$title = ucfirst(reset($group_item['days']));
}
$hours = $group_item['value'];
$rows[] = ['data' => [$title, $hours], 'class' => $class];
}
if (!empty($rows)) {
$table = [
'#theme' => 'table',
'#header' => [],
'#rows' => $rows,
];
}
}
return [
'lazy_hours' => $lazy_hours,
'label' => $label,
'table' => $table,
'js_settings' => $js_settings,
];
}
/**
* Returns array with data for rendering Holidays Hours.
*
* @return array
* @throws \Exception
*/
protected function getBranchHolidayHours() {
$rows = [];
$config = $this->configFactory->get('openy_field_holiday_hours.settings');
// Calculate timezone offset.
$dt = new DrupalDateTime('now', $this->configFactory->get('system.date')->get('timezone')['default']);
$tz_offset = $dt->getOffset();
// The Holiday Hours should be shown before N days.
$show_before_offset = $config->get('show_before_offset') ?: self::SHOW_BEFORE_OFFSET;
$show_before_offset = $tz_offset + $show_before_offset;
// Also the Holiday Hours should be shown during N offset after a holiday.
$show_after_offset = $config->get('show_after_offset') ?: self::SHOW_AFTER_OFFSET;
$request_time = $this->time->getRequestTime();
if ($this->node->hasField('field_branch_holiday_hours')) {
$holiday_hours = $this->node->field_branch_holiday_hours->getValue();
foreach ($holiday_hours as $holiday) {
// Skip holidays with empty date.
if (empty($holiday['date'])) {
continue;
}
$holiday_timestamp = $holiday['date'];
if ($request_time < ($holiday_timestamp + $show_after_offset) && ($holiday_timestamp - $request_time) <= $show_before_offset) {
$title = Html::escape($holiday['holiday']);
$rows[] = [
'data' => [
$title,
$holiday['hours'],
],
'data-timestamp' => $holiday_timestamp,
];
}
}
$table = [
'#theme' => 'table',
'#rows' => $rows,
'#cache' => [
'tags' => ['ymca_cron'],
],
];
}
return [
'label' => $this->t('Holiday Hours'),
'table' => $table ?? []
];
}
/**
* Returns More Hours link render array.
*
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment