Skip to content

Commit

Permalink
Refactor: Merge block level attributes (#7361)
Browse files Browse the repository at this point in the history
  • Loading branch information
pauloiankoski authored Apr 23, 2024
1 parent 2f9b92f commit 8065dde
Show file tree
Hide file tree
Showing 8 changed files with 128 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public function __invoke(DonationForm $donationForm)
}

/**
* @unreleased Update to store donation levels with descriptions
* @since 3.0.0 update with dynamic values from amount field
* @since 3.0.0
*/
Expand All @@ -43,7 +44,8 @@ public function storeDonationLevels(DonationForm $donationForm)
'_give_id' => [
'level_id' => $index,
],
'_give_amount' => $donationLevel
'_give_amount' => $donationLevel['value'],
'_give_text' => $donationLevel['label'] ?? '',
];
}, $donationLevels, array_keys($donationLevels));

Expand Down
80 changes: 80 additions & 0 deletions src/DonationForms/Migrations/UpdateDonationLevelsSchema.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace Give\DonationForms\Migrations;

use Give\DonationForms\Repositories\DonationFormRepository;
use Give\Framework\Migrations\Contracts\Migration;

/**
* Update the donation levels schema to support descriptions
*
* @unreleased
*/
class UpdateDonationLevelsSchema extends Migration
{
/**
* @inheritdoc
*/
public static function id()
{
return 'donation-forms-donation-levels-schema';
}

/**
* @inheritdoc
*/
public static function title()
{
return 'Update Donation Levels schema to support descriptions';
}

/**
* @inheritdoc
*/
public static function timestamp()
{
return strtotime('2024-04-22');
}

/**
* @unreleased
*/
public function run()
{
$forms = give(DonationFormRepository::class)
->prepareQuery()
->whereIsNotNull("give_formmeta_attach_meta_fields.meta_value")
->getAll();

if ( ! $forms) {
return;
}

foreach ($forms as $form) {
$amountBlock = $form->blocks->findByName('givewp/donation-amount');

if ( ! $amountBlock) {
continue;
}

$blockAttributes = $amountBlock->getAttributes();
$levels = $blockAttributes["levels"];
$defaultLevel = $blockAttributes["defaultLevel"] ?? 0;

if ( ! is_array($levels) || empty($levels) || isset($levels[0]['value'])) {
continue;
}

$levels = array_map(function($level) use ($defaultLevel) {
return [
'value' => $level,
'label' => '',
'checked' => $level === $defaultLevel,
];
}, $levels);

$amountBlock->setAttribute('levels', $levels);
$form->save();
}
}
}
4 changes: 3 additions & 1 deletion src/DonationForms/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
use Give\DonationForms\DataTransferObjects\DonationFormPreviewRouteData;
use Give\DonationForms\DataTransferObjects\DonationFormViewRouteData;
use Give\DonationForms\FormDesigns\ClassicFormDesign\ClassicFormDesign;
use Give\DonationForms\FormDesigns\TwoPanelStepsFormLayout\TwoPanelStepsFormLayout;
use Give\DonationForms\FormDesigns\MultiStepFormDesign\MultiStepFormDesign;
use Give\DonationForms\FormDesigns\TwoPanelStepsFormLayout\TwoPanelStepsFormLayout;
use Give\DonationForms\FormPage\TemplateHandler;
use Give\DonationForms\Migrations\CleanMultipleSlashesOnDB;
use Give\DonationForms\Migrations\RemoveDuplicateMeta;
use Give\DonationForms\Migrations\UpdateDonationLevelsSchema;
use Give\DonationForms\Repositories\DonationFormRepository;
use Give\DonationForms\Routes\AuthenticationRoute;
use Give\DonationForms\Routes\DonateRoute;
Expand Down Expand Up @@ -76,6 +77,7 @@ public function boot()
give(MigrationsRegister::class)->addMigrations([
CleanMultipleSlashesOnDB::class,
RemoveDuplicateMeta::class,
UpdateDonationLevelsSchema::class,
]);
}

