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: Add editable Campaign dropdown to Donation Details screen #7859

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
17 changes: 17 additions & 0 deletions assets/src/css/admin/payment-history.scss
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,23 @@ tr.status-refunded td {
}
}

#give_payment_form_select {
+ #give_payment_form_select_chosen {
a.chosen-single {
transition: background-color 1s ease-out;
}
}

&.flash {
+ #give_payment_form_select_chosen {
a.chosen-single {
background-color: yellow !important;
transition: background-color 0.2s ease-in;
}
}
}
}

//Payment View Metabox
#give-order-update {
.give-donation-status {
Expand Down
57 changes: 57 additions & 0 deletions assets/src/js/admin/admin-scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,63 @@ const gravatar = require('gravatar');
$('#post').on('click', '.give-thickbox', function () {
$('.give-select-chosen', '#choose-give-form').css('width', '100%');
});

const $campaignSelect = $('#give_payment_campaign_select');
const $formSelect = $('#give_payment_form_select');

if ($campaignSelect.length && $formSelect.length) {
(function () {
let initialized = false;
const campaignsData = $campaignSelect.data('campaigns');
const formsData = Array.from($formSelect.find('option'))
.filter((option) => option.value > 0)
.map((option) => ({
id: parseInt(option.value),
title: option.text.trim(),
}));

const flashElement = (element) => {
element.classList.add('flash');

setTimeout(() => {
element.classList.remove('flash');
}, 200);
};

$campaignSelect
.on('change', function () {
const selectedCampaignId = $(this).val();
const campaign = campaignsData.find(
(campaign) => Number(campaign.id) === Number(selectedCampaignId)
);

if (campaign) {
const formIds = campaign.form_ids.split(',').map(Number);

if (formIds.length > 0) {
$formSelect.empty();

const filteredForms = formsData.filter((form) => formIds.includes(form.id));
filteredForms.forEach((form) => {
$formSelect.append(new Option(form.title, form.id));
});

if (initialized) {
flashElement($formSelect[0]);
}
}

if (campaign.default_form) {
$formSelect.val(campaign.default_form);
}
}

$formSelect.trigger('chosen:updated');
initialized = true;
})
.change();
})();
}
};

/**
Expand Down
111 changes: 107 additions & 4 deletions includes/admin/class-give-html-elements.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
*/

// Exit if accessed directly.
use Give\Framework\Database\DB;

if ( ! defined( 'ABSPATH' ) ) {
exit;
}
Expand Down Expand Up @@ -226,10 +228,111 @@ public function forms_dropdown( $args = array() ) {
return $output;
}

