wordsonline_connector-1.0.x-dev/src/Form/OrderConfirmForm.php
src/Form/OrderConfirmForm.php
<?php
namespace Drupal\wordsonline_connector\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\wordsonline_connector\WordsOnlineConst;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\tmgmt\Entity\Job;
use Drupal\Core\Database\Connection;
use Drupal\Core\Messenger\Messenger;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\tmgmt\JobInterface;
/**
* Form to confirm quote.
*/
class OrderConfirmForm extends FormBase {
use StringTranslationTrait;
const FORM_PREFIX = "<div class='order-progress-note d-none' style='text-align: initial;'><div class='container div-page-position' style='margin-top: 0px;'><div class='row ch-position' data-bind='with: orderDetail'><div class='ch-title'><span>Quote Detail</span></div>";
const FORM_SURFIX = "</div></div></div></div></div><div class='container loading-quote'> <div class='loading'><p>loading quote</p><span></span></div></div>";
const INFO_PREFIX = "<div class='wol-order-content'><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Estimated Delivery Time</span><div class='ch-row-right' style='width:60%'>";
const INFO_SURFIX = "</div></div><div class='ch-summary-row-2'><span class='ch-row-left'>Additional Preferences</span><div class='ch-row-right' style='line-height:1.5'><span class='step-2-right-targt'></span></div></div><div class='ch-summary-row-2'><span class='ch-row-left'>DTP Pagecount</span> <span class='ch-row-right' id='dtpPageCount'></span></div><div class='ch-summary-row-2'><span class='ch-row-left'>Word Count</span> <span class='ch-row-right' id='wordCount'></span></div><div class='ch-price-row'><span class='ch-row-left'>Order Total</span><div class='ch-row-right'><span class='ch-price-value' id='translationAmount'></span> <span class='ch-price-text' id='translationCurrency'></span></div></div></div>";
const ACTION_PREFIX = "</div><div class='wol-order-action'>";
const ACTION_SURFIX = "</div>";
/**
* Database.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* Constructor.
*
* @param \Drupal\Core\Database\Connection $database
* Database connection.
* @param \Drupal\Core\Messenger\Messenger $messenger
* Messenger.
*/
public function __construct(Connection $database, Messenger $messenger) {
$this->database = $database;
$this->setMessenger($messenger);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('database'),
$container->get('messenger')
);
}
/**
* Get Id of form.
*
* @return string
* Return form id.
*/
public function getFormId() {
return 'wol_order_form';
}
/**
* Get request name
*
* @param string $tableName
* The name of target table.
* @param int $job_id
* Job id.
*
* @return string
* Return request name.
*/
public function getRequestNameFirstOrDefault($tableName, $job_id){
$request_name = NULL;
$results = $this->database->select($tableName, 'wol')
->extend('\Drupal\Core\Database\Query\PagerSelectExtender')
->condition('job_id', $job_id)
->fields('wol')
->limit(1)
->execute()
->fetchAssoc();
if ($results != NULL) {
$request_name = $results["request_name"];
}
return $request_name;
}
/**
* Build the form UI.
*
* @param array $form
* Form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
* @param string $allowSubmmit
* Allow Submit.
* @param string $job_id
* Job id.
*
* @return array
* Return form.
*/
public function buildForm(array $form, FormStateInterface $form_state, $allowSubmmit = 'true', $job_id = NULL,$request_guid = NULL) {
// $results = $this->database->select('wordsonline_connector_jobs', 'wol')
// ->extend('\Drupal\Core\Database\Query\PagerSelectExtender')
// ->condition('job_id', $job_id)
// ->fields('wol')
// ->limit(1)
// ->execute()
// ->fetchAssoc();
// $request_name = NULL;
// if ($results != NULL) {
// $request_name = $results["request_name"];
// }
$form['#prefix'] = OrderConfirmForm::FORM_PREFIX;
$form['#suffix'] = "</div></div></div></div><div class='container loading-quote' data-job-id ='" . $job_id . "' data-request-guid ='" . $request_guid . "' onload='getQuote()'> <div class='loading'><p>loading quote</p><span></span></div>";
$timezone = date_default_timezone_get();
$cf = $this->database->query(WordsOnlineConst::SELECT_CONFIG)->fetchAssoc();
if ($cf != NULL) {
$auth["username"] = $cf["username"];
$auth["password"] = $cf["password"];
$auth["scope"] = $cf["scope"];
$auth["grant_type"] = $cf["grant_type"];
$response = wordsonline_connector_get_token('POST', $auth);
$response = json_decode($response, TRUE);
$timezone = timezone_name_from_abbr($response['timezone']);
}
$markup = new FormattableMarkup("<div class='wol-order-info'>", []);
$form['order_info'] = [
'#markup' => $markup,
];
$due_date = NULL;
$job = Job::load($job_id);
if ($job) {
$request_name = $this->getRequestNameFirstOrDefault(WordsOnlineConst::JOB_TABLE, $job_id);
$due_date = $job->getSetting('due_date');
$content_type = $job->getSetting('content_type');
$service_level = $job->getSetting('serice_level');
$source_lang = $job->getSourceLangcode();
$target_lang = $job->getTargetLangcode();
$ret_lang = $this->database->query('SELECT code,lang_name FROM wordsonline_connector_support_languges')->fetchAll();
foreach ($ret_lang as $row) {
if ($row->code == $source_lang) {
$source_lang = $row->lang_name;
}
if ($row->code == $target_lang) {
$target_lang = $row->lang_name;
}
}
$count = count($job->getItems());
$wol_order_info_summary = "<div class='wol-order-info-summary'><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Request Name</span><div class='ch-row-right' style='width:60%'>@name</div></div><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Items To Translate</span><div class='ch-row-right' style='width:60%'>@count</div></div><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Language Paire</span><div class='ch-row-right' style='width:60%'><span class='wol-lang-source'>@source_lang</span> › <span class='wol-btn'>@target_lang</span></div></div><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Content Type</span><div class='ch-row-right' style='width:60%'>@content_type</div></div><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Service Level</span><div class='ch-row-right' style='width:60%'>@service_level</div></div></div>";
$wol_order_info_summary = str_replace('@count',$count, $wol_order_info_summary);
$wol_order_info_summary = str_replace('@source_lang',$source_lang, $wol_order_info_summary);
$wol_order_info_summary = str_replace('@target_lang',$target_lang, $wol_order_info_summary);
$wol_order_info_summary = str_replace('@service_level',$service_level, $wol_order_info_summary);
$wol_order_info_summary = str_replace('@content_type',$content_type, $wol_order_info_summary);
$wol_order_info_summary = str_replace('@name',$request_name, $wol_order_info_summary);
$markup = new FormattableMarkup($wol_order_info_summary, []);
// $markup = new FormattableMarkup(
// "<div class='wol-order-info-summary'><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Request Name</span><div class='ch-row-right' style='width:60%'>@name</div></div><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Items To Translate</span><div class='ch-row-right' style='width:60%'>@count</div></div><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Language Paire</span><div class='ch-row-right' style='width:60%'><span class='wol-lang-source'>@source_lang</span> › <span class='wol-btn'>@target_lang</span></div></div><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Content Type</span><div class='ch-row-right' style='width:60%'>@content_type</div></div><div class='ch-summary-row-2'><span class='ch-row-left' style='width:35%'>Service Level</span><div class='ch-row-right' style='width:60%'>@service_level</div></div></div>",
// [
// '@count' => $count,
// '@source_lang' => $source_lang,
// '@target_lang' => $target_lang,
// '@service_level' => $service_level,
// '@content_type' => $content_type,
// '@name' => $request_name,
// ]
// );
$form['order_info_detail'] = [
'#markup' => $markup,
];
}
$markup = new FormattableMarkup(OrderConfirmForm::INFO_PREFIX, []);
$form['info_prefix'] = [
'#markup' => $markup,
];
if ($timezone) {
$form['estimate_date'] = [
'#type' => 'date',
'#format' => 'YYY-MM-DD h:mm A',
'#required' => TRUE,
'#value' => $due_date,
'#attributes' => [
'min' => (new \DateTime("tomorrow", new \DateTimeZone($timezone)))->format('Y-m-d'),
'onchange' => 'onDateChage(this)',
],
];
}
else {
$form['estimate_date'] = [
'#type' => 'date',
'#format' => 'YYY-MM-DD h:mm A',
'#required' => TRUE,
'#value' => $due_date,
'#attributes' => [
'onchange' => 'onDateChage(this)',
],
];
}
$form['job_id'] = [
'#type' => 'hidden',
'#default_value' => $job_id,
'#value' => $job_id,
];
$markup = new FormattableMarkup(OrderConfirmForm::INFO_SURFIX, []);
$form['infor_surfix'] = [
'#markup' => $markup,
];
$auto_approve_quote = $job->getSetting('auto_approve_quote');
if (!$auto_approve_quote) {
$auto_approve_quote = FALSE;
}
if ($auto_approve_quote == FALSE && $allowSubmmit == 'true') {
$form['actions']['#prefix'] = OrderConfirmForm::ACTION_PREFIX;
$form['actions']['#surfix'] = OrderConfirmForm::ACTION_SURFIX;
$form['actions']['cancel'] = [
'#type' => 'submit',
'#value' => $this->t('← Back'),
'#submit' => [[$this, 'setCancel']],
'#name' => 'cancelOrrder',
'#attributes' => ['class' => ['btn', 'btn-layout', 'btn-text']],
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Confirm Order'),
'#submit' => [[$this, 'confirmOrder']] ,
'#name' => 'confirmOrder',
'#attributes' => ['class' => ['btn', 'btn-layout', 'ml-3', 'wol-btn']],
];
}
$form['#attached']['library'][] = 'wordsonline_connector/wordsonline';
return $form;
}
/**
* Check is weekend.
*
* @param string $date
* Date string.
*
* @return bool
* Return is weekend.
*/
public function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}
/**
* Approve quote.
*
* @param array $form
* Target form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
public function confirmOrder(array $form, FormStateInterface $form_state) {
$field = $form_state->getUserInput();
$job_id = $field['job_id'];
$due_date = $field['estimate_date'];
$req = $this->database->query("SELECT * FROM wordsonline_connector_jobs where job_id = :job_id LIMIT 1", [':job_id' => $job_id])->fetchAssoc();
if ($req == NULL) {
$this->messenger()->addMessage("Cannot find job");
return;
}
$token = $this->getToken();
if ($token != NULL) {
$phpTime = date('Y-m-d H:i:s');
if ($response['timezone']) {
$tz = timezone_name_from_abbr($response['timezone']);
$timezone = new \DateTimeZone($tz);
$offset = $timezone->getOffset(new \DateTime($phpTime));
$offsetHours = round(($offset) / 3600);
if ($offsetHours < 12) {
$offsetHours = 12 - $offsetHours;
}
else {
$offsetHours = 1;
}
if ($offsetHours > 23) {
$due_date = date('Y-m-d', strtotime($due_date . ' + 1 days'));
}
$due_date = $due_date . " $offsetHours:05:00";
}
$status = wordsonline_connector_approve_quote($req['request_guid'], "Approve", $due_date, $token);
if ($status == 1) {
$this->database->update(WordsOnlineConst::JOB_TABLE)
->condition('job_id', $job_id)
->fields(['status' => WordsOnlineConst::JOB_ORDERED])
->execute();
$url = new Url('wordsonline_connector.wol_job', [], []);
$url->setAbsolute();
$response = new RedirectResponse($url->toString());
$response->send();
$this->messenger()->addMessage("Order is confirmed!");
return;
}
$url = new Url('wordsonline_connector.wol_job', [], []);
$url->setAbsolute();
$response = new RedirectResponse($url->toString());
$response->send();
}
}
/**
* Get the token.
*/
public function getToken(){
$results = $this->database->query(WordsOnlineConst::SELECT_CONFIG)->fetchAssoc();
$token = NULL;
if ($results != NULL) {
$auth["username"] = $results["username"];
$auth["password"] = $results["password"];
$auth["scope"] = $results["scope"];
$auth["grant_type"] = $results["grant_type"];
$response = wordsonline_connector_get_token('POST', $auth);
$response = json_decode($response, TRUE);
$token = $response['access_token'];
}
else {
$this->messenger()->addError(
$this->t(
'Cannot find WordsOnline provider settings.
Please contact <a href="mailto:@url">@url</a>
to obtain WordsOnline provider settings.',
[
"@url" => WordsOnlineConst::HELPDESK_MAIL,
]
)
);
}
return $token;
}
/**
* Cancel quote.
*
* @param array $form
* Target form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
public function setCancel(array $form, FormStateInterface $form_state) {
$field = $form_state->getUserInput();
$job_id = $field['job_id'];
$due_date = $field['estimate_date'];
$req = $this->database->query("SELECT * FROM wordsonline_connector_jobs where job_id = :job_id LIMIT 1", ['job_id' => $job_id])->fetchAssoc();
if ($req == NULL) {
$job = Job::load($job_id);
if ($job) {
$job->delete();
}
$this->messenger()->addMessage("job cancelled");
return;
}
$token = $this->getToken();
if ($token != NULL) {
$status = wordsonline_connector_approve_quote($req['request_guid'], "Cancel", $due_date, $token);
if ($status == 1) {
$this->database->update(WordsOnlineConst::JOB_TABLE)
->condition('job_id', $job_id)
->fields(['status' => WordsOnlineConst::JOB_CANCELLED])
->execute();
$job = Job::load($job_id);
if ($job) {
$job->delete();
}
$this->messenger()->addMessage("job cancelled");
return;
}
else {
$this->messenger()->addError("can't cancel job");
return;
}
}
}
/**
* {@inheritdoc}
*
* @param array $form
* Form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$field = $form_state->getUserInput();
$due_date = $field['estimate_date'];
if ($this->isWeekend($due_date)) {
$form_state->setErrorByName('estimate_date', $this->t("Please kindly provide the available date for working day."));
}
}
/**
* {@inheritdoc}
*
* @param array $form
* Form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
}
}