Expand Down
26 changes: 19 additions & 7 deletions src/FormBuilder/resources/js/form-builder/src/blocks.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,26 @@
"attributes": {
"label": "Donation Amount",
"levels": [
10,
25,
50,
100,
250,
500
{
"value": 10,
"checked": true
},
{
"value": 25
},
{
"value": 50
},
{
"value": 100
},
{
"value": 250
},
{
"value": 500
}
],
"defaultLevel": 10,
"priceOption": "multi",
"setPrice": 25,
"customAmount": true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,17 @@ import cx from 'classnames';

const DonationLevels = ({
levels,
defaultLevel,
descriptionsEnabled,
descriptions,
}: {
levels: DonationAmountAttributes['levels'];
defaultLevel: DonationAmountAttributes['defaultLevel'];
descriptionsEnabled: DonationAmountAttributes['descriptionsEnabled'];
descriptions: DonationAmountAttributes['descriptions'];
}) => (
<LevelGrid descriptionsEnabled={descriptionsEnabled}>
{levels.map((level, index) => {
const levelAmount = formatCurrencyAmount(level.toString());
const hasDescriptions = descriptions?.length === levels?.length;
const levelAmount = formatCurrencyAmount(level?.value?.toString());

return (
<LevelButton selected={level === defaultLevel} key={index} descriptionsEnabled={descriptionsEnabled}>
<LevelButton selected={level.checked} key={index} descriptionsEnabled={descriptionsEnabled}>
<span
className={cx({
'give-donation-block__level__amount': descriptionsEnabled,
Expand All @@ -40,7 +35,7 @@ const DonationLevels = ({

{descriptionsEnabled && (
<span className={'give-donation-block__level__label'}>
{hasDescriptions ? descriptions[index] : __('Description goes here', 'give')}
{level.label ? level.label : __('Description goes here', 'give')}
</span>
)}
</LevelButton>
Expand Down Expand Up @@ -80,7 +75,6 @@ const Edit = ({attributes, setAttributes}) => {
const {
label = __('Donation Amount', 'give'),
levels,
defaultLevel,
priceOption,
setPrice,
customAmount,
Expand All @@ -90,7 +84,6 @@ const Edit = ({attributes, setAttributes}) => {
recurringLengthOfTime,
recurringOptInDefaultBillingPeriod,
recurringEnableOneTimeDonations,
descriptions,
descriptionsEnabled,
} = attributes as DonationAmountAttributes;

Expand Down Expand Up @@ -130,9 +123,7 @@ const Edit = ({attributes, setAttributes}) => {
{isMultiLevel && (
<DonationLevels
levels={levels}
defaultLevel={defaultLevel}
descriptionsEnabled={descriptionsEnabled}
descriptions={descriptions}
/>
)}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import {CurrencyControl} from '@givewp/form-builder/components/CurrencyControl';
import periodLookup from '../period-lookup';
import RecurringDonationsPromo from '@givewp/form-builder/promos/recurring-donations';
import {getFormBuilderWindowData} from '@givewp/form-builder/common/getWindowData';
import {useCallback, useState} from '@wordpress/element';
import {useCallback} from '@wordpress/element';
import type {OptionProps} from '@givewp/form-builder-library/build/OptionsPanel/types';
import {useEffect} from 'react';
import {useEffect, useState} from 'react';
import {DonationAmountAttributes} from '@givewp/form-builder/blocks/fields/amount/types';
import {subscriptionPeriod} from '@givewp/forms/registrars/templates/groups/DonationAmount/subscriptionPeriod';
import {OptionsPanel} from '@givewp/form-builder-library';
Expand Down Expand Up @@ -65,9 +65,7 @@ const Inspector = ({attributes, setAttributes}) => {
const {
label = __('Donation Amount', 'give'),
levels,
descriptions,
descriptionsEnabled = false,
defaultLevel,
priceOption,
setPrice,
customAmount,
Expand Down Expand Up @@ -125,59 +123,55 @@ const Inspector = ({attributes, setAttributes}) => {
const recurringGateways = gateways.filter((gateway) => gateway.supportsSubscriptions);
const isRecurringSupported = enabledGateways.some((gateway) => gateway.supportsSubscriptions);
const isRecurring = isRecurringSupported && recurringEnabled;
const hasDescriptions = descriptions?.length === levels?.length;

const [donationLevels, setDonationLevels] = useState<OptionProps[]>(
levels.map((level, index) => ({
levels.map((level) => ({
...level,
id: String(Math.floor(Math.random() * 1000000)),
label: hasDescriptions ? descriptions[index] : '',
value: level.toString(),
checked: defaultLevel === level,
value: level.value.toString(),
}))
);

const handleLevelAdded = () => {
const newLevelValue = levels.length ? String(Math.max(...levels) * 2) : '10';
const levelValues = levels.map((level) => Number(level.value));
const newLevelValue = levelValues.length ? String(Math.max(...levelValues) * 2) : '10';
const newLevel = {
id: String(Math.floor(Math.random() * 1000000)),
label:'',
label: '',
value: newLevelValue,
checked: false,
};

// If there are no levels, set the new level as the default.
if (!levels.length) {
newLevel.checked = true;
setAttributes({defaultLevel: Number(newLevelValue)});
}

setDonationLevels([...donationLevels, newLevel]);
setAttributes({levels: [...levels, Number(newLevelValue)]});
setAttributes({levels: [...levels, newLevel]});
};

const handleLevelRemoved = (level: OptionProps, index: number) => {
const newLevels = levels.filter((_, i) => i !== index);
const newDonationLevels = donationLevels.filter((_, i) => i !== index);

if (level.checked && newDonationLevels.length > 0) {
newDonationLevels[0].checked = true;
setAttributes({defaultLevel: Number(newDonationLevels[0].value)});
if (level.checked && newLevels.length > 0) {
newLevels[0].checked = true;
}

setDonationLevels(newDonationLevels);
setDonationLevels(newLevels);
setAttributes({levels: newLevels});
};

const handleLevelsChange = (options: OptionProps[]) => {
const checkedLevel = options.filter((option) => option.checked);
const newLevels = options.filter((option) => option.value).map((option) => Number(option.value));
const newDescriptions = options.map((option) => option.label);
const newLevels = options
.filter((option) => option.value)
.map((option) => ({
...option,
value: Number(option.value),
}));

setDonationLevels(options);
setAttributes({
levels: newLevels,
defaultLevel: Number(checkedLevel[0].value),
descriptions: newDescriptions,
});
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ const {
setPrice,
priceOption,
levels,
descriptions,
defaultLevel,
} = getDefaultBlockAttributes('givewp/donation-amount');

const settings: FieldBlock['settings'] = {
Expand All @@ -40,14 +38,6 @@ const settings: FieldBlock['settings'] = {
type: 'array',
default: levels,
},
descriptions: {
type: 'array',
default: descriptions,
},
defaultLevel: {
type: 'number',
default: defaultLevel,
},
priceOption: {
type: 'string',
default: priceOption,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import {OptionProps} from '@givewp/form-builder-library/build/OptionsPanel/types';
import type {subscriptionPeriod} from '@givewp/forms/registrars/templates/groups/DonationAmount/subscriptionPeriod';

export interface DonationAmountAttributes {
label: string;
levels: number[];
levels: OptionProps[];
descriptions: string[];
descriptionsEnabled: boolean;
defaultLevel: number;
Expand Down

0 comments on commit 8065dde

Please sign in to comment.