Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Time Based Form Goals #7384

Merged
merged 14 commits into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion includes/shortcodes.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ function give_form_shortcode( $atts ) {
*
* Show the Give donation form goals.
*
* @unreleased add start_date and end_date attributes
* @since 3.7.0 Sanitize attributes
* @since 3.4.0 Add additional validations to check if the form is valid and has the 'published' status.
* @since 1.0
Expand All @@ -228,7 +229,9 @@ function give_goal_shortcode( $atts ) {
'id' => '',
'show_text' => true,
'show_bar' => true,
'color' => '',
'color' => '#66BB6A',
'start_date' => '',
'end_date' => '',
],
$atts,
'give_goal'
Expand Down
42 changes: 34 additions & 8 deletions src/DonationForms/DataTransferObjects/DonationFormGoalData.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@

namespace Give\DonationForms\DataTransferObjects;

use Give\DonationForms\DonationQuery;
use Give\DonationForms\Models\DonationForm;
use Give\DonationForms\Properties\FormSettings;
use Give\DonationForms\Repositories\DonationFormRepository;
use Give\DonationForms\SubscriptionQuery;
use Give\DonationForms\ValueObjects\GoalProgressType;
use Give\DonationForms\ValueObjects\GoalType;
use Give\Framework\Support\Contracts\Arrayable;

Expand Down Expand Up @@ -32,6 +36,18 @@ class DonationFormGoalData implements Arrayable
* @var int
*/
public $targetAmount;
/**
* @var GoalProgressType
*/
public $goalProgressType;
/**
* @var string|null
*/
public $goalStartDate;
/**
* @var string|null
*/
public $goalEndDate;

/**
* @since 3.0.0
Expand All @@ -43,6 +59,9 @@ public function __construct(int $formId, FormSettings $formSettings)
$this->isEnabled = $formSettings->enableDonationGoal ?? false;
$this->goalType = $formSettings->goalType ?? GoalType::AMOUNT();
$this->targetAmount = $this->formSettings->goalAmount ?? 0;
$this->goalProgressType = $this->formSettings->goalProgressType ?? GoalProgressType::ALL_TIME();
$this->goalStartDate = $this->formSettings->goalStartDate ?? null;
$this->goalEndDate = $this->formSettings->goalEndDate ?? null;
}

/**
Expand All @@ -52,23 +71,30 @@ public function __construct(int $formId, FormSettings $formSettings)
*/
public function getCurrentAmount()
{
/** @var DonationFormRepository $donationFormRepository */
$donationFormRepository = give(DonationFormRepository::class);
$query = $this->goalType->isOneOf(GoalType::SUBSCRIPTIONS(), GoalType::AMOUNT_FROM_SUBSCRIPTIONS(), GoalType::DONORS_FROM_SUBSCRIPTIONS())
? new SubscriptionQuery()
: new DonationQuery();

$query->form($this->formId);

if($this->goalProgressType->isCustom()) {
$query->between($this->goalStartDate, $this->goalEndDate);
jonwaldstein marked this conversation as resolved.
Show resolved Hide resolved
}

switch ($this->goalType):
case GoalType::DONORS():
return $donationFormRepository->getTotalNumberOfDonors($this->formId);
return $query->countDonors();
case GoalType::DONATIONS():
return $donationFormRepository->getTotalNumberOfDonations($this->formId);
return $query->count();
case GoalType::SUBSCRIPTIONS():
return $donationFormRepository->getTotalNumberOfSubscriptions($this->formId);
return $query->count();
case GoalType::AMOUNT_FROM_SUBSCRIPTIONS():
return $donationFormRepository->getTotalInitialAmountFromSubscriptions($this->formId);
return $query->sumInitialAmount();
case GoalType::DONORS_FROM_SUBSCRIPTIONS():
return $donationFormRepository->getTotalNumberOfDonorsFromSubscriptions($this->formId);
return $query->countDonors();
case GoalType::AMOUNT():
default:
return $donationFormRepository->getTotalRevenue($this->formId);
return $query->sumIntendedAmount();
endswitch;
}

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

namespace Give\DonationForms;

use Give\Donations\ValueObjects\DonationMetaKeys;
use Give\Framework\QueryBuilder\JoinQueryBuilder;
use Give\Framework\QueryBuilder\QueryBuilder;

/**
* An opinionated Query Builder for GiveWP donations and meta fields.
*
* @unreleased
*
* Example usage:
* (new DonationQuery)
* ->form(1816)
* ->between('2024-02-00', '2024-02-23')
* ->sumIntendedAmount();
*/
class DonationQuery extends QueryBuilder
{
/**
* @unreleased
*/
public function __construct()
{
$this->from('posts', 'donation');
}

/**
* An opinionated join method for the donation meta table.
* @unreleased
*/
public function joinMeta($key, $alias)
{
$this->join(function (JoinQueryBuilder $builder) use ($key, $alias) {
$builder
->leftJoin('give_donationmeta', $alias)
->on('donation.ID', $alias . '.donation_id')
->andOn($alias . '.meta_key', $key, true);
});
return $this;
}

/**
* An opinionated where method for the donation form ID meta field.
* @unreleased
*/
public function form($formId)
{
$this->joinMeta('_give_payment_form_id', 'formId');
$this->where('formId.meta_value', $formId);
return $this;
}


/**
* An opinionated where method for the multiple donation form IDs meta field.
* @unreleased
*/
public function forms(array $formIds)
{
$this->joinMeta('_give_payment_form_id', 'formId');
$this->whereIn('formId.meta_value', $formIds);
return $this;
}

/**
* An opinionated whereBetween method for the completed date meta field.
* @unreleased
*/
public function between($startDate, $endDate)
{
$this->joinMeta('_give_completed_date', 'completed');
$this->whereBetween(
'completed.meta_value',
date('Y-m-d H:i:s', strtotime($startDate)),
date('Y-m-d H:i:s', strtotime($endDate))
);
return $this;
}

/**
* Returns a calculated sum of the intended amounts (without recovered fees) for the donations.
* @unreleased
* @return int|float
*/
public function sumIntendedAmount()
{
$this->joinMeta('_give_payment_total', 'amount');
$this->joinMeta('_give_fee_donation_amount', 'intendedAmount');
return $this->sum(
'COALESCE(intendedAmount.meta_value, amount.meta_value)'
);
}

public function countDonors()
{
$this->joinMeta(DonationMetaKeys::DONOR_ID, 'donorId');
return $this->count('DISTINCT donorId.meta_value');
}
}
19 changes: 19 additions & 0 deletions src/DonationForms/Properties/FormSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
use Give\DonationForms\ValueObjects\DesignSettingsSectionStyle;
use Give\DonationForms\ValueObjects\DesignSettingsTextFieldStyle;
use Give\DonationForms\ValueObjects\DonationFormStatus;
use Give\DonationForms\ValueObjects\GoalProgressType;
use Give\DonationForms\ValueObjects\GoalType;
use Give\Framework\Support\Contracts\Arrayable;
use Give\Framework\Support\Contracts\Jsonable;

/**
* @unreleased Add goalProgressType
* @since 3.2.0 Remove addSlashesRecursive method
* @since 3.0.0
*/
Expand Down Expand Up @@ -45,6 +47,18 @@ class FormSettings implements Arrayable, Jsonable
* @var GoalType
*/
public $goalType;
/**
* @var GoalProgressType
*/
public $goalProgressType;
/**
* @var string
*/
public $goalStartDate;
/**
* @var string
*/
public $goalEndDate;
/**
* @var string
*/
Expand Down Expand Up @@ -275,6 +289,11 @@ public static function fromArray(array $array): self
$self->goalType = ! empty($array['goalType']) && GoalType::isValid($array['goalType']) ? new GoalType(
$array['goalType']
) : GoalType::AMOUNT();
$self->goalProgressType = ! empty($array['goalProgressType']) && GoalProgressType::isValid($array['goalProgressType'])
? new GoalProgressType($array['goalProgressType'])
: GoalProgressType::ALL_TIME();
$self->goalStartDate = $array['goalStartDate'] ?? '';
$self->goalEndDate = $array['goalEndDate'] ?? '';
$self->designId = $array['designId'] ?? null;
$self->primaryColor = $array['primaryColor'] ?? '#69b86b';
$self->secondaryColor = $array['secondaryColor'] ?? '#f49420';
Expand Down
22 changes: 7 additions & 15 deletions src/DonationForms/Repositories/DonationFormRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Give\DonationForms\Actions\ConvertDonationFormBlocksToFieldsApi;
use Give\DonationForms\DonationQuery;
use Give\DonationForms\Models\DonationForm;
use Give\DonationForms\ValueObjects\DonationFormMetaKeys;
use Give\Donations\ValueObjects\DonationMetaKeys;
Expand Down Expand Up @@ -393,10 +394,8 @@ public function getTotalNumberOfDonorsFromSubscriptions(int $formId): int
*/
public function getTotalNumberOfDonations(int $formId): int
{
return DB::table('posts')
->leftJoin('give_donationmeta', 'ID', 'donation_id')
->where('meta_key', DonationMetaKeys::FORM_ID)
->where('meta_value', $formId)
return (new DonationQuery)
->form($formId)
->count();
}

Expand All @@ -411,21 +410,14 @@ public function getTotalNumberOfSubscriptions(int $formId): int
}

