Files
opnform-host-nginx/api/app/Service/Forms/FormCleaner.php
Chirag Chhatrala ff1a4d17d8 Partial submissions (#705)
* Implement partial form submissions feature

* Add status filtering for form submissions

* Add Partial Submission in Analytics

* improve partial submission

* fix lint

* Add type checking for submission ID in form submission job

* on form stats Partial Submissions only if enable

* Partial Submissions is PRO Feature

* Partial Submissions is PRO Feature

* improvement migration

* Update form submission status labels to 'Submitted' and 'In Progress'

* start partial sync when dataFormValue update

* badge size xs

* Refactor partial submission hash management

* Refactor partial form submission handling in PublicFormController

* fix submissiona

* Refactor form submission ID handling and metadata processing

- Improve submission ID extraction and decoding across controllers
- Add robust handling for submission hash and ID conversion
- Enhance metadata processing in StoreFormSubmissionJob
- Simplify submission storage logic with clearer metadata extraction
- Minor UI improvements in FormSubmissions and OpenTable components

* Enhance form submission settings UI with advanced partial submission options

- Restructure partial submissions toggle with more descriptive label
- Add advanced submission options section with Pro tag
- Improve help text for partial submissions feature
- Update ProTag with more detailed upgrade modal description

* Refactor partial form submission sync mechanism

- Improve partial submission synchronization in usePartialSubmission composable
- Replace interval-based sync with Vue's reactive watch
- Add robust handling for different form data input patterns
- Implement onBeforeUnmount hook for final sync attempt
- Enhance data synchronization reliability and performance

* Improve partial form submission validation and synchronization

* fix lint

* Refactor submission identifier processing in PublicFormController

- Updated the docblock for the method responsible for processing submission identifiers to clarify its functionality. The method now explicitly states that it converts a submission hash or string ID into a numeric submission_id, ensuring consistent internal storage format.

These changes aim to improve code documentation and enhance understanding of the method's purpose and behavior.

* Enhance Form Logic Condition Checker to Exclude Partial Submissions

- Updated the query in FormLogicConditionChecker to exclude submissions with a status of 'partial', ensuring that only complete submissions are processed.
- Minor formatting adjustment in the docblock of PublicFormController for improved clarity.

These changes aim to refine submission handling and enhance the accuracy of form logic evaluations.

* Partial Submission Test

* Refactor FormSubmissionController and PartialSubmissionTest for Consistency

- Updated the `FormSubmissionController` to improve code consistency by adjusting the formatting of anonymous functions in the `filter` and `first` methods.
- Modified `PartialSubmissionTest` to simplify the `Storage::fake()` method call, removing the unnecessary 'local' parameter for better clarity.

These changes aim to enhance code readability and maintainability across the form submission handling and testing components.

* Enhance FormSubmissionController and EditSubmissionTest for Clarity

- Added validation to the `FormSubmissionController` by introducing `$submissionData = $request->validated();` to ensure that only validated data is processed for form submissions.
- Improved code readability in the `FormSubmissionController` by adjusting the formatting of anonymous functions in the `filter` and `first` methods.
- Removed unnecessary blank lines in the `EditSubmissionTest` to streamline the test setup.

These changes aim to enhance data integrity during form submissions and improve overall code clarity and maintainability.

---------

Co-authored-by: Julien Nahum <julien@nahum.net>
2025-04-28 17:33:55 +02:00

292 lines
8.1 KiB
PHP

<?php
namespace App\Service\Forms;
use App\Http\Requests\UserFormRequest;
use App\Http\Resources\FormResource;
use App\Models\Forms\Form;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Stevebauman\Purify\Facades\Purify;
use function collect;
class FormCleaner
{
/**
* All the performed cleanings
*
* @var bool
*/
private array $cleanings = [];
private array $data;
// For remove keys those have empty value
private array $customKeys = ['seo_meta'];
private array $formDefaults = [
'no_branding' => false,
'database_fields_update' => null,
'editable_submissions' => false,
'custom_code' => null,
'seo_meta' => [],
'redirect_url' => null,
'enable_partial_submissions' => false,
];
private array $formNonTrialingDefaults = [
// Custom code protection disabled for now
// 'custom_code' => null,
];
private array $fieldDefaults = [
// 'name' => '' TODO: prevent name changing, use alias for column and keep original name as it is
'file_upload' => false,
];
private array $cleaningMessages = [
// For form
'no_branding' => 'OpenForm branding is not hidden.',
'database_fields_update' => 'Form submission will only create new records (no updates).',
'editable_submissions' => 'Users will not be able to edit their submissions.',
'custom_code' => 'Custom code was disabled',
'seo_meta' => 'Custom SEO was disabled',
'redirect_url' => 'Redirect Url was disabled',
'enable_partial_submissions' => 'Partial submissions were disabled',
// For fields
'file_upload' => 'Link field is not a file upload.',
'custom_block' => 'The custom block was removed.',
];
/**
* Returns form data after request ingestion
*/
public function getData(): array
{
return $this->data;
}
/**
* Returns true if at least one cleaning was done
*/
public function hasCleaned(): bool
{
return count($this->cleanings) > 0;
}
/**
* Returns the messages for each cleaning step performed
*/
public function getPerformedCleanings(): array
{
$cleaningMsgs = [];
foreach ($this->cleanings as $key => $val) {
$cleaningMsgs[$key] = collect($val)->map(function ($cleaning) {
return $this->cleaningMessages[$cleaning];
});
}
return $cleaningMsgs;
}
/**
* Removes form pro features from data if user isn't pro
*/
public function processRequest(UserFormRequest $request): FormCleaner
{
$data = $request->validated();
$this->data = $this->commonCleaning($data);
return $this;
}
/**
* Create form cleaner instance from existing form
*/
public function processForm(Request $request, Form $form): FormCleaner
{
$data = (new FormResource($form))->toArray($request);
$this->data = $this->commonCleaning($data);
return $this;
}
private function isPro(Workspace $workspace)
{
return $workspace->is_pro;
}
private function isTrialing(Workspace $workspace)
{
return $workspace->is_trialing;
}
/**
* Dry run celanings
*
* @param User|null $user
*/
public function simulateCleaning(Workspace $workspace): FormCleaner
{
if ($this->isTrialing($workspace)) {
$this->data = $this->removeNonTrialingFeatures($this->data, true);
}
if (!$this->isPro($workspace)) {
$this->data = $this->removeProFeatures($this->data, true);
}
return $this;
}
/**
* Perform Cleanigns
*
* @param User|null $user
* @return $this|array
*/
public function performCleaning(Workspace $workspace): FormCleaner
{
if ($this->isTrialing($workspace)) {
$this->data = $this->removeNonTrialingFeatures($this->data, true);
}
if (!$this->isPro($workspace)) {
$this->data = $this->removeProFeatures($this->data);
}
return $this;
}
/**
* Clean all forms:
* - Escape html of custom text block
*/
private function commonCleaning(array $data)
{
foreach ($data['properties'] as &$property) {
if ($property['type'] == 'nf-text' && isset($property['content'])) {
$property['content'] = Purify::clean($property['content']);
}
}
return $data;
}
private function removeNonTrialingFeatures(array $data, $simulation = false)
{
$this->clean($data, $this->formNonTrialingDefaults);
return $data;
}
private function removeProFeatures(array $data, $simulation = false)
{
$this->cleanForm($data, $simulation);
$this->cleanProperties($data, $simulation);
return $data;
}
private function cleanForm(array &$data, $simulation = false): void
{
$this->clean($data, $this->formDefaults, $simulation);
}
private function cleanProperties(array &$data, $simulation = false): void
{
foreach ($data['properties'] as $key => &$property) {
/*
// Remove pro custom blocks
if (\Str::of($property['type'])->startsWith('nf-')) {
$this->cleanings[$property['name']][] = 'custom_block';
if (!$simulation) {
unset($data['properties'][$key]);
}
continue;
}
// Remove logic
if (($property['logic']['conditions'] ?? null) != null || ($property['logic']['actions'] ?? []) != []) {
$this->cleanings[$property['name']][] = 'logic';
if (!$simulation) {
unset($data['properties'][$key]['logic']);
}
}
*/
// Clean pro field options
$this->cleanField($property, $this->fieldDefaults, $simulation);
}
}
private function clean(array &$data, array $defaults, $simulation = false): void
{
foreach ($defaults as $key => $value) {
// Get value from form
$formVal = Arr::get($data, $key);
// Transform customkeys values
$formVal = $this->cleanCustomKeys($key, $formVal);
// Transform boolean values
$formVal = (($formVal === 0 || $formVal === '0') ? false : $formVal);
$formVal = (($formVal === 1 || $formVal === '1') ? true : $formVal);
if (!is_null($formVal) && $formVal !== $value) {
if (!isset($this->cleanings['form'])) {
$this->cleanings['form'] = [];
}
$this->cleanings['form'][] = $key;
// If not a simulation, do the cleaning
if (!$simulation) {
Arr::set($data, $key, $value);
}
}
}
}
private function cleanField(array &$data, array $defaults, $simulation = false): void
{
foreach ($defaults as $key => $value) {
if (isset($data[$key]) && Arr::get($data, $key) !== $value) {
$this->cleanings[$data['name']][] = $key;
if (!$simulation) {
Arr::set($data, $key, $value);
}
}
}
// Remove pro types columns
/*foreach (['files'] as $proType) {
if ($data['type'] == $proType && (!isset($data['hidden']) || !$data['hidden'])) {
$this->cleanings[$data['name']][] = $proType;
if (!$simulation) {
$data['hidden'] = true;
}
}
}*/
}
// Remove keys those have empty value
private function cleanCustomKeys($key, $formVal)
{
if (in_array($key, $this->customKeys) && $formVal !== null) {
$newVal = [];
foreach ($formVal as $k => $val) {
if ($val) {
$newVal[$k] = $val;
}
}
return $newVal;
}
return $formVal;
}
}