This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,40 @@
<?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\Api;
/**
* Data Collection API Interface
*/
interface DataCollectionInterface
{
/**
* Submit data collection
*
* @param string $data
* @param string $formType
* @return mixed
*/
public function submitData($data, $formType = 'default');
/**
* Get current user's inquiry records
*
* @param int $pageSize Page size
* @param int $currentPage Current page number
* @return array
*/
public function getMyInquiryRecords($pageSize = 10, $currentPage = 1);
}
@@ -0,0 +1,206 @@
<?php
namespace Stemcell\Datacollection\Cron;
use Alekseon\CustomFormsBuilder\Model\ResourceModel\Form\Collection as FormCollection;
use Alekseon\CustomFormsBuilder\Model\ResourceModel\FormRecord\Attribute as FormRecordAttributeResourceModel;
use Alekseon\CustomFormsBuilder\Model\ResourceModel\FormRecord\Attribute\CollectionFactory as FormRecordAttributeCollectionFactory;
use Alekseon\CustomFormsBuilder\Model\ResourceModel\FormRecord\CollectionFactory as FormRecordCollectionFactory;
use Alekseon\CustomFormsEmailNotification\Model\EmailNotification;
use Alekseon\CustomFormsEmailNotification\Model\EmailNotificationFactory as EmailNotificationFactory;
use Alekseon\CustomFormsEmailNotification\Model\ResourceModel\EmailNotification as EmailNotificationResourceModel;
use Alekseon\CustomFormsEmailNotification\Model\ResourceModel\EmailNotification\CollectionFactory as EmailNotificationCollectionFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\State;
use Magento\Framework\Module\Dir;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Psr\Log\LoggerInterface;
use Stemcell\Datacollection\Helper\Email;
use Symfony\Component\Console\Command\Command;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
/**
* 通过邮件将所有询价表单数据用excel附件的形式发到指定邮箱
*/
class FormRecordsNotification
{
private array $formAttributesOptions = [];
private string $excelType = 'xlsx';
public function __construct(
private FormRecordCollectionFactory $formRecordCollectionFactory,
private FormCollection $formCollection,
private FormRecordAttributeCollectionFactory $formRecordAttributeCollectionFactory,
private FormRecordAttributeResourceModel $formRecordAttributeResourceModel,
private State $state,
private Email $email,
protected ScopeConfigInterface $scopeConfig,
private Dir $dir,
private EmailNotificationCollectionFactory $emailNotificationCollectionFactory,
private EmailNotificationResourceModel $emailNotificationResourceModel,
private EmailNotificationFactory $emailNotificationFactory,
private LoggerInterface $logger,
private TimezoneInterface $timezone
)
{
}
/**
* @param int $formId
* @return array
*/
protected function getSentFromRecordsId(int $formId)
{
$collection = $this->emailNotificationCollectionFactory->create()
->addFieldToSelect('record_id')
->addFieldToFilter('sent_status', EmailNotification::STATUS_SENT)
->addFieldToFilter('form_id', $formId);
return $collection->getColumnValues('record_id');
}
/**
* @param array $records
* @param array $headers
* @param string $title
* @return string
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
protected function generateExcelContent(array $records, array $headers, string $title)
{
$excelSaveDir = $this->dir->getDir('Stemcell_Datacollection') . '/data';
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$column = 'A';
foreach ($headers as $header) {
$sheet->setCellValue($column . '1', $header);
$column++;
}
$sheet->getStyle('A1:' . $column . '1')->getFont()->setBold(true);
$rowIndex = 2;
foreach ($records as $record) {
$column = 'A';
foreach ($headers as $header) {
$sheet->setCellValue($column . $rowIndex, $record[$header] ?? '');
$column++;
}
$rowIndex++;
}
$writer = new Xlsx($spreadsheet);
// $writer->save($excelSaveDir.DIRECTORY_SEPARATOR.$title);
ob_start();
$writer->save('php://output');
return ob_get_clean();
}
public function execute()
{
// $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_FRONTEND);
$receivers = (string)$this->scopeConfig->getValue('alekseon_custom_forms/new_entity_notification_email/to');
$receivers = array_filter(explode(',', $receivers), function (string $email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
});
if (empty($receivers)) {
$this->logger->critical('邮件发送询价表单数据。如果要使用此项功能,请在管理后台配置Alekseon Extensions->Custom Forms->New Entity Notification Email的Send Email To邮件接收人');
return;
}
$forms = $this->formCollection->addAttributeToSelect('title');
$excels = [];
$sentFormRecords = [];
foreach ($forms as $form) {
$formRecordAttributes = $this->formRecordAttributeCollectionFactory->create()
->addFieldToSelect(['attribute_code', 'frontend_input', 'frontend_label'])
->addFieldToFilter('form_id', $form->getId())
->setOrder('sort_order', 'ASC');
$attributes = [];
$headers = [];
foreach ($formRecordAttributes as $recordAttribute) {
$attributes[$recordAttribute->getAttributeCode()] = $recordAttribute;
$headers[] = $recordAttribute->getFrontendLabel();
}
$headers[] = '创建时间';
$formRecords = $this->formRecordCollectionFactory->create()->addAttributeToSelect(array_keys($attributes))
->addAttributeToFilter('form_id', $form->getId());
$sentRecords = $this->getSentFromRecordsId($form->getId());
if ($sentRecords) {
$formRecords->addAttributeToFilter('entity_id', ['nin' => $sentRecords]);
}
$records = [];
foreach ($formRecords as $formRecord) {
$record = [];
foreach ($formRecord->getData() as $attribute => $value) {
if (isset($attributes[$attribute])) {
if (in_array($attributes[$attribute]->getFrontendInput(), ['multiselect', 'select'])) {
if (!isset($this->formAttributesOptions[$attribute])) {
foreach ($this->formRecordAttributeResourceModel->getAttributeOptionValues($attributes[$attribute]) as $key => $dataObject) {
/* @var $dataObject \Magento\Framework\DataObject */
$this->formAttributesOptions[$attribute][$key] = $dataObject->getLabel();
}
}
$optionsId = explode(',', $value);
$optionsLabel = [];
foreach ($optionsId as $optionId) {
if ($optionId) {
$optionsLabel[] = $this->formAttributesOptions[$attribute][$optionId];
}
}
$formRecord->setData($attributes[$attribute]->getFrontendLabel(), implode(',', $optionsLabel));
$record[$attributes[$attribute]->getFrontendLabel()] = implode(',', $optionsLabel);
} else {
$record[$attributes[$attribute]->getFrontendLabel()] = $value;
}
}
if ($attribute == 'created_at') {
$convertedDate = $this->timezone->date(new \DateTime($value));
$record['创建时间'] = $convertedDate->format('Y-m-d H:i:s');
}
}
$records[] = $record;
$sentFormRecords[] = [
'form_id' => $form->getId(),
'record_id' => $formRecord->getId(),
'notification_type' => 'email',
'sent_status' => EmailNotification::STATUS_SENT,
'sent_at' => date('Y-m-d H:i:s'),
];
}
$noData = empty($records) ? '无数据-' : '';
$title = $noData.$form->getTitle(). '-' . date('Ymd') . '.' . $this->excelType;
$excels[] = [
'title' => $title,
'content' => $this->generateExcelContent($records, $headers, $title)
];
}
$this->email->sendEmailWithAttachment(
$receivers,
'小程序询价表单-' . date('Ymd'),
$excels
);
if (!empty($sentFormRecords)) {
foreach ($sentFormRecords as $sentFormRecord) {
$this->emailNotificationResourceModel->save(
$this->emailNotificationFactory->create()->setData($sentFormRecord)
);
}
}
}
}
@@ -0,0 +1,97 @@
<?php
namespace Stemcell\Datacollection\Helper;
use Alekseon\CustomFormsEmailNotification\Block\Adminhtml\Form\Edit\Tab\ConfirmationEmail;
use Laminas\Mime\Message;
use Laminas\Mime\Mime;
use Laminas\Mime\Part;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Filesystem;
use Magento\Framework\Exception\MailException;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Store\Model\StoreManagerInterface;
use \Magento\Framework\App\Helper\Context;
class Email extends \Magento\Framework\App\Helper\AbstractHelper
{
const FORM_RECORDS_NOTIFICATION_TEMPLATE = 'alekseon_custom_form_records_notification_email_template';
public function __construct(
private TransportBuilder $transportBuilder,
private StateInterface $inlineTranslation,
private StoreManagerInterface $storeManager,
private Filesystem $filesystem,
Context $context
) {
parent::__construct($context);
}
/**
* 发送带Excel附件的邮件
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function sendEmailWithAttachment(array $recipientEmail, string $recipientName, array $excels)
{
$this->inlineTranslation->suspend();
try {
$storeId = $this->storeManager->getStore()->getId();
// 邮件变量
$templateVars = [
'emailTitle' => $recipientName,
'recordHtml' => '<p>邮件内容</p>'
];
$templateId = self::FORM_RECORDS_NOTIFICATION_TEMPLATE;
// 发件人信息(定义在 Stores > Configuration > General > Store Email Addresses)
$from = [
'email' => $this->scopeConfig->getValue('trans_email/ident_general/email'),
'name' => 'Stemcell'
];
// 创建 Transport
$transport = $this->transportBuilder
->setTemplateIdentifier($templateId)
->setTemplateOptions([
'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
'store' => $storeId
])
->setTemplateVars($templateVars)
->setFromByScope($from)
->addTo($recipientEmail)
->getTransport();
$mail = $transport->getMessage();
$body = new Message();
foreach ($excels as $excel) {
if (empty($excel['content'])) {
echo $excel['title'].PHP_EOL;
}
$attachment = new Part($excel['content']);
$attachment->type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
$attachment->disposition = Mime::DISPOSITION_ATTACHMENT;
$attachment->encoding = Mime::ENCODING_BASE64;
$attachment->filename = mb_convert_encoding($excel['title'], 'GB2312');
// $body->addPart(new Part(' '));
$body->addPart($attachment);
}
$mail->setBody($body);
$transport->sendMessage();
$this->inlineTranslation->resume();
return true;
} catch (MailException $e) {
$this->inlineTranslation->resume();
throw new \Exception(__('邮件发送失败: %1', $e->getMessage()));
}
}
}
@@ -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);
}
}
+176
View File
@@ -0,0 +1,176 @@
# Stemcell_Datacollection Module
这是一个Magento2数据收集模块,提供了基本的WebAPI接口,支持多种表单类型的数据收集。
## 功能特性
- 提供POST API接口用于数据收集
- 支持Inquiry表单数据收集
- 支持默认数据收集(保存到日志文件)
- 支持匿名访问
- 数据验证和错误处理
## 安装
第一步:composer require alekseon/custom-forms-builder
第二步:
php bin/magento module:enable Alekseon_AlekseonEav Alekseon_CustomFormsBuilder Alekseon_CustomFormsEmailNotification Alekseon_CustomFormsStatistics
第三步:php bin/magento setup:upgrade
第四步:php bin/magento module:enable Stemcell_Datacollection
第五步:php bin/magento setup:upgrade
## API接口
### 1. 默认数据收集
**URL:** `POST /rest/V1/datacollection/submit`
**参数:**
- `data` (string): 要收集的数据内容
- `formType` (string, 可选): 表单类型,默认为 'default'
**示例请求:**
```bash
curl -X POST "https://your-domain.com/rest/V1/datacollection/submit" \
-H "Content-Type: application/json" \
-d '{"data": "测试数据内容"}'
```
### 2. Inquiry表单数据收集
**URL:** `POST /rest/V1/datacollection/inquiry`
**参数:**
- `data` (string): JSON格式的inquiry表单数据
- `formType` (string): 设置为 'inquiry'
**Inquiry表单字段:**
- `inquiry_company`: 公司名称
- `inquiry_email`: 邮箱地址
- `inquiry_mobile`: 手机号码
- `inquiry_province`: 省份
- `inquiry_subject_group`: 主题组
- `inquiry_username`: 用户名
**示例请求:**
```bash
curl -X POST "https://your-domain.com/rest/V1/datacollection/inquiry" \
-H "Content-Type: application/json" \
-d '{
"data": "{\"inquiry_company\":\"测试公司\",\"inquiry_email\":\"test@example.com\",\"inquiry_mobile\":\"13800138000\",\"inquiry_province\":\"北京\",\"inquiry_subject_group\":\"产品咨询\",\"inquiry_username\":\"张三\",\"inquiry_product_sku\":\"AKD732894723\",\"inquiry_product_name\":\"商品名称123456测试\"}",
"formType": "inquiry"
}'
```
### 3. Lecture表单数据收集
**URL:** `POST /rest/V1/datacollection/lecture`
**参数:**
- `data` (string): JSON格式的lecture表单数据
- `formType` (string): 设置为 'lecture'
**Lecture表单字段:**
- `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)
**示例请求:**
```bash
curl -X POST "https://your-domain.com/rest/V1/datacollection/lecture" \
-H "Content-Type: application/json" \
-d '{
"data": "{\"lecture_username\":\"李四\",\"lecture_company\":\"生物科技公司\",\"lecture_subject_group\":\"细胞生物学\",\"lecture_province\":\"上海\",\"lecture_email\":\"lisi@biotech.com\",\"lecture_mobile\":\"13900139000\",\"lecture_species_studied\":\"人类,小鼠,大鼠\",\"lecture_cell_type\":\"干细胞\",\"lecture_apply_topics\":\"细胞治疗,再生医学\",\"lecture_the_way\":\"线上讲座\"}",
"formType": "lecture"
}'
```
**响应示例:**
```json
"Inquiry data collected successfully (Record ID: 123)"
```
## 数据存储
### Inquiry表单数据
- 表单记录存储在 `alekseon_custom_form_record` 表
- 字段值存储在 `alekseon_custom_form_record_entity_varchar` 表
- 字段定义存储在 `alekseon_custom_form_record_attribute` 表
### Lecture表单数据
- 表单记录存储在 `alekseon_custom_form_record` 表
- varchar类型字段值存储在 `alekseon_custom_form_record_entity_varchar` 表
- select类型字段值存储在 `alekseon_custom_form_record_entity_int` 表(存储option_id)
- multiselect类型字段值存储在 `alekseon_custom_form_record_entity_varchar` 表(存储逗号分隔的option_id)
- 字段定义存储在 `alekseon_custom_form_record_attribute` 表
- 选项值存储在 `alekseon_custom_form_record_attribute_option` 和 `alekseon_custom_form_record_attribute_option_value` 表
### 默认数据
- 接收到的数据会保存在 `var/log/datacollection/` 目录下
- 每个请求会创建一个带时间戳的日志文件
## 安装说明
1. 将模块文件复制到 `app/code/Stemcell/Datacollection/` 目录
2. 运行以下命令启用模块:
```bash
php bin/magento module:enable Stemcell_Datacollection
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush
```
## 文件结构
```
Stemcell_Datacollection/
├── Api/
│ └── DataCollectionInterface.php
├── Model/
│ ├── DataCollection.php
│ └── Type/
│ ├── Inquiry.php
│ └── Lecture.php
├── etc/
│ ├── module.xml
│ ├── webapi.xml
│ └── di.xml
├── composer.json
├── registration.php
└── README.md
```
## 扩展说明
### 添加新的表单类型
1. 在 `Model/Type/` 目录下创建新的表单模型类
2. 在 `DataCollection.php` 中添加新的表单类型处理逻辑
3. 在 `webapi.xml` 中添加新的API路由(可选)
### 表单模型要求
新的表单模型类需要实现以下方法:
- `processData($data)`: 处理表单数据
- `validateData($data)`: 验证表单数据
- `getFieldsConfig()`: 获取字段配置
## 注意事项
- 确保Alekseon_CustomFormsBuilder模块已正确安装
- Inquiry表单必须在后台创建,标识符为 'inquiry'
- Lecture表单必须在后台创建,标识符为 'lecture'
- Inquiry表单所有字段必须是varchar类型
- Lecture表单支持varchar、select和multiselect字段类型
- 生产环境使用前请根据实际需求进行修改
- 默认允许匿名访问,如需权限控制请修改 `webapi.xml` 中的资源配置
## 通过邮件将所有询价表单数据用excel附件的形式发到指定邮箱
- 代码再Stemcell\Datacollection\Cron\FormRecordsNotification
- 需要去管理后台配置Alekseon Extensions->Custom Forms->New Entity Notification Email的Send Email To邮件接收人
@@ -0,0 +1,200 @@
<?php
namespace Stemcell\Datacollection\Setup\Patch\Data;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\App\ResourceConnection;
class InitializationData implements DataPatchInterface
{
/**
* @var ResourceConnection
*/
private $resource;
public function __construct(
ResourceConnection $resource
) {
$this->resource = $resource;
}
public function apply()
{
$connection = $this->resource->getConnection();
//$tableName = $this->resource->getTableName('your_table_name');
$sql = "INSERT INTO `alekseon_custom_form` (`created_at`, `identifier`, `group_fields_in`, `admin_note`)
VALUES
('2025-08-25 15:58:32', 'Inquiry', 'fieldsets', NULL),
('2025-08-26 03:00:21', 'Lecture', 'fieldsets', NULL),
('2025-08-26 05:03:59', 'Livedemo', 'fieldsets', NULL);
";
$connection->query($sql);
$sql = "INSERT INTO `alekseon_custom_form_tab` (`label`, `form_id`)
VALUES
('stemcell_inquiry', '1'),
('stemcell_lecture', '2'),
('stemcell_livedemo', '3');
";
$connection->query($sql);
$sql = "INSERT INTO `alekseon_custom_form_record_attribute` (`entity_type_code`, `attribute_code`, `frontend_input`, `backend_type`, `frontend_label`, `source_model`, `backend_model`, `scope`, `is_required`, `visible_in_grid`, `sort_order`, `note`, `is_user_defined`, `default_value`, `is_unique`, `frontend_class`, `is_wysiwyg_enabled`, `group_code`, `input_validator`, `attribute_extra_params`, `has_option_codes`, `form_id`, `identifier`, `input_visibility`)
VALUES
('alekseon_custom_form_record', 'inquiry_username', 'text', 'varchar', '姓名', NULL, NULL, '0', '1', '1', '1', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', 'username', '1'),
('alekseon_custom_form_record', 'inquiry_mobile', 'text', 'varchar', '手机号码', NULL, NULL, '0', '1', '1', '10', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', 'mobile', '1'),
('alekseon_custom_form_record', 'inquiry_email', 'text', 'varchar', '电子邮箱', NULL, NULL, '0', '1', '1', '20', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', 'email', '1'),
('alekseon_custom_form_record', 'inquiry_company', 'text', 'varchar', '公司单位', NULL, NULL, '0', '1', '1', '30', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', 'company', '1'),
('alekseon_custom_form_record', 'inquiry_subject_group', 'text', 'varchar', '课题组', NULL, NULL, '0', '0', '1', '40', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', 'subject_group', '1'),
('alekseon_custom_form_record', 'inquiry_province', 'text', 'varchar', '所在省份', NULL, NULL, '0', '1', '1', '50', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', 'province', '1'),
('alekseon_custom_form_record', 'lecture_username', 'text', 'varchar', '姓名', NULL, NULL, '0', '0', '1', '1', NULL, '1', NULL, '0', NULL, '0', '2', '0', '{\"input_params\":[]}', '0', '2', 'username', '1'),
('alekseon_custom_form_record', 'lecture_company', 'text', 'varchar', '单位', NULL, NULL, '0', '1', '1', '10', NULL, '1', NULL, '0', NULL, '0', '2', '0', '{\"input_params\":[]}', '0', '2', 'company', '1'),
('alekseon_custom_form_record', 'lecture_subject_group', 'text', 'varchar', '课题组', NULL, NULL, '0', '0', '1', '20', NULL, '1', NULL, '0', NULL, '0', '2', '0', '{\"input_params\":[]}', '0', '2', 'subject_group', '1'),
('alekseon_custom_form_record', 'lecture_province', 'text', 'varchar', '省份', NULL, NULL, '0', '1', '1', '30', NULL, '1', NULL, '0', NULL, '0', '2', '0', '{\"input_params\":[]}', '0', '2', 'province', '1'),
('alekseon_custom_form_record', 'lecture_email', 'text', 'varchar', '邮件', NULL, NULL, '0', '1', '1', '40', NULL, '1', NULL, '0', NULL, '0', '2', '0', '{\"input_params\":[]}', '0', '2', 'email', '1'),
('alekseon_custom_form_record', 'lecture_mobile', 'text', 'varchar', '手机', NULL, NULL, '0', '0', '1', '50', NULL, '1', NULL, '0', NULL, '0', '2', '0', '{\"input_params\":[]}', '0', '2', 'mobile', '1'),
('alekseon_custom_form_record', 'lecture_species_studied', 'multiselect', 'varchar', '研究的物种', NULL, NULL, '0', '0', '1', '60', NULL, '1', '', '0', NULL, '0', '2', NULL, '{\"input_params\":[]}', '0', '2', 'species_studied', '1'),
('alekseon_custom_form_record', 'lecture_cell_type', 'select', 'int', '研究的细胞类型', NULL, NULL, '0', '0', '1', '70', NULL, '1', '', '0', NULL, '0', '2', NULL, '{\"input_params\":[]}', '0', '2', 'cell_type', '1'),
('alekseon_custom_form_record', 'lecture_apply_topics', 'text', 'varchar', '需要申请的讲座主题', NULL, NULL, '0', '0', '1', '80', NULL, '1', NULL, '0', NULL, '0', '2', '0', '{\"input_params\":[]}', '0', '2', 'apply_topics', '1'),
('alekseon_custom_form_record', 'lecture_the_way', 'select', 'int', '希望通过哪种方式进行讲座', NULL, NULL, '0', '0', '1', '90', NULL, '1', '', '0', NULL, '0', '2', NULL, '{\"input_params\":[]}', '0', '2', 'the_way', '1'),
('alekseon_custom_form_record', 'livedemo_username', 'text', 'varchar', '姓名', NULL, NULL, '0', '0', '1', '10', NULL, '1', NULL, '0', NULL, '0', '3', '0', '{\"input_params\":[]}', '0', '3', NULL, '1'),
('alekseon_custom_form_record', 'livedemo_company', 'text', 'varchar', '单位', NULL, NULL, '0', '0', '1', '20', NULL, '1', NULL, '0', NULL, '0', '3', '0', '{\"input_params\":[]}', '0', '3', NULL, '1'),
('alekseon_custom_form_record', 'livedemo_subject_group', 'text', 'varchar', '课题组', NULL, NULL, '0', '0', '1', '30', NULL, '1', NULL, '0', NULL, '0', '3', '0', '{\"input_params\":[]}', '0', '3', NULL, '1'),
('alekseon_custom_form_record', 'livedemo_province', 'text', 'varchar', '省份', NULL, NULL, '0', '0', '1', '40', NULL, '1', NULL, '0', NULL, '0', '3', '0', '{\"input_params\":[]}', '0', '3', NULL, '1'),
('alekseon_custom_form_record', 'livedemo_email', 'text', 'varchar', '邮箱', NULL, NULL, '0', '0', '1', '50', NULL, '1', NULL, '0', NULL, '0', '3', '0', '{\"input_params\":[]}', '0', '3', NULL, '1'),
('alekseon_custom_form_record', 'livedemo_mobile', 'text', 'varchar', '手机', NULL, NULL, '0', '0', '1', '60', NULL, '1', NULL, '0', NULL, '0', '3', '0', '{\"input_params\":[]}', '0', '3', NULL, '1'),
('alekseon_custom_form_record', 'livedemo_product_show', 'select', 'int', '需要申请上门演示的产品', NULL, NULL, '0', '0', '1', '70', NULL, '1', '', '0', NULL, '0', '3', NULL, '{\"input_params\":[]}', '0', '3', NULL, '1'),
('alekseon_custom_form_record', 'livedemo_species_studied', 'multiselect', 'varchar', '研究的物种', NULL, NULL, '0', '0', '1', '80', NULL, '1', '', '0', NULL, '0', '3', NULL, '{\"input_params\":[]}', '0', '3', NULL, '1'),
('alekseon_custom_form_record', 'livedemo_cell_type', 'select', 'int', '研究的细胞类型', NULL, NULL, '0', '0', '1', '90', NULL, '1', '', '0', NULL, '0', '3', NULL, '{\"input_params\":[]}', '0', '3', NULL, '1');
";
$connection->query($sql);
$sql = "INSERT INTO `alekseon_custom_form_entity_int` (`attribute_id`, `store_id`, `entity_id`, `value`)
VALUES
('4', '0', '1', '0'),
('9', '0', '1', '0'),
('2', '0', '1', '0'),
('4', '0', '2', '0'),
('9', '0', '2', '0'),
('2', '0', '2', '0'),
('4', '0', '3', '0'),
('9', '0', '3', '0'),
('2', '0', '3', '0');
";
$connection->query($sql);
$sql = "INSERT INTO `alekseon_custom_form_entity_text` (`attribute_id`, `store_id`, `entity_id`, `value`)
VALUES
('8', '0', '1', ''),
('8', '0', '2', ''),
('8', '0', '3', '');
";
$connection->query($sql);
$sql = "INSERT INTO `alekseon_custom_form_entity_varchar` (`attribute_id`, `store_id`, `entity_id`, `value`)
VALUES
('1', '0', '1', '询价'),
('3', '0', '1', ''),
('6', '0', '1', ''),
('5', '0', '1', '0'),
('7', '0', '1', ''),
('1', '0', '2', '讲座申请'),
('3', '0', '2', ''),
('6', '0', '2', ''),
('5', '0', '2', '0'),
('7', '0', '2', ''),
('1', '0', '3', '现场演示'),
('3', '0', '3', ''),
('6', '0', '3', ''),
('5', '0', '3', '0'),
('7', '0', '3', '');
";
$connection->query($sql);
$sql = "INSERT INTO `alekseon_custom_form_record_attribute_option` (`attribute_id`, `sort_order`, `option_code`)
VALUES
('13', '1', ''),
('13', '2', ''),
('13', '3', ''),
('13', '4', ''),
('13', '5', ''),
('14', '1', ''),
('14', '2', ''),
('14', '3', ''),
('14', '4', ''),
('14', '5', ''),
('14', '6', ''),
('14', '7', ''),
('14', '8', ''),
('16', '1', ''),
('16', '2', ''),
('23', '1', ''),
('23', '2', ''),
('23', '3', ''),
('23', '4', ''),
('24', '1', ''),
('24', '2', ''),
('24', '3', ''),
('24', '4', ''),
('24', '5', ''),
('25', '1', ''),
('25', '2', ''),
('25', '3', ''),
('25', '4', ''),
('25', '5', ''),
('25', '6', ''),
('25', '7', ''),
('25', '8', '');
";
$connection->query($sql);
$sql = "INSERT INTO `alekseon_custom_form_record_attribute_option_value` (`option_id`, `store_id`, `value`)
VALUES
('1', '0', '人'),
('2', '0', '小鼠'),
('3', '0', '大鼠'),
('4', '0', '非人灵长类(NHP)'),
('5', '0', '其它'),
('6', '0', 'T细胞'),
('7', '0', 'B细胞'),
('8', '0', 'NK细胞'),
('9', '0', '单核细胞'),
('10', '0', 'PBMCs'),
('11', '0', 'iPSCs'),
('12', '0', 'CD34+造血干祖细胞'),
('13', '0', '其它'),
('14', '0', '线上'),
('15', '0', '线下'),
('16', '0', '细胞分选试剂盒'),
('17', '0', 'CellPore转染系统'),
('18', '0', 'RoboSep全自动细胞分选仪'),
('19', '0', 'STEMvison造血集落计数与成像仪'),
('20', '0', '人'),
('21', '0', '小鼠'),
('22', '0', '大鼠'),
('23', '0', '非人灵长类(NHP)'),
('24', '0', '其它'),
('25', '0', 'T细胞'),
('26', '0', 'B细胞'),
('27', '0', 'NK细胞'),
('28', '0', '单核细胞'),
('29', '0', 'PBMCs'),
('30', '0', 'iPSCs'),
('31', '0', 'CD34+造血干祖细胞'),
('32', '0', '其它');
";
$connection->query($sql);
//$connection->insert($tableName, $data);
}
public static function getDependencies()
{
return [];
}
public function getAliases()
{
return [];
}
}
@@ -0,0 +1,50 @@
<?php
namespace Stemcell\Datacollection\Setup\Patch\Data;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\App\ResourceConnection;
class InquiryAddFieldData implements DataPatchInterface
{
/**
* @var ResourceConnection
*/
private $resource;
public function __construct(
ResourceConnection $resource
) {
$this->resource = $resource;
}
public function apply()
{
$connection = $this->resource->getConnection();
//$tableName = $this->resource->getTableName('your_table_name');
$sql = "
INSERT INTO `alekseon_custom_form_record_attribute` (`entity_type_code`, `attribute_code`, `frontend_input`, `backend_type`, `frontend_label`, `source_model`, `backend_model`, `scope`, `is_required`, `visible_in_grid`, `sort_order`, `note`, `is_user_defined`, `default_value`, `is_unique`, `frontend_class`, `is_wysiwyg_enabled`, `group_code`, `input_validator`, `attribute_extra_params`, `has_option_codes`, `form_id`, `identifier`, `input_visibility`)
VALUES
('alekseon_custom_form_record', 'inquiry_product_sku', 'text', 'varchar', '询价商品SKU', NULL, NULL, '0', '0', '1', '60', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', 'product_sku', '1'),
('alekseon_custom_form_record', 'inquiry_product_name', 'text', 'varchar', '询价商品名称', NULL, NULL, '0', '0', '1', '70', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', 'product_name', '1'),
('alekseon_custom_form_record', 'inquiry_customer_id', 'text', 'varchar', '用户ID', NULL, NULL, '0', '0', '1', '0', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', '1756286643_1', '1'),
('alekseon_custom_form_record', 'inquiry_incrementid', 'text', 'varchar', '询价编号', NULL, NULL, '0', '0', '1', '80', NULL, '1', NULL, '0', NULL, '0', '1', '0', '{\"input_params\":[]}', '0', '1', '1756286643_2', '1');
";
$connection->query($sql);
//$connection->insert($tableName, $data);
}
public static function getDependencies()
{
return [
InitializationData::class
];
}
public function getAliases()
{
return [];
}
}
@@ -0,0 +1,20 @@
{
"name": "stemcell/module-datacollection",
"version": "1.0.0",
"description": "Stemcell Data Collection Module",
"type": "magento2-module",
"require": {
"magento/framework": "*"
},
"license": [
"Proprietary"
],
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Stemcell\\Datacollection\\": ""
}
}
}
@@ -0,0 +1,17 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Alekseon sp. z o.o.
* http://www.alekseon.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<group id="default">
<job name="form_records_notification_emails" instance="Stemcell\Datacollection\Cron\FormRecordsNotification" method="execute">
<schedule>0 16 * * *</schedule>
</job>
<job name="form_records_notification_emails_2" instance="Stemcell\Datacollection\Cron\FormRecordsNotification" method="execute">
<schedule>30 11 * * *</schedule>
</job>
</group>
</config>
@@ -0,0 +1,4 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Stemcell\Datacollection\Api\DataCollectionInterface" type="Stemcell\Datacollection\Model\DataCollection" />
</config>
@@ -0,0 +1,10 @@
<?xml version="1.0"?>
<!--
/**
* Copyright © Alekseon sp. z o.o.
* http://www.alekseon.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
<template id="alekseon_custom_form_records_notification_email_template" label="每天定时发新询价数据给指定邮箱" file="form_records_notification.html" type="html" module="Stemcell_Datacollection" area="frontend"/>
</config>
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Stemcell_Datacollection">
<sequence>
<module name="Magento_Webapi"/>
<module name="Alekseon_CustomFormsBuilder"/>
</sequence>
</module>
</config>
@@ -0,0 +1,44 @@
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<!-- Simple Data Collection API -->
<route url="/V1/datacollection/submit" method="POST">
<service class="Stemcell\Datacollection\Api\DataCollectionInterface" method="submitData"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
<!-- Inquiry Form Data Collection API -->
<route url="/V1/datacollection/inquiry" method="POST">
<service class="Stemcell\Datacollection\Api\DataCollectionInterface" method="submitData"/>
<resources>
<resource ref="self"/>
</resources>
</route>
<!-- Lecture Form Data Collection API -->
<route url="/V1/datacollection/lecture" method="POST">
<service class="Stemcell\Datacollection\Api\DataCollectionInterface" method="submitData"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
<!-- Livedemo Form Data Collection API -->
<route url="/V1/datacollection/livedemo" method="POST">
<service class="Stemcell\Datacollection\Api\DataCollectionInterface" method="submitData"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
<!-- Get My Inquiry Records API (Private) -->
<route url="/V1/datacollection/my-inquiry-records" method="POST">
<service class="Stemcell\Datacollection\Api\DataCollectionInterface" method="getMyInquiryRecords"/>
<resources>
<resource ref="self"/>
</resources>
</route>
</routes>
@@ -0,0 +1,18 @@
<?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)
*/
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Stemcell_Datacollection', __DIR__);
@@ -0,0 +1,4 @@
<!--@subject {{trans "%title" title=$emailTitle}} @-->
<p>
{{var recordHtml|raw}}
</p>