/**
* @unreleased Update query to use intended amounts (without recovered fees).
* @since 3.0.0
*/
public function getTotalRevenue(int $formId): int
{
$query = DB::table('give_formmeta')
->select('meta_value as totalRevenue')
->where('form_id', $formId)
->where('meta_key', '_give_form_earnings')
->get();

if (!$query) {
return 0;
}

return (int)$query->totalRevenue;
return (int) (new DonationQuery)
->form($formId)
->sumIntendedAmount();
}

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

namespace Give\DonationForms;

use Give\Framework\QueryBuilder\QueryBuilder;

/**
* @unreleased
*/
class SubscriptionQuery extends QueryBuilder
{
/**
* @unreleased
*/
public function __construct()
{
$this->from('give_subscriptions');
}

/**
* @unreleased
*/
public function form($formId)
{
$this->where('product_id', $formId);
return $this;
}


/**
* @unreleased
*/
public function forms(array $formIds)
{
$this->whereIn('product_id', $formIds);
return $this;
}

/**
* @unreleased
*/
public function between($startDate, $endDate)
{
$this->whereBetween(
'created',
date('Y-m-d H:i:s', strtotime($startDate)),
date('Y-m-d H:i:s', strtotime($endDate))
);
return $this;
}

/**
* @unreleased
*/
public function sumInitialAmount()
{
return $this->sum('initial_amount');
}

/**
* @unreleased
*/
public function countDonors()
{
return $this->count('DISTINCT customer_id');
}
}
19 changes: 19 additions & 0 deletions src/DonationForms/ValueObjects/GoalProgressType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Give\DonationForms\ValueObjects;

use Give\Framework\Support\ValueObjects\Enum;

/**
* @unreleased
*
* @method static GoalProgressType ALL_TIME()
* @method static GoalProgressType CUSTOM()
* @method bool isAllTime()
* @method bool isCustom()
*/
class GoalProgressType extends Enum
{
const ALL_TIME = 'all_time';
const CUSTOM = 'custom';
}
Loading
Loading