/**
* Donors Dropdown
*
* Renders an HTML Dropdown of all donors.
/**
* @unreleased
*/
public function campaigns_dropdown($args = [])
{
$defaults = [
'name' => 'campaigns',
'id' => 'campaigns',
'class' => '',
'multiple' => false,
'selected' => 0,
'chosen' => false,
'number' => 30,
'placeholder' => esc_attr__('All Campaigns', 'give'),
'data' => [
'search-type' => 'campaign',
],
'query_args' => [],
];

$args = wp_parse_args($args, $defaults);

$campaigns_args = wp_parse_args(
$args['query_args'],
[
'orderby' => 'id',
'order' => 'DESC',
'per_page' => $args['number'],
]
);

/**
* Filter the campaigns dropdown.
*
* @unreleased
*
* @param array $campaigns_args Arguments for campaigns_dropdown query.
*
* @return array Arguments for campaigns_dropdown query.
*/
$campaigns_args = apply_filters('give_campaigns_dropdown_args', $campaigns_args);

$campaigns = DB::table('give_campaigns', 'campaigns')
->select(
['campaigns.id', 'id'],
['campaigns.form_id', 'defaultFormId'],
['campaign_title', 'title'],
['GROUP_CONCAT(campaign_forms.form_id)', 'form_ids']
)
->join(function ($builder) {
$builder
->leftJoin("give_campaign_forms", "campaign_forms")
->on("campaign_forms.campaign_id", "id");
})
->groupBy("campaigns.id")
->orderBy($campaigns_args['orderby'], $campaigns_args['order'])
->limit($campaigns_args['per_page'])
->getAll();

$options = [];

// Ensure the selected.
if (false !== $args['selected'] && $args['selected'] !== 0) {
$options[$args['selected']] = get_the_title($args['selected']);
}

$options[0] = esc_html__('No campaigns found.', 'give');
if ( ! empty($campaigns)) {
$options[0] = $args['placeholder'];
foreach ($campaigns as $campaign) {
$campaign_title = empty($campaign->title)
? sprintf(__('Untitled (#%s)', 'give'), $campaign->id)
: $campaign->title;

$options[absint($campaign->id)] = esc_html($campaign_title);
}
}

$output = $this->select(
[
'name' => $args['name'],
'selected' => $args['selected'],
'id' => $args['id'],
'class' => $args['class'],
'options' => $options,
'chosen' => $args['chosen'],
'multiple' => $args['multiple'],
'placeholder' => $args['placeholder'],
'show_option_all' => false,
'show_option_none' => false,
'data' => array_merge(
$args['data'],
['campaigns' => json_encode($campaigns)]
),
]
);

return $output;
}


/**
* Donors Dropdown
*
* Renders an HTML Dropdown of all donors.
*
* @since 1.0
* @access public
Expand Down
14 changes: 14 additions & 0 deletions includes/admin/payments/actions.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*/

// Exit if accessed directly.
use Give\Donations\Models\Donation;
use Give\Donations\ValueObjects\DonationMetaKeys;

if (!defined('ABSPATH')) {
Expand Down Expand Up @@ -312,6 +313,19 @@ function give_update_payment_details( $data ) {
$payment->update_payment_setup( $payment->ID );
}

// Update payment campaign.
$donation = Donation::find($payment->ID);

if ($donation) {
$new_campaign_id = absint($data['give-payment-campaign-select']);
$current_campaign_id = absint($donation->campaignId);

if ($new_campaign_id && $new_campaign_id !== $current_campaign_id) {
$donation->campaignId = $new_campaign_id;
$donation->save();
}
}

$comment_id = isset( $data['give_comment_id'] ) ? absint( $data['give_comment_id'] ) : 0;
$has_anonymous_setting_field = give_is_anonymous_donation_field_enabled( $payment->form_id );

Expand Down
18 changes: 17 additions & 1 deletion includes/admin/payments/view-payment-details.php
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,23 @@
);
?>
</p>
</div>
<p>
<strong><?php
esc_html_e('Campaign:', 'give'); ?></strong><br>
<?php
$donation = Donation::find($payment->ID);
echo Give()->html->campaigns_dropdown(
[
'selected' => $donation->campaignId,
'name' => 'give-payment-campaign-select',
'id' => 'give-payment-campaign-select',
'chosen' => true,
'placeholder' => '',
]
);
?>
</p>
</div>
<div class="column">
<p>
<strong><?php _e( 'Donation Date:', 'give' ); ?></strong><br>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
use Give\Revenue\Repositories\Revenue;

/**
* @unreleased Updated class to support update other properties
* @since 2.22.1
*/
class UpdateRevenueWhenDonationAmountUpdated
class UpdateRevenueWhenDonationUpdated
{
/**
* @unreleased Added support to update revenue campaignId
* @since 3.3.0 updated to accept Donation model
* @since 2.22.1
*/
Expand All @@ -19,5 +21,9 @@ public function __invoke(Donation $donation)
if ($donation->isDirty('amount')) {
give(Revenue::class)->updateRevenueAmount($donation);
}

if ($donation->isDirty('campaignId')) {
give(Revenue::class)->updateRevenueCampaignId($donation);
}
}
}
18 changes: 18 additions & 0 deletions src/Revenue/Repositories/Revenue.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,24 @@ public function updateRevenueAmount(Donation $donation)
);
}

