init
This commit is contained in:
@@ -0,0 +1,236 @@
|
||||
<?php
|
||||
/**
|
||||
* 2012-2025 D1m Group
|
||||
*
|
||||
* NOTICE OF LICENSE
|
||||
*
|
||||
* This source file is subject to the Open Software License (OSL 3.0) that is available
|
||||
* through the world-wide-web at this URL: http://www.opensource.org/licenses/OSL-3.0
|
||||
* If you are unable to obtain it through the world-wide-web, please send an email
|
||||
* to sales@d1m.cn so we can send you a copy immediately.
|
||||
*
|
||||
* @copyright 2012-2025 D1m Group
|
||||
* @license http://www.opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
|
||||
*/
|
||||
|
||||
namespace Stemcell\Datacollection\Model;
|
||||
|
||||
use Magento\Framework\App\Filesystem\DirectoryList;
|
||||
use Magento\Framework\Filesystem;
|
||||
use Magento\Framework\Filesystem\Io\File;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Stemcell\Commerce\Model\WebapiResponse;
|
||||
use Stemcell\Datacollection\Api\DataCollectionInterface;
|
||||
use Stemcell\Datacollection\Model\Type\EBook;
|
||||
use Stemcell\Datacollection\Model\Type\Inquiry;
|
||||
use Stemcell\Datacollection\Model\Type\Lecture;
|
||||
use Stemcell\Datacollection\Model\Type\Livedemo;
|
||||
use Stemcell\Datacollection\Model\Type\LiveDemoForm;
|
||||
|
||||
/**
|
||||
* Data Collection Model
|
||||
*/
|
||||
class DataCollection implements DataCollectionInterface
|
||||
{
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public function __construct(
|
||||
private Filesystem $filesystem,
|
||||
private File $ioFile,
|
||||
private Inquiry $inquiryModel,
|
||||
private Lecture $lectureModel,
|
||||
private Livedemo $livedemoModel,
|
||||
private LiveDemoForm $liveDemoForm,
|
||||
private EBook $eBookModel,
|
||||
private Json $jsonSerializer,
|
||||
private \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress,
|
||||
private \Magento\Framework\App\CacheInterface $cache,
|
||||
private WebapiResponse $webapiResponse
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitData($data, $formType = 'default')
|
||||
{
|
||||
try {
|
||||
$this->ipcheck();
|
||||
// Handle different form types
|
||||
if ($formType === 'inquiry') {
|
||||
$result = $this->handleInquiryForm($data);
|
||||
}
|
||||
|
||||
if ($formType === 'lecture') {
|
||||
$result = $this->handleLectureForm($data);
|
||||
}
|
||||
|
||||
if ($formType === 'ebook'){
|
||||
$result = $this->handleEBookForm($data, $formType);
|
||||
}
|
||||
|
||||
if ($formType === 'livedemo') {
|
||||
$result = $this->handleLivedemoForm($data, $formType);
|
||||
}
|
||||
|
||||
// Default handling - save to log file
|
||||
if ($formType === 'default') {
|
||||
$result = $this->handleDefaultData($data);
|
||||
}
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$result = ['error' => "Error collecting data: " . $e->getMessage()];
|
||||
}
|
||||
|
||||
return $this->webapiResponse::json($result);
|
||||
}
|
||||
|
||||
private function handleEbookForm(string $data, string $formType){
|
||||
try {
|
||||
// Decode JSON data
|
||||
$decodedData = $this->jsonSerializer->unserialize($data);
|
||||
|
||||
// Validate data
|
||||
$this->eBookModel->setFormCode($formType)->validateData($decodedData);
|
||||
|
||||
// Process data
|
||||
return $this->eBookModel->processData($decodedData);
|
||||
//return $result['message'] . ' (Record ID: ' . $result['record_id'] . ')';
|
||||
} catch (\Exception $e) {
|
||||
return ['error' => "Error processing inquiry form: " . $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle livedemo form data
|
||||
*/
|
||||
private function handleLivedemoForm(string $data, string $formType)
|
||||
{
|
||||
try {
|
||||
$decodedData = $this->jsonSerializer->unserialize($data);
|
||||
|
||||
$this->liveDemoForm->setFormCode($formType)->validateData($decodedData);
|
||||
return $this->liveDemoForm->processData($decodedData);
|
||||
//return $result['message'] . ' (Record ID: ' . $result['record_id'] . ')';
|
||||
} catch (\Exception $e) {
|
||||
return ['error' => "Error processing livedemo form: " . $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle inquiry form data
|
||||
*
|
||||
* @param string $data
|
||||
* @return array
|
||||
*/
|
||||
private function handleInquiryForm($data)
|
||||
{
|
||||
try {
|
||||
// Decode JSON data
|
||||
$decodedData = $this->jsonSerializer->unserialize($data);
|
||||
|
||||
// Validate data
|
||||
$this->inquiryModel->validateData($decodedData);
|
||||
|
||||
// Process data
|
||||
return $this->inquiryModel->processData($decodedData);
|
||||
//return $result['message'] . ' (Record ID: ' . $result['record_id'] . ')';
|
||||
} catch (\Exception $e) {
|
||||
return ['error' => "Error processing inquiry form: " . $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle lecture form data
|
||||
*
|
||||
* @param string $data
|
||||
* @return array
|
||||
*/
|
||||
private function handleLectureForm($data)
|
||||
{
|
||||
try {
|
||||
// Decode JSON data
|
||||
$decodedData = $this->jsonSerializer->unserialize($data);
|
||||
|
||||
// Validate data
|
||||
$this->lectureModel->validateData($decodedData);
|
||||
|
||||
// Process data
|
||||
return $this->lectureModel->processData($decodedData);
|
||||
//return $result['message'] . ' (Record ID: ' . $result['record_id'] . ')';
|
||||
|
||||
} catch (\Exception $e) {
|
||||
return ['error' => "Error processing lecture form: " . $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle default data (save to log file)
|
||||
*
|
||||
* @param string $data
|
||||
* @return array
|
||||
*/
|
||||
private function handleDefaultData($data)
|
||||
{
|
||||
$filename = $this->log($data);
|
||||
return ['success' => "Data collected successfully. File: " . $filename];
|
||||
}
|
||||
|
||||
private function log($data)
|
||||
{
|
||||
// Get var directory path
|
||||
$varDir = $this->filesystem->getDirectoryWrite(DirectoryList::LOG);
|
||||
$logPath = $varDir->getAbsolutePath('datacollection');
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
if (!is_dir($logPath)) {
|
||||
$this->ioFile->mkdir($logPath, 0755);
|
||||
}
|
||||
|
||||
// Create log file with timestamp
|
||||
$filename = 'data_' . date('Y-m-d') . '.log';
|
||||
$filePath = $logPath . '/' . $filename;
|
||||
|
||||
// Prepare log content
|
||||
$logContent = "Timestamp: " . date('Y-m-d H:i:s') . "\n";
|
||||
$logContent .= "Data: " . $data . "\n";
|
||||
$logContent .= "----------------------------------------\n";
|
||||
|
||||
// Write to file
|
||||
$this->ioFile->write($filePath, $logContent);
|
||||
return $filename;
|
||||
}
|
||||
|
||||
private function ipcheck()
|
||||
{
|
||||
$ip = $this->remoteAddress->getRemoteAddress();
|
||||
$cacheKey = 'datacollection_rate_limit_' . $ip;
|
||||
$count = $this->cache->load($cacheKey) ?: 0;
|
||||
|
||||
if ($count >= 5) {
|
||||
$this->log('IP ' . $ip . ' has made 5 requests in the last 5 minutes.');
|
||||
throw new \Magento\Framework\Exception\LocalizedException(__('Too many requests. Please try again later.'));
|
||||
}
|
||||
|
||||
// 增加计数并设置5分钟过期
|
||||
$this->cache->save((string)($count + 1), $cacheKey, [], 300);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getMyInquiryRecords($pageSize = 10, $currentPage = 1)
|
||||
{
|
||||
try {
|
||||
// Delegate to Inquiry model
|
||||
$result = $this->inquiryModel->getMyInquiryRecords($pageSize, $currentPage);
|
||||
} catch (\Exception $e) {
|
||||
$result = [ 'error' => $e->getMessage()];
|
||||
}
|
||||
|
||||
return $this->webapiResponse::json($result);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
/**
|
||||
* 2012-2025 D1m Group
|
||||
*
|
||||
* NOTICE OF LICENSE
|
||||
*
|
||||
* This source file is subject to the Open Software License (OSL 3.0) that is available
|
||||
* through the world-wide-web at this URL: http://www.opensource.org/licenses/OSL-3.0
|
||||
* If you are unable to obtain it through the world-wide-web, please send an email
|
||||
* to sales@d1m.cn so we can send you a copy immediately.
|
||||
*
|
||||
* @copyright 2012-2025 D1m Group
|
||||
* @license http://www.opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
|
||||
*/
|
||||
|
||||
namespace Stemcell\Datacollection\Model\Type;
|
||||
|
||||
use Magento\Framework\App\CacheInterface;
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Stdlib\DateTime\Timezone;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Magento\Authorization\Model\UserContextInterface;
|
||||
use Stemcell\Commerce\Model\WebapiResponse;
|
||||
|
||||
class Base
|
||||
{
|
||||
|
||||
public function __construct(
|
||||
protected ResourceConnection $resourceConnection,
|
||||
protected StoreManagerInterface $storeManager,
|
||||
protected CacheInterface $cache,
|
||||
protected UserContextInterface $userContext,
|
||||
protected WebapiResponse $webapiResponse,
|
||||
protected Timezone $timezone
|
||||
) {
|
||||
}
|
||||
public function validateFormDataBefore($data)
|
||||
{
|
||||
// 添加防重复提交检查
|
||||
$dataHash = md5(json_encode($data));
|
||||
$cacheKey = 'duplicate_data_check_' . $dataHash;
|
||||
|
||||
if ($this->cache->load($cacheKey)) {
|
||||
throw new LocalizedException(__('Duplicate submission detected. Please try again later.'));
|
||||
}
|
||||
|
||||
// 设置24小时过期
|
||||
$this->cache->save('1', $cacheKey, [], 86400);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
namespace Stemcell\Datacollection\Model\Type;
|
||||
|
||||
use Alekseon\CustomFormsBuilder\Model\Form;
|
||||
use Alekseon\CustomFormsBuilder\Model\FormRecord;
|
||||
use Magento\Authorization\Model\UserContextInterface;
|
||||
use Magento\Framework\App\CacheInterface;
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Stdlib\DateTime\Timezone;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Stemcell\Commerce\Model\WebapiResponse;
|
||||
|
||||
class EBook extends Lecture
|
||||
{
|
||||
protected array $fields = [
|
||||
'name' => '姓名',
|
||||
'company' => '单位',
|
||||
'province' => '省份',
|
||||
'email' => '邮箱',
|
||||
'phone' => '手机号',
|
||||
'research_field' => '研究领域',
|
||||
];
|
||||
|
||||
protected string $formCode;
|
||||
|
||||
public function __construct(
|
||||
ResourceConnection $resourceConnection,
|
||||
StoreManagerInterface $storeManager,
|
||||
CacheInterface $cache,
|
||||
UserContextInterface $userContext,
|
||||
WebapiResponse $webapiResponse,
|
||||
Timezone $timezone,
|
||||
protected Form $form,
|
||||
protected FormRecord $formRecord,
|
||||
) {
|
||||
parent::__construct($resourceConnection, $storeManager, $cache, $userContext, $webapiResponse, $timezone);
|
||||
}
|
||||
|
||||
public function setFormCode(string $formCode)
|
||||
{
|
||||
$this->formCode = $formCode;
|
||||
return $this;
|
||||
}
|
||||
/**
|
||||
* @param array $data
|
||||
* @return true
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function validateData($data)
|
||||
{
|
||||
$errors = [];
|
||||
$this->validateFormDataBefore($data);
|
||||
// Check required fields
|
||||
foreach ($this->fields as $field => $label) {
|
||||
if (!isset($data[$field]) || empty(trim($data[$field]))) {
|
||||
$errors[] = sprintf('"%s"必填', $label);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate email format
|
||||
if (isset($data['email']) && !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
|
||||
$errors[] = '邮箱格式错误';
|
||||
}
|
||||
|
||||
// Validate mobile format (basic validation)
|
||||
if (isset($data['phone']) && !preg_match('/^[0-9+\-\s()]+$/', $data['phone'])) {
|
||||
$errors[] = '手机号格式错误';
|
||||
}
|
||||
|
||||
if (!empty($errors)) {
|
||||
throw new LocalizedException(__(implode(', ', $errors)));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $formId
|
||||
* @param string $fieldIdentifier
|
||||
* @param string|array $label
|
||||
* @return array
|
||||
*/
|
||||
public function getOptionIdByLabel(int $formId, string $fieldIdentifier, string | array $label)
|
||||
{
|
||||
$optionIds = [];
|
||||
$attributeId = $this->getAttributeId($formId, $fieldIdentifier);
|
||||
|
||||
if ($attributeId) {
|
||||
|
||||
// Handle multiselect values (comma-separated)
|
||||
if (is_string($label)) {
|
||||
$values = explode(',', $label);
|
||||
} elseif (is_array($label)) {
|
||||
$values = $label;
|
||||
} else {
|
||||
$values = [$label];
|
||||
}
|
||||
|
||||
foreach ($values as $singleValue) {
|
||||
$singleValue = trim($singleValue);
|
||||
if (!empty($singleValue)) {
|
||||
$optionId = $this->getOptionIdByValue($attributeId, $singleValue);
|
||||
if ($optionId) {
|
||||
$optionIds[] = $optionId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $optionIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function processData($data)
|
||||
{
|
||||
|
||||
$form = $this->form->load($this->formCode, 'identifier');
|
||||
$data['research_field'] = $this->getOptionIdByLabel($form->getId(), 'research_field', $data['research_field']);
|
||||
|
||||
$data['form_id'] = $form->getId();
|
||||
$data['customer_id'] = $this->userContext->getUserId();
|
||||
|
||||
/* @var $record FormRecord */
|
||||
$record = $form->getRecordById(false, true);
|
||||
|
||||
if (!empty($data)) {
|
||||
$record->setFormId($form->getId());
|
||||
$record->addData($data);
|
||||
$record->getResource()->save($record);
|
||||
}
|
||||
|
||||
return [
|
||||
'record_id' => $record->getId()
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
<?php
|
||||
/**
|
||||
* 2012-2025 D1m Group
|
||||
*
|
||||
* NOTICE OF LICENSE
|
||||
*
|
||||
* This source file is subject to the Open Software License (OSL 3.0) that is available
|
||||
* through the world-wide-web at this URL: http://www.opensource.org/licenses/OSL-3.0
|
||||
* If you are unable to obtain it through the world-wide-web, please send an email
|
||||
* to sales@d1m.cn so we can send you a copy immediately.
|
||||
*
|
||||
* @copyright 2012-2025 D1m Group
|
||||
* @license http://www.opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
|
||||
*/
|
||||
|
||||
namespace Stemcell\Datacollection\Model\Type;
|
||||
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Exception\NoSuchEntityException;
|
||||
|
||||
/**
|
||||
* Inquiry Model for Data Collection
|
||||
*/
|
||||
class Inquiry extends Base
|
||||
{
|
||||
/**
|
||||
* Form identifier
|
||||
*/
|
||||
const FORM_IDENTIFIER = 'inquiry';
|
||||
|
||||
/**
|
||||
* Inquiry fields mapping
|
||||
*/
|
||||
const INQUIRY_FIELDS = [
|
||||
'inquiry_company',
|
||||
'inquiry_email',
|
||||
'inquiry_mobile',
|
||||
'inquiry_province',
|
||||
'inquiry_subject_group',
|
||||
'inquiry_username',
|
||||
'inquiry_product_sku',
|
||||
'inquiry_product_name',
|
||||
//'inquiry_incrementid',
|
||||
//'inquiry_customer_id',
|
||||
];
|
||||
|
||||
/**
|
||||
* Process inquiry data
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function processData($data)
|
||||
{
|
||||
try {
|
||||
// Get form ID
|
||||
$formId = $this->getFormId();
|
||||
|
||||
// Create form record
|
||||
$recordId = $this->createFormRecord($formId);
|
||||
|
||||
// Process and store field values
|
||||
$this->processFields($recordId, $formId, $data);
|
||||
|
||||
return [
|
||||
'record_id' => $recordId
|
||||
];
|
||||
|
||||
} catch (\Exception $e) {
|
||||
throw new LocalizedException(__('Failed to process inquiry data: %1', $e->getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get form ID by identifier
|
||||
*
|
||||
* @return int
|
||||
* @throws NoSuchEntityException
|
||||
*/
|
||||
private function getFormId()
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form');
|
||||
|
||||
$select = $connection->select()
|
||||
->from($tableName, ['entity_id'])
|
||||
->where('identifier = ?', self::FORM_IDENTIFIER);
|
||||
|
||||
$formId = $connection->fetchOne($select);
|
||||
|
||||
if (!$formId) {
|
||||
throw new NoSuchEntityException(__('Form with identifier "%1" not found', self::FORM_IDENTIFIER));
|
||||
}
|
||||
|
||||
return $formId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create form record
|
||||
*
|
||||
* @param int $formId
|
||||
* @return int
|
||||
*/
|
||||
private function createFormRecord($formId)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record');
|
||||
|
||||
$data = [
|
||||
'form_id' => $formId,
|
||||
//'created_from_store_id' => $this->storeManager->getStore()->getId(),
|
||||
'created_from_store_id' => 0,
|
||||
'created_at' => date('Y-m-d H:i:s')
|
||||
];
|
||||
|
||||
$connection->insert($tableName, $data);
|
||||
return $connection->fetchOne("SELECT LAST_INSERT_ID()");
|
||||
}
|
||||
|
||||
/**
|
||||
* Process and store field values
|
||||
*
|
||||
* @param int $recordId
|
||||
* @param int $formId
|
||||
* @param array $data
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
private function processFields($recordId, $formId, $data)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$attributeTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute');
|
||||
$varcharTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_entity_varchar');
|
||||
|
||||
foreach (self::INQUIRY_FIELDS as $fieldIdentifier) {
|
||||
if (isset($data[$fieldIdentifier]) && !empty($data[$fieldIdentifier])) {
|
||||
// Get attribute ID
|
||||
$attributeId = $this->getAttributeId($formId, $fieldIdentifier);
|
||||
|
||||
if ($attributeId) {
|
||||
// Store value in varchar table
|
||||
$this->storeVarcharValue($recordId, $attributeId, $data[$fieldIdentifier]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate and store inquiry_incrementid
|
||||
$this->storeVarcharValue($recordId, $this->getAttributeId($formId, 'inquiry_incrementid'), $this->generateXJCode($recordId));
|
||||
|
||||
// Store customer_id if user is logged in
|
||||
$customerId = $this->userContext->getUserId();
|
||||
if ($customerId) {
|
||||
$this->storeVarcharValue($recordId, $this->getAttributeId($formId, 'inquiry_customer_id'), (string)$customerId);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get attribute ID by form ID and field identifier
|
||||
*
|
||||
* @param int $formId
|
||||
* @param string $fieldIdentifier
|
||||
* @return int|null
|
||||
*/
|
||||
private function getAttributeId($formId, $fieldIdentifier)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute');
|
||||
|
||||
$select = $connection->select()
|
||||
->from($tableName, ['id'])
|
||||
->where('form_id = ?', $formId)
|
||||
->where('attribute_code = ?', $fieldIdentifier);
|
||||
|
||||
return $connection->fetchOne($select);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store varchar value
|
||||
*
|
||||
* @param int $recordId
|
||||
* @param int $attributeId
|
||||
* @param string $value
|
||||
*/
|
||||
private function storeVarcharValue($recordId, $attributeId, $value)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_entity_varchar');
|
||||
|
||||
$data = [
|
||||
'entity_id' => $recordId,
|
||||
'attribute_id' => $attributeId,
|
||||
'value' => $value
|
||||
];
|
||||
|
||||
$connection->insert($tableName, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate inquiry data
|
||||
*
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function validateData($data)
|
||||
{
|
||||
$errors = [];
|
||||
$this->validateFormDataBefore($data);
|
||||
// Check required fields
|
||||
foreach (self::INQUIRY_FIELDS as $field) {
|
||||
if (!isset($data[$field]) || empty(trim($data[$field]))) {
|
||||
$errors[] = sprintf('Field "%s" is required', $field);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate email format
|
||||
if (isset($data['inquiry_email']) && !filter_var($data['inquiry_email'], FILTER_VALIDATE_EMAIL)) {
|
||||
$errors[] = 'Invalid email format';
|
||||
}
|
||||
|
||||
// Validate mobile format (basic validation)
|
||||
if (isset($data['inquiry_mobile']) && !preg_match('/^[0-9+\-\s()]+$/', $data['inquiry_mobile'])) {
|
||||
$errors[] = 'Invalid mobile format';
|
||||
}
|
||||
|
||||
if (!empty($errors)) {
|
||||
throw new LocalizedException(__(implode(', ', $errors)));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get inquiry fields configuration
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getFieldsConfig()
|
||||
{
|
||||
return [
|
||||
'form_identifier' => self::FORM_IDENTIFIER,
|
||||
'fields' => self::INQUIRY_FIELDS,
|
||||
'description' => 'Inquiry form data collection'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current customer ID
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getCustomerId()
|
||||
{
|
||||
return $this->userContext->getUserId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current user's inquiry records
|
||||
*
|
||||
* @param int $pageSize Page size
|
||||
* @param int $currentPage Current page number
|
||||
* @return array
|
||||
* @throws \Magento\Framework\Exception\AuthorizationException
|
||||
* @throws \Magento\Framework\Exception\NoSuchEntityException
|
||||
* @throws \Magento\Framework\Exception\LocalizedException
|
||||
*/
|
||||
public function getMyInquiryRecords($pageSize = 10, $currentPage = 1)
|
||||
{
|
||||
try {
|
||||
// Get current customer ID
|
||||
$customerId = $this->userContext->getUserId();
|
||||
|
||||
// Get form ID
|
||||
$formId = $this->getFormId();
|
||||
|
||||
// Get customer ID attribute ID
|
||||
$customerIdAttributeId = $this->getAttributeId($formId, 'inquiry_customer_id');
|
||||
|
||||
// Get all fields from Inquiry model
|
||||
$fieldsConfig = $this->getFieldsConfig();
|
||||
$fields = $fieldsConfig['fields'];
|
||||
|
||||
// Add inquiry_incrementid and inquiry_customer_id to fields
|
||||
$fields[] = 'inquiry_incrementid';
|
||||
$fields[] = 'inquiry_customer_id';
|
||||
|
||||
// Get attribute IDs for all fields
|
||||
$attributeIds = [];
|
||||
foreach ($fields as $field) {
|
||||
$attributeId = $this->getAttributeId($formId, $field);
|
||||
if ($attributeId) {
|
||||
$attributeIds[$field] = $attributeId;
|
||||
}
|
||||
}
|
||||
|
||||
// Get connection
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
|
||||
// Get table names
|
||||
$recordTable = $this->resourceConnection->getTableName('alekseon_custom_form_record');
|
||||
$varcharTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_entity_varchar');
|
||||
|
||||
// Build query to get all records for the current user
|
||||
$select = $connection->select()
|
||||
->from(['r' => $recordTable], ['entity_id', 'created_at'])
|
||||
->joinLeft(
|
||||
['v' => $varcharTable],
|
||||
'r.entity_id = v.entity_id AND v.attribute_id = ' . $customerIdAttributeId . ' AND v.value = ' . $customerId,
|
||||
[]
|
||||
)
|
||||
->where('r.form_id = ?', $formId)
|
||||
->where('v.value IS NOT NULL')
|
||||
->order('r.created_at DESC');
|
||||
|
||||
// Calculate total records
|
||||
$totalRecords = $connection->fetchOne($connection->select()->from(['count' => $select], ['COUNT(*)']));
|
||||
|
||||
// Apply pagination
|
||||
$pageSize = max(1, (int)$pageSize);
|
||||
$currentPage = max(1, (int)$currentPage);
|
||||
$offset = ($currentPage - 1) * $pageSize;
|
||||
$select->limit($pageSize, $offset);
|
||||
|
||||
// Get record IDs
|
||||
$records = $connection->fetchAll($select);
|
||||
|
||||
$result = [];
|
||||
|
||||
// For each record, get all field values
|
||||
foreach ($records as $record) {
|
||||
$recordData = [
|
||||
//'record_id' => $record['entity_id'],
|
||||
'created_at' => $this->timezone->date(new \DateTime($record['created_at']))->format('Y-m-d')
|
||||
];
|
||||
|
||||
// Get all field values for this record
|
||||
foreach ($attributeIds as $field => $attributeId) {
|
||||
$valueSelect = $connection->select()
|
||||
->from($varcharTable, ['value'])
|
||||
->where('entity_id = ?', $record['entity_id'])
|
||||
->where('attribute_id = ?', $attributeId);
|
||||
|
||||
$value = $connection->fetchOne($valueSelect);
|
||||
if ($value !== false) {
|
||||
$recordData[$field] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$result[] = $recordData;
|
||||
}
|
||||
|
||||
// Return results with pagination information
|
||||
return [
|
||||
'items' => $result,
|
||||
'total_count' => $totalRecords,
|
||||
'page_size' => $pageSize,
|
||||
'current_page' => $currentPage,
|
||||
'total_pages' => ceil($totalRecords / $pageSize)
|
||||
];
|
||||
|
||||
} catch (\Exception $e) {
|
||||
throw new \Magento\Framework\Exception\LocalizedException(__('Failed to get inquiry records: %1', $e->getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
private function generateXJCode($num)
|
||||
{
|
||||
$prefix = 'XJ';
|
||||
// 如果小于1000,补足3位;否则直接输出
|
||||
if ($num < 1000) {
|
||||
return $prefix . str_pad($num, 3, "0", STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
return $prefix . $num;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
<?php
|
||||
/**
|
||||
* 2012-2025 D1m Group
|
||||
*
|
||||
* NOTICE OF LICENSE
|
||||
*
|
||||
* This source file is subject to the Open Software License (OSL 3.0) that is available
|
||||
* through the world-wide-web at this URL: http://www.opensource.org/licenses/OSL-3.0
|
||||
* If you are unable to obtain it through the world-wide-web, please send an email
|
||||
* to sales@d1m.cn so we can send you a copy immediately.
|
||||
*
|
||||
* @copyright 2012-2025 D1m Group
|
||||
* @license http://www.opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
|
||||
*/
|
||||
|
||||
namespace Stemcell\Datacollection\Model\Type;
|
||||
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Exception\NoSuchEntityException;
|
||||
|
||||
/**
|
||||
* Lecture Model for Data Collection
|
||||
*/
|
||||
class Lecture extends Base
|
||||
{
|
||||
/**
|
||||
* Form identifier
|
||||
*/
|
||||
const FORM_IDENTIFIER = 'lecture';
|
||||
|
||||
/**
|
||||
* Field code => type mapping (unified)
|
||||
*/
|
||||
const FIELDS = [
|
||||
'lecture_username' => 'varchar',
|
||||
'lecture_company' => 'varchar',
|
||||
// 'lecture_subject_group' => 'varchar',
|
||||
'lecture_province' => 'varchar',
|
||||
'lecture_email' => 'varchar',
|
||||
'lecture_mobile' => 'varchar',
|
||||
'lecture_species_studied' => 'multiselect',
|
||||
'lecture_cell_type' => 'select',
|
||||
'lecture_apply_topics' => 'varchar',
|
||||
'lecture_the_way' => 'select'
|
||||
];
|
||||
|
||||
/**
|
||||
* Process lecture data
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function processData($data)
|
||||
{
|
||||
try {
|
||||
$this->logDebug("Starting to process lecture data: " . json_encode($data));
|
||||
|
||||
// Get form ID
|
||||
$formId = $this->getFormId();
|
||||
$this->logDebug("Form ID: {$formId}");
|
||||
|
||||
// Debug database structure
|
||||
$this->debugDatabaseStructure($formId);
|
||||
|
||||
// Create form record
|
||||
$recordId = $this->createFormRecord($formId);
|
||||
$this->logDebug("Created record ID: {$recordId}");
|
||||
|
||||
// Process and store field values
|
||||
$this->processFields($recordId, $formId, $data);
|
||||
|
||||
return [
|
||||
'record_id' => $recordId
|
||||
];
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$this->logDebug("Error processing lecture data: " . $e->getMessage());
|
||||
throw new LocalizedException(__('Failed to process lecture data: %1', $e->getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get form ID by identifier
|
||||
*
|
||||
* @return int
|
||||
* @throws NoSuchEntityException
|
||||
*/
|
||||
private function getFormId()
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form');
|
||||
|
||||
$select = $connection->select()
|
||||
->from($tableName, ['entity_id'])
|
||||
->where('identifier = ?', self::FORM_IDENTIFIER);
|
||||
|
||||
$formId = $connection->fetchOne($select);
|
||||
|
||||
if (!$formId) {
|
||||
throw new NoSuchEntityException(__('Form with identifier "%1" not found', self::FORM_IDENTIFIER));
|
||||
}
|
||||
|
||||
return $formId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create form record
|
||||
*
|
||||
* @param int $formId
|
||||
* @return int
|
||||
*/
|
||||
private function createFormRecord($formId)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record');
|
||||
|
||||
$data = [
|
||||
'form_id' => $formId,
|
||||
'created_from_store_id' => 0,
|
||||
'created_at' => date('Y-m-d H:i:s')
|
||||
];
|
||||
|
||||
$connection->insert($tableName, $data);
|
||||
return $connection->fetchOne("SELECT LAST_INSERT_ID()");
|
||||
}
|
||||
|
||||
/**
|
||||
* Process and store field values
|
||||
*
|
||||
* @param int $recordId
|
||||
* @param int $formId
|
||||
* @param array $data
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
protected function processFields($recordId, $formId, $data)
|
||||
{
|
||||
foreach (array_keys(self::FIELDS) as $fieldIdentifier) {
|
||||
if (isset($data[$fieldIdentifier]) && !empty($data[$fieldIdentifier])) {
|
||||
$fieldType = self::FIELDS[$fieldIdentifier];
|
||||
|
||||
switch ($fieldType) {
|
||||
case 'varchar':
|
||||
$this->processVarcharField($recordId, $formId, $fieldIdentifier, $data[$fieldIdentifier]);
|
||||
break;
|
||||
case 'select':
|
||||
$this->processSelectField($recordId, $formId, $fieldIdentifier, $data[$fieldIdentifier]);
|
||||
break;
|
||||
case 'multiselect':
|
||||
$this->processMultiselectField($recordId, $formId, $fieldIdentifier, $data[$fieldIdentifier]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process varchar field
|
||||
*
|
||||
* @param int $recordId
|
||||
* @param int $formId
|
||||
* @param string $fieldIdentifier
|
||||
* @param string $value
|
||||
*/
|
||||
private function processVarcharField($recordId, $formId, $fieldIdentifier, $value)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_entity_varchar');
|
||||
|
||||
$attributeId = $this->getAttributeId($formId, $fieldIdentifier);
|
||||
if ($attributeId) {
|
||||
$data = [
|
||||
'entity_id' => $recordId,
|
||||
'attribute_id' => $attributeId,
|
||||
'value' => $value
|
||||
];
|
||||
$connection->insert($tableName, $data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process select field
|
||||
*
|
||||
* @param int $recordId
|
||||
* @param int $formId
|
||||
* @param string $fieldIdentifier
|
||||
* @param string $value
|
||||
*/
|
||||
private function processSelectField($recordId, $formId, $fieldIdentifier, $value)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_entity_int');
|
||||
|
||||
$attributeId = $this->getAttributeId($formId, $fieldIdentifier);
|
||||
if ($attributeId) {
|
||||
$this->logDebug("Processing select field: {$fieldIdentifier}, attribute_id: {$attributeId}, value: {$value}");
|
||||
|
||||
// Get option ID by value
|
||||
$optionId = $this->getOptionIdByValue($attributeId, $value);
|
||||
if ($optionId) {
|
||||
$data = [
|
||||
'entity_id' => $recordId,
|
||||
'attribute_id' => $attributeId,
|
||||
'value' => $optionId
|
||||
];
|
||||
|
||||
$this->logDebug("Inserting select data: " . json_encode($data));
|
||||
$connection->insert($tableName, $data);
|
||||
$this->logDebug("Select data inserted successfully");
|
||||
} else {
|
||||
$this->logDebug("No option_id found for select value: '{$value}'");
|
||||
}
|
||||
} else {
|
||||
$this->logDebug("Attribute ID not found for select field: {$fieldIdentifier}");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process multiselect field
|
||||
*
|
||||
* @param int $recordId
|
||||
* @param int $formId
|
||||
* @param string $fieldIdentifier
|
||||
* @param string $value
|
||||
*/
|
||||
private function processMultiselectField($recordId, $formId, $fieldIdentifier, $value)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_entity_varchar');
|
||||
|
||||
$attributeId = $this->getAttributeId($formId, $fieldIdentifier);
|
||||
if ($attributeId) {
|
||||
$this->logDebug("Processing multiselect field: {$fieldIdentifier}, attribute_id: {$attributeId}, value: {$value}");
|
||||
|
||||
// Handle multiselect values (comma-separated)
|
||||
if (is_string($value)) {
|
||||
$values = explode(',', $value);
|
||||
} elseif (is_array($value)) {
|
||||
$values = $value;
|
||||
} else {
|
||||
$values = [$value];
|
||||
}
|
||||
|
||||
$this->logDebug("Split values: " . json_encode($values));
|
||||
|
||||
$optionIds = [];
|
||||
foreach ($values as $singleValue) {
|
||||
$singleValue = trim($singleValue);
|
||||
if (!empty($singleValue)) {
|
||||
$this->logDebug("Processing single value: '{$singleValue}'");
|
||||
$optionId = $this->getOptionIdByValue($attributeId, $singleValue);
|
||||
if ($optionId) {
|
||||
$optionIds[] = $optionId;
|
||||
$this->logDebug("Added option_id: {$optionId}");
|
||||
} else {
|
||||
$this->logDebug("No option_id found for value: '{$singleValue}'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->logDebug("Final option_ids: " . json_encode($optionIds));
|
||||
|
||||
if (!empty($optionIds)) {
|
||||
$data = [
|
||||
'entity_id' => $recordId,
|
||||
'attribute_id' => $attributeId,
|
||||
'value' => implode(',', $optionIds)
|
||||
];
|
||||
|
||||
$this->logDebug("Inserting data: " . json_encode($data));
|
||||
$connection->insert($tableName, $data);
|
||||
$this->logDebug("Data inserted successfully");
|
||||
} else {
|
||||
$this->logDebug("No option_ids found, skipping insert");
|
||||
}
|
||||
} else {
|
||||
$this->logDebug("Attribute ID not found for field: {$fieldIdentifier}");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get attribute ID by form ID and field identifier
|
||||
*
|
||||
* @param int $formId
|
||||
* @param string $fieldIdentifier
|
||||
* @return int|null
|
||||
*/
|
||||
public function getAttributeId($formId, $fieldIdentifier)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute');
|
||||
|
||||
$select = $connection->select()
|
||||
->from($tableName, ['id'])
|
||||
->where('form_id = ?', $formId)
|
||||
->where('attribute_code = ?', $fieldIdentifier);
|
||||
|
||||
return $connection->fetchOne($select);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get option ID by value
|
||||
*
|
||||
* @param int $attributeId
|
||||
* @param string $value
|
||||
* @return int|null
|
||||
*/
|
||||
public function getOptionIdByValue($attributeId, $value)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$optionTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute_option');
|
||||
$optionValueTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute_option_value');
|
||||
|
||||
// Debug: Log the query parameters
|
||||
$this->logDebug("Looking for option_id for attribute_id: {$attributeId}, value: {$value}");
|
||||
|
||||
$select = $connection->select()
|
||||
->from(['o' => $optionTable], ['o.option_id'])
|
||||
->join(
|
||||
['ov' => $optionValueTable],
|
||||
'o.option_id = ov.option_id',
|
||||
[]
|
||||
)
|
||||
->where('o.attribute_id = ?', $attributeId)
|
||||
->where('ov.value = ?', trim($value));
|
||||
|
||||
$sql = $select->assemble();
|
||||
$this->logDebug("SQL Query: " . $sql);
|
||||
|
||||
$optionId = $connection->fetchOne($select);
|
||||
$this->logDebug("Found option_id: " . ($optionId ?: 'NULL'));
|
||||
|
||||
return $optionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate lecture data
|
||||
*
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function validateData($data)
|
||||
{
|
||||
$errors = [];
|
||||
$this->validateFormDataBefore($data);
|
||||
// Check required fields
|
||||
foreach (array_keys(self::FIELDS) as $field) {
|
||||
if (!isset($data[$field]) || empty(trim($data[$field]))) {
|
||||
$errors[] = sprintf('Field "%s" is required', $field);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate email format
|
||||
if (isset($data['lecture_email']) && !filter_var($data['lecture_email'], FILTER_VALIDATE_EMAIL)) {
|
||||
$errors[] = 'Invalid email format';
|
||||
}
|
||||
|
||||
// Validate mobile format (basic validation)
|
||||
if (isset($data['lecture_mobile']) && !preg_match('/^[0-9+\-\s()]+$/', $data['lecture_mobile'])) {
|
||||
$errors[] = 'Invalid mobile format';
|
||||
}
|
||||
|
||||
// Validate multiselect field
|
||||
if (isset($data['lecture_species_studied'])) {
|
||||
if (is_string($data['lecture_species_studied'])) {
|
||||
$values = explode(',', $data['lecture_species_studied']);
|
||||
foreach ($values as $value) {
|
||||
if (empty(trim($value))) {
|
||||
$errors[] = 'lecture_species_studied contains empty values';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($errors)) {
|
||||
throw new LocalizedException(__(implode(', ', $errors)));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get lecture fields configuration
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getFieldsConfig()
|
||||
{
|
||||
return [
|
||||
'form_identifier' => self::FORM_IDENTIFIER,
|
||||
'fields' => array_keys(self::FIELDS),
|
||||
'field_types' => self::FIELDS,
|
||||
'description' => 'Lecture form data collection'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available options for select/multiselect fields
|
||||
*
|
||||
* @param int $formId
|
||||
* @return array
|
||||
*/
|
||||
public function getFieldOptions($formId)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$attributeTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute');
|
||||
$optionTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute_option');
|
||||
$optionValueTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute_option_value');
|
||||
|
||||
$options = [];
|
||||
|
||||
foreach (self::FIELDS as $fieldCode => $fieldType) {
|
||||
if (in_array($fieldType, ['select', 'multiselect'])) {
|
||||
$attributeId = $this->getAttributeId($formId, $fieldCode);
|
||||
if ($attributeId) {
|
||||
$select = $connection->select()
|
||||
->from(['o' => $optionTable], ['o.option_id'])
|
||||
->join(
|
||||
['ov' => $optionValueTable],
|
||||
'o.option_id = ov.option_id',
|
||||
['ov.value']
|
||||
)
|
||||
->where('o.attribute_id = ?', $attributeId)
|
||||
->order('o.sort_order ASC');
|
||||
|
||||
$fieldOptions = $connection->fetchAll($select);
|
||||
$options[$fieldCode] = $fieldOptions;
|
||||
|
||||
// Log available options for debugging
|
||||
$this->logDebug("Available options for {$fieldCode}: " . json_encode($fieldOptions));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug method to check database structure
|
||||
*
|
||||
* @param int $formId
|
||||
*/
|
||||
public function debugDatabaseStructure($formId)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
|
||||
// Check form
|
||||
$formTable = $this->resourceConnection->getTableName('alekseon_custom_form');
|
||||
$formSelect = $connection->select()->from($formTable)->where('entity_id = ?', $formId);
|
||||
$formData = $connection->fetchRow($formSelect);
|
||||
$this->logDebug("Form data: " . json_encode($formData));
|
||||
|
||||
// Check attributes
|
||||
$attributeTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute');
|
||||
$attributeSelect = $connection->select()->from($attributeTable)->where('form_id = ?', $formId);
|
||||
$attributes = $connection->fetchAll($attributeSelect);
|
||||
$this->logDebug("Attributes: " . json_encode($attributes));
|
||||
|
||||
// Check options for select/multiselect fields
|
||||
foreach (self::FIELDS as $fieldCode => $fieldType) {
|
||||
if (in_array($fieldType, ['select', 'multiselect'])) {
|
||||
$attributeId = $this->getAttributeId($formId, $fieldCode);
|
||||
if ($attributeId) {
|
||||
$this->logDebug("Checking options for field: {$fieldCode}, attribute_id: {$attributeId}");
|
||||
|
||||
$optionTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute_option');
|
||||
$optionValueTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute_option_value');
|
||||
|
||||
$optionSelect = $connection->select()
|
||||
->from(['o' => $optionTable], ['o.option_id', 'o.attribute_id'])
|
||||
->join(
|
||||
['ov' => $optionValueTable],
|
||||
'o.option_id = ov.option_id',
|
||||
['ov.value']
|
||||
)
|
||||
->where('o.attribute_id = ?', $attributeId);
|
||||
|
||||
$options = $connection->fetchAll($optionSelect);
|
||||
$this->logDebug("Options for {$fieldCode}: " . json_encode($options));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug logging method
|
||||
*
|
||||
* @param string $message
|
||||
*/
|
||||
private function logDebug($message)
|
||||
{
|
||||
// Write to a debug log file
|
||||
$logDir = BP . '/var/log/datacollection';
|
||||
if (!is_dir($logDir)) {
|
||||
mkdir($logDir, 0755, true);
|
||||
}
|
||||
|
||||
$logFile = $logDir . '/lecture_debug.log';
|
||||
$timestamp = date('Y-m-d H:i:s');
|
||||
$logMessage = "[{$timestamp}] {$message}" . PHP_EOL;
|
||||
|
||||
file_put_contents($logFile, $logMessage, FILE_APPEND | LOCK_EX);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
namespace Stemcell\Datacollection\Model\Type;
|
||||
|
||||
use Alekseon\CustomFormsBuilder\Model\FormRecord;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
|
||||
class LiveDemoForm extends EBook
|
||||
{
|
||||
protected array $fields = [
|
||||
'livedemo_username' => '姓名',
|
||||
'livedemo_company' => '单位',
|
||||
'livedemo_province' => '省份',
|
||||
'livedemo_email' => '邮箱',
|
||||
'livedemo_mobile' => '手机号',
|
||||
'livedemo_product_show' => '需要申请上门演示的产品',
|
||||
];
|
||||
|
||||
protected array $dependsFields = [
|
||||
'EasySep™细胞分选试剂盒' => [
|
||||
'livedemo_species_studied' => '您要研究的物种',
|
||||
'livedemo_cell_type' => '您研究的细胞类型',
|
||||
],
|
||||
'CellPore™转染系统' => [
|
||||
'livedemo_species_studied' => '您要研究的物种',
|
||||
'livedemo_cell_type' => '您研究的细胞类型',
|
||||
'livedemo_substance' => '您想要递送的物质',
|
||||
'livedemo_xiayou' => '您的下游应用',
|
||||
],
|
||||
'RoboSep™全自动细胞分选仪' => [
|
||||
'livedemo_species_studied' => '您要研究的物种',
|
||||
'livedemo_cell_type' => '您研究的细胞类型',
|
||||
],
|
||||
'STEMvison™造血集落计数与成像仪' => [
|
||||
'livedemo_species_studied' => '您要研究的物种'
|
||||
],
|
||||
'STEMprep™全自动组织处理器' => [
|
||||
'livedemo_species_studied' => '您要研究的物种',
|
||||
'livedemo_organization_type' => '您研究的组织类型',
|
||||
'livedemo_organization_xiayou' => '您在组织处理后的下游应用',
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return true
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function validateData($data)
|
||||
{
|
||||
$errors = [];
|
||||
$this->validateFormDataBefore($data);
|
||||
// Check required fields
|
||||
foreach ($this->fields as $field => $label) {
|
||||
if (!isset($data[$field]) || empty(trim($data[$field]))) {
|
||||
$errors[] = sprintf('"%s"必填', $label);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate email format
|
||||
if (isset($data['livedemo_email']) && !filter_var($data['livedemo_email'], FILTER_VALIDATE_EMAIL)) {
|
||||
$errors[] = '邮箱格式错误';
|
||||
}
|
||||
|
||||
// Validate mobile format (basic validation)
|
||||
if (isset($data['livedemo_mobile']) && !preg_match('/^[0-9+\-\s()]+$/', $data['livedemo_mobile'])) {
|
||||
$errors[] = '手机号格式错误';
|
||||
}
|
||||
|
||||
$demoProduct = isset($data['livedemo_product_show']) ? $data['livedemo_product_show'] : false;
|
||||
if ($demoProduct && isset($this->dependsFields[$demoProduct])) {
|
||||
foreach ($this->dependsFields[$demoProduct] as $field => $label) {
|
||||
if (!isset($data[$field])) {
|
||||
$errors[] = sprintf('"%s"必填', $label);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($errors)) {
|
||||
throw new LocalizedException(__(implode(', ', $errors)));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @return array
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function processData($data)
|
||||
{
|
||||
$form = $this->form->load('Livedemo', 'identifier');
|
||||
|
||||
$dropdownAttributes = [
|
||||
['attribute' => 'livedemo_product_show', 'isMultipleSelect' => false],
|
||||
['attribute' => 'livedemo_species_studied', 'isMultipleSelect' => true],
|
||||
['attribute' => 'livedemo_cell_type', 'isMultipleSelect' => true],
|
||||
['attribute' => 'livedemo_organization_type', 'isMultipleSelect' => true],
|
||||
['attribute' => 'livedemo_organization_xiayou', 'isMultipleSelect' => true],
|
||||
['attribute' => 'livedemo_substance', 'isMultipleSelect' => true],
|
||||
['attribute' => 'livedemo_xiayou', 'isMultipleSelect' => true],
|
||||
];
|
||||
|
||||
foreach ($dropdownAttributes as $attribute) {
|
||||
$attributeCode = $attribute['attribute'];
|
||||
if (isset($data[$attributeCode])) {
|
||||
if ($attribute['isMultipleSelect']) {
|
||||
$data[$attributeCode] = $this->getOptionIdByLabel($form->getId(), $attributeCode, $data[$attributeCode]);
|
||||
// echo $attributeCode.': '.implode(',', $data[$attributeCode]).PHP_EOL;
|
||||
} else {
|
||||
$options = $this->getOptionIdByLabel($form->getId(), $attributeCode, $data[$attributeCode]);
|
||||
$data[$attributeCode] = current($options);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
$data['form_id'] = $form->getId();
|
||||
$data['customer_id'] = $this->userContext->getUserId();
|
||||
|
||||
/* @var $record FormRecord */
|
||||
$record = $form->getRecordById(false, true);
|
||||
|
||||
if (!empty($data)) {
|
||||
$record->setFormId($form->getId());
|
||||
$record->addData($data);
|
||||
$record->getResource()->save($record);
|
||||
}
|
||||
|
||||
return [
|
||||
'record_id' => $record->getId()
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
/**
|
||||
* 2012-2025 D1m Group
|
||||
*/
|
||||
|
||||
namespace Stemcell\Datacollection\Model\Type;
|
||||
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Exception\NoSuchEntityException;
|
||||
|
||||
class Livedemo extends Base
|
||||
{
|
||||
const FORM_IDENTIFIER = 'livedemo';
|
||||
|
||||
// Unified field map: code => type
|
||||
const FIELDS = [
|
||||
'livedemo_username' => 'varchar',
|
||||
'livedemo_company' => 'varchar',
|
||||
'livedemo_subject_group' => 'varchar',
|
||||
'livedemo_province' => 'varchar',
|
||||
'livedemo_email' => 'varchar',
|
||||
'livedemo_mobile' => 'varchar',
|
||||
'livedemo_product_show' => 'select',
|
||||
'livedemo_species_studied' => 'multiselect',
|
||||
'livedemo_cell_type' => 'select'
|
||||
];
|
||||
|
||||
public function processData($data)
|
||||
{
|
||||
try {
|
||||
$this->logDebug("Starting to process livedemo data: " . json_encode($data));
|
||||
$formId = $this->getFormId();
|
||||
$this->logDebug("Form ID: {$formId}");
|
||||
$recordId = $this->createFormRecord($formId);
|
||||
$this->logDebug("Created record ID: {$recordId}");
|
||||
$this->processFields($recordId, $formId, $data);
|
||||
|
||||
return [
|
||||
'record_id' => $recordId
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
$this->logDebug("Error processing livedemo data: " . $e->getMessage());
|
||||
throw new LocalizedException(__('Failed to process livedemo data: %1', $e->getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
private function getFormId()
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form');
|
||||
|
||||
$select = $connection->select()
|
||||
->from($tableName, ['entity_id'])
|
||||
->where('identifier = ?', self::FORM_IDENTIFIER);
|
||||
|
||||
$formId = $connection->fetchOne($select);
|
||||
if (!$formId) {
|
||||
throw new NoSuchEntityException(__('Form with identifier "%1" not found', self::FORM_IDENTIFIER));
|
||||
}
|
||||
return $formId;
|
||||
}
|
||||
|
||||
private function createFormRecord($formId)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record');
|
||||
|
||||
$data = [
|
||||
'form_id' => $formId,
|
||||
'created_from_store_id' => 0,
|
||||
'created_at' => date('Y-m-d H:i:s')
|
||||
];
|
||||
|
||||
$connection->insert($tableName, $data);
|
||||
return $connection->fetchOne("SELECT LAST_INSERT_ID()");
|
||||
}
|
||||
|
||||
private function processFields($recordId, $formId, $data)
|
||||
{
|
||||
foreach (array_keys(self::FIELDS) as $fieldIdentifier) {
|
||||
if (!isset($data[$fieldIdentifier]) || $data[$fieldIdentifier] === '' || $data[$fieldIdentifier] === null) {
|
||||
continue;
|
||||
}
|
||||
$fieldType = self::FIELDS[$fieldIdentifier];
|
||||
switch ($fieldType) {
|
||||
case 'varchar':
|
||||
$this->processVarcharField($recordId, $formId, $fieldIdentifier, $data[$fieldIdentifier]);
|
||||
break;
|
||||
case 'select':
|
||||
$this->processSelectField($recordId, $formId, $fieldIdentifier, $data[$fieldIdentifier]);
|
||||
break;
|
||||
case 'multiselect':
|
||||
$this->processMultiselectField($recordId, $formId, $fieldIdentifier, $data[$fieldIdentifier]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function processVarcharField($recordId, $formId, $fieldIdentifier, $value)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_entity_varchar');
|
||||
$attributeId = $this->getAttributeId($formId, $fieldIdentifier);
|
||||
if ($attributeId) {
|
||||
$this->logDebug("VARCHAR field {$fieldIdentifier} -> attribute_id: {$attributeId}, value: {$value}");
|
||||
$data = [
|
||||
'entity_id' => $recordId,
|
||||
'attribute_id' => $attributeId,
|
||||
'value' => $value
|
||||
];
|
||||
$this->logDebug("Inserting VARCHAR: " . json_encode($data));
|
||||
$connection->insert($tableName, $data);
|
||||
}
|
||||
}
|
||||
|
||||
private function processSelectField($recordId, $formId, $fieldIdentifier, $value)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_entity_int');
|
||||
$attributeId = $this->getAttributeId($formId, $fieldIdentifier);
|
||||
if ($attributeId) {
|
||||
$this->logDebug("SELECT field {$fieldIdentifier} -> attribute_id: {$attributeId}, value: {$value}");
|
||||
$optionId = $this->getOptionIdByValue($attributeId, $value);
|
||||
if ($optionId) {
|
||||
$data = [
|
||||
'entity_id' => $recordId,
|
||||
'attribute_id' => $attributeId,
|
||||
'value' => $optionId
|
||||
];
|
||||
$this->logDebug("Inserting SELECT: " . json_encode($data));
|
||||
$connection->insert($tableName, $data);
|
||||
} else {
|
||||
$this->logDebug("No option_id found for value '{$value}' (attribute_id {$attributeId})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function processMultiselectField($recordId, $formId, $fieldIdentifier, $value)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_entity_varchar');
|
||||
$attributeId = $this->getAttributeId($formId, $fieldIdentifier);
|
||||
if ($attributeId) {
|
||||
$this->logDebug("MULTI field {$fieldIdentifier} -> attribute_id: {$attributeId}, raw: " . (is_string($value) ? $value : json_encode($value)));
|
||||
if (is_string($value)) {
|
||||
$values = explode(',', $value);
|
||||
} elseif (is_array($value)) {
|
||||
$values = $value;
|
||||
} else {
|
||||
$values = [$value];
|
||||
}
|
||||
$optionIds = [];
|
||||
foreach ($values as $singleValue) {
|
||||
$singleValue = trim((string)$singleValue);
|
||||
if ($singleValue === '') {
|
||||
continue;
|
||||
}
|
||||
$this->logDebug("Resolving MULTI item '{$singleValue}'");
|
||||
$optionId = $this->getOptionIdByValue($attributeId, $singleValue);
|
||||
if ($optionId) {
|
||||
$optionIds[] = $optionId;
|
||||
} else {
|
||||
$this->logDebug("No option_id found for multi value '{$singleValue}' (attribute_id {$attributeId})");
|
||||
}
|
||||
}
|
||||
if (!empty($optionIds)) {
|
||||
$data = [
|
||||
'entity_id' => $recordId,
|
||||
'attribute_id' => $attributeId,
|
||||
'value' => implode(',', $optionIds)
|
||||
];
|
||||
$this->logDebug("Inserting MULTI: " . json_encode($data));
|
||||
$connection->insert($tableName, $data);
|
||||
} else {
|
||||
$this->logDebug("No option_ids resolved for MULTI field {$fieldIdentifier}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getAttributeId($formId, $fieldIdentifier)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$tableName = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute');
|
||||
|
||||
$select = $connection->select()
|
||||
->from($tableName, ['id'])
|
||||
->where('form_id = ?', $formId)
|
||||
->where('attribute_code = ?', $fieldIdentifier);
|
||||
|
||||
return $connection->fetchOne($select);
|
||||
}
|
||||
|
||||
public function getOptionIdByValue($attributeId, $value)
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$optionTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute_option');
|
||||
$optionValueTable = $this->resourceConnection->getTableName('alekseon_custom_form_record_attribute_option_value');
|
||||
|
||||
$valueTrim = trim((string)$value);
|
||||
$select = $connection->select()
|
||||
->from(['o' => $optionTable], ['o.option_id'])
|
||||
->join(
|
||||
['ov' => $optionValueTable],
|
||||
'o.option_id = ov.option_id',
|
||||
[]
|
||||
)
|
||||
->where('o.attribute_id = ?', $attributeId)
|
||||
->where('ov.value = ?', $valueTrim);
|
||||
|
||||
$sql = $select->assemble();
|
||||
$this->logDebug("Lookup option_id: attr={$attributeId}, value='{$valueTrim}', sql={$sql}");
|
||||
$optionId = $connection->fetchOne($select);
|
||||
$this->logDebug("Resolved option_id: " . ($optionId ?: 'NULL'));
|
||||
return $optionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
*
|
||||
* @return true
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function validateData($data)
|
||||
{
|
||||
$errors = [];
|
||||
$this->validateFormDataBefore($data);
|
||||
foreach (array_keys(self::FIELDS) as $field) {
|
||||
if (!isset($data[$field]) || trim((string)$data[$field]) === '') {
|
||||
$errors[] = sprintf('Field "%s" is required', $field);
|
||||
}
|
||||
}
|
||||
if (isset($data['livedemo_email']) && !filter_var($data['livedemo_email'], FILTER_VALIDATE_EMAIL)) {
|
||||
$errors[] = 'Invalid email format';
|
||||
}
|
||||
if (isset($data['livedemo_mobile']) && !preg_match('/^[0-9+\-\s()]+$/', (string)$data['livedemo_mobile'])) {
|
||||
$errors[] = 'Invalid mobile format';
|
||||
}
|
||||
if (!empty($errors)) {
|
||||
throw new LocalizedException(__(implode(', ', $errors)));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getFieldsConfig()
|
||||
{
|
||||
return [
|
||||
'form_identifier' => self::FORM_IDENTIFIER,
|
||||
'fields' => array_keys(self::FIELDS),
|
||||
'field_types' => self::FIELDS,
|
||||
'description' => 'Livedemo form data collection'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug logging helper (writes to var/log/datacollection/livedemo_debug.log)
|
||||
*/
|
||||
private function logDebug($message)
|
||||
{
|
||||
if (!defined('BP')) {
|
||||
return; // safety
|
||||
}
|
||||
$logDir = BP . '/var/log/datacollection';
|
||||
if (!is_dir($logDir)) {
|
||||
@mkdir($logDir, 0755, true);
|
||||
}
|
||||
$logFile = $logDir . '/livedemo_debug.log';
|
||||
$timestamp = date('Y-m-d H:i:s');
|
||||
@file_put_contents($logFile, "[{$timestamp}] {$message}" . PHP_EOL, FILE_APPEND | LOCK_EX);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user