/**
* @unreleased
*
* @return false|int
*/
public function updateRevenueCampaignId(Donation $donation)
{
global $wpdb;

return DB::update(
$wpdb->give_revenue,
['campaign_id' => $donation->campaignId],
['donation_id' => $donation->id],
['%d'],
['%d']
);
}

/**
* Validate new revenue data.
*
Expand Down
6 changes: 2 additions & 4 deletions src/Revenue/RevenueServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@

namespace Give\Revenue;

use Give\Donations\Models\Donation;
use Give\Framework\Migrations\MigrationsRegister;
use Give\Helpers\Hooks;
use Give\Revenue\Listeners\DeleteRevenueWhenDonationDeleted;
use Give\Revenue\Listeners\UpdateRevenueWhenDonationAmountUpdated;
use Give\Revenue\Listeners\UpdateRevenueWhenDonationUpdated;
use Give\Revenue\Migrations\AddPastDonationsToRevenueTable;
use Give\Revenue\Migrations\CreateRevenueTable;
use Give\Revenue\Migrations\RemoveRevenueForeignKeys;
use Give\Revenue\Repositories\Revenue;
use Give\ServiceProviders\ServiceProvider;

class RevenueServiceProvider implements ServiceProvider
Expand Down Expand Up @@ -40,7 +38,7 @@ public function boot()
Hooks::addAction('delete_post', DeleteRevenueWhenDonationDeleted::class, '__invoke', 10, 1);
Hooks::addAction('give_insert_payment', DonationHandler::class, 'handle', 999, 1);
Hooks::addAction('give_register_updates', AddPastDonationsToRevenueTable::class, 'register', 10, 1);
Hooks::addAction('givewp_donation_updated', UpdateRevenueWhenDonationAmountUpdated::class);
Hooks::addAction('givewp_donation_updated', UpdateRevenueWhenDonationUpdated::class);
Hooks::addAction('give_updated_edited_donation',LegacyListeners\UpdateRevenueWhenDonationAmountUpdated::class);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use Give\Donations\ValueObjects\DonationStatus;
use Give\Framework\Database\DB;
use Give\Framework\Support\ValueObjects\Money;
use Give\Revenue\Listeners\UpdateRevenueWhenDonationAmountUpdated;
use Give\Revenue\Listeners\UpdateRevenueWhenDonationUpdated;
use Give\Tests\TestCase;
use Give\Tests\TestTraits\RefreshDatabase;

Expand All @@ -26,18 +26,24 @@ public function testRevenueIsUpdatedWhenDonationIsUpdated(): void
$donation = Donation::factory()->create([
'status' => DonationStatus::COMPLETE(),
'amount' => Money::fromDecimal(250.00, 'USD'),
'campaignId' => 1,
]);

$donation->amount = Money::fromDecimal(25.00, 'USD');
$donation->campaignId = 2;
$donation->save();

$listener = new UpdateRevenueWhenDonationAmountUpdated();
$listener = new UpdateRevenueWhenDonationUpdated();
$listener($donation);

$this->assertEquals(
Money::fromDecimal(25.00, 'USD')->formatToMinorAmount(),
$this->getRevenueAmountForDonation($donation)
);
$this->assertEquals(
2,
$this->getRevenueCampaignIdForDonation($donation)
);
}

/**
Expand All @@ -50,5 +56,13 @@ private function getRevenueAmountForDonation(Donation $donation)

return $revenue->amount;
}

private function getRevenueCampaignIdForDonation(Donation $donation)
{
global $wpdb;
$revenue = DB::get_row("SELECT * FROM {$wpdb->give_revenue} WHERE donation_id = {$donation->id}");

return $revenue->campaign_id;
}
}