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

feat: redo new-match #7823

Merged
merged 4 commits into from
Nov 11, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
217 changes: 217 additions & 0 deletions app/assets/v2/js/grants/new_match.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
Vue.component('v-select', VueSelect.VueSelect);


Vue.mixin({
methods: {
clearForm: function() {
let vm = this;

vm.form = {
why: '',
amount: 0,
stage: '',
grant_types: [],
grant_categories: [],
grant_collections: [],
anonymous: false,
comment: '',
tx_id: ''
};

},
transfer_web3: function(params) {
let vm = this;

const amount = params.amount;
const decimals = 18;
const to = '0xde21F729137C5Af1b01d73aF1dC21eFfa2B8a0d6';
// const token_addr = "0x6B175474E89094C44Da98b954EedeAC495271d0F";
const token_addr = (document.web3network == 'mainnet') ?
'0x6B175474E89094C44Da98b954EedeAC495271d0F' :
'0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa'

;
const amountInWei = amount * 1.0 * Math.pow(10, decimals);
const amountAsString = new web3.utils.BN(BigInt(amountInWei)).toString();

const token_contract = new web3.eth.Contract(token_abi, token_addr);

return token_contract.methods.transfer(to, web3.utils.toHex(amountAsString))
.send({from: selectedAccount},
(error, tx_id) => {
if (error) {
_alert({ message: gettext('Unable to pay the match pledge amount. Please try again.') }, 'error');
console.error(`error: unable to pay pledge due to : ${error}`);
return;
}
params['tx_id'] = tx_id;
console.log(params);
vm.submitted = true;
vm.createMatchingPledge(params);

}
);
},
checkForm: function(e) {
let vm = this;

vm.submitted = true;
vm.errors = {};
if (!vm.form.why.length) {
vm.$set(vm.errors, 'why', 'Please select why you want to create a match pledge');
}
if (!vm.form.amount) {
vm.$set(vm.errors, 'amount', 'Please enter amount you would want to pledge');
}
if (!vm.form.stage) {
vm.$set(vm.errors, 'stage', 'Please select the stage of funding');
}

if (!vm.grants_to_fund) {
vm.$set(vm.errors, 'grants_to_fund', 'Please select one of the options');
} else if (vm.grants_to_fund == 'types' && !vm.form.grant_types.length > 0) {
vm.$set(vm.errors, 'grant_types', 'Please select the grant types');
} else if (vm.grants_to_fund == 'collections' && !vm.form.grant_collections.length > 0) {
vm.$set(vm.errors, 'grant_collections', 'Please select the collections');
}


if (Object.keys(vm.errors).length) {
return false; // there are errors the user must correct
}
vm.submitted = false;
return true; // no errors, continue to create match pledge
},
submitForm: async function(event) {
thelostone-mc marked this conversation as resolved.
Show resolved Hide resolved
event.preventDefault();
let vm = this;
let form = vm.form;

// Exit if form is not valid
if (!vm.checkForm(event))
return;

if (vm.grants_to_fund == 'types') {
vm.form.grant_collections = [];
} else if (vm.grants_to_fund == 'collections') {
vm.form.grant_types = [];
vm.form.grant_categories = [];
}

const params = {
'why': form.why,
'amount': form.amount,
'stage': form.stage,
'grant_types[]': form.grant_types.join(),
'grant_categories[]': form.grant_categories.join(),
'grant_collections[]': form.grant_collections.join(),
'anonymous': form.anonymous,
'comment': form.comment
};

if (form.stage == 'ready') {
if (!provider) {
onConnect();
return false;
}

vm.transfer_web3(params);
} else {
vm.submitted = true;
vm.createMatchingPledge(params);
}

},
async createMatchingPledge(data) {
let vm = this;

if (typeof ga !== 'undefined') {
ga('send', 'event', 'Create Match Pledge', 'click', 'Grant Match Pledge Creator');
}


try {
const url = '/grants/v1/api/matching-pledge/create';

const headers = {
'X-CSRFToken': $("input[name='csrfmiddlewaretoken']").val()
};

response = await fetchData(url, 'POST', data, headers);

if (response.status == 200) {
_alert('Match Pledge Request Created.');
vm.clearForm();
} else {
vm.submitted = false;
_alert('Unable to create matching pledge. Please try again', 'error');
console.error(`error: match pledge creation failed with status: ${response.status} and message: ${response.message}`);
}

} catch (err) {
vm.submitted = false;
_alert('Unable to create matching pledge. Please try again', 'error');
console.error(`error: match pledge creation failed with msg ${err}`);
}
}
},
watch: {
deep: true,
form: {
deep: true,
handler(newVal, oldVal) {
if (this.dirty && this.submitted) {
this.checkForm();
}
this.dirty = true;
}
}
}
});

if (document.getElementById('gc-new-match')) {

const why_options = [
'to see an ecosystem grow',
'to give back',
'to support a marketing campaign',
'all of the above',
'other'
];
const stage_options = [
{'key': 'ready', 'val': 'I am ready to transfer DAI'},
{'key': 'details', 'val': 'Send me more details'}
];

appFormBounty = new Vue({
delimiters: [ '[[', ']]' ],
el: '#gc-new-match',
components: {
'vue-select': 'vue-select'
},
data() {
return {
grants_to_fund: 'types',
grant_types: document.grant_types,
grant_collections: document.grant_collections,
grant_categories: document.grant_categories,
why_options: why_options,
stage_options: stage_options,
network: 'mainnet',
submitted: false,
errors: {},
form: {
why: '',
amount: 0,
stage: '',
grant_types: [],
grant_categories: [],
grant_collections: [],
anonymous: false,
comment: '',
tx_id: ''
}
};
}
});
}
4 changes: 0 additions & 4 deletions app/assets/v2/js/grants/newmatch.js

This file was deleted.

42 changes: 19 additions & 23 deletions app/grants/clr.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

import numpy as np
import pytz
from grants.models import Contribution, Grant, PhantomFunding
from grants.models import Contribution, Grant, GrantCollection
from marketing.models import Stat
from perftools.models import JSONStore

Expand Down Expand Up @@ -173,10 +173,10 @@ def get_totals_by_pair(contrib_dict):
pair_totals
{user_id (str): {user_id (str): pair_total (float)}}
sms_verified_list
[user_id (str)]
[user_id (str)]
bright_verified_list
[user_id (str)]
v_threshold
v_threshold
float
uv_threshold
float
Expand All @@ -192,7 +192,7 @@ def get_totals_by_pair(contrib_dict):
def calculate_clr(aggregated_contributions, pair_totals, sms_verified_list, bright_verified_list, v_threshold, uv_threshold, total_pot):
bigtot = 0
totals = []

for proj, contribz in aggregated_contributions.items():
tot = 0
_num = 0
Expand Down Expand Up @@ -327,7 +327,6 @@ def calculate_clr_for_donation(grant, amount, grant_contributions_curr, total_po
Returns:
contributions : contributions data object
grants : list of grants based on clr_type
phantom_funding_profiles : phantom funding data object
'''
def fetch_data(clr_round, network='mainnet'):
Expand All @@ -336,17 +335,23 @@ def fetch_data(clr_round, network='mainnet'):
clr_end_date = clr_round.end_date
grant_filters = clr_round.grant_filters
subscription_filters = clr_round.subscription_filters
collection_filters = clr_round.collection_filters

contributions = Contribution.objects.prefetch_related('subscription').filter(match=True, created_on__gte=clr_start_date, created_on__lte=clr_end_date, success=True).nocache()
if subscription_filters:
contributions = contributions.filter(**subscription_filters)

grants = Grant.objects.filter(network=network, hidden=False, active=True, is_clr_eligible=True, link_to_new_grant=None)
grants = grants.filter(**grant_filters)

phantom_funding_profiles = PhantomFunding.objects.filter(created_on__gte=clr_start_date, created_on__lte=clr_end_date)
if grant_filters:
# Grant Filters (grant_type, category)
grants = grants.filter(**grant_filters)
elif collection_filters:
# Collection Filters
grant_ids = GrantCollection.objects.filter(**collection_filters).values_list('grants', flat=True)
grants = grants.filter(pk__in=grant_ids)

return grants, contributions, phantom_funding_profiles
return grants, contributions



Expand All @@ -356,7 +361,6 @@ def fetch_data(clr_round, network='mainnet'):
Args:
grants : grants list
contributions : contributions list for thoe grants
phantom_funding_profiles: phantom funding for those grants
clr_round : GrantCLR
Returns:
Expand All @@ -366,7 +370,7 @@ def fetch_data(clr_round, network='mainnet'):
}
'''
def populate_data_for_clr(grants, contributions, phantom_funding_profiles, clr_round):
def populate_data_for_clr(grants, contributions, clr_round):

contrib_data_list = []

Expand All @@ -386,21 +390,16 @@ def populate_data_for_clr(grants, contributions, phantom_funding_profiles, clr_r
# contributions
contribs = copy.deepcopy(contributions).filter(subscription__grant_id=grant.id, subscription__is_postive_vote=True, created_on__gte=clr_start_date, created_on__lte=clr_end_date)

# phantom funding
grant_phantom_funding_contributions = phantom_funding_profiles.filter(grant_id=grant.id, created_on__gte=clr_start_date, created_on__lte=clr_end_date)

# SMS verified contributions
sms_verified_contribution_ids = [ele.pk for ele in contribs if ele.profile_for_clr.sms_verification]
sms_verified_phantom_funding_contribution_ids = [ele.profile_id for ele in grant_phantom_funding_contributions if ele.profile.sms_verification]
sms_verified_profile = list(set(sms_verified_contribution_ids + sms_verified_phantom_funding_contribution_ids))
sms_verified_profile = list(set(sms_verified_contribution_ids))

# BrightID verified contributions
brightid_verified_contribution_ids = [ele.pk for ele in contribs if ele.profile_for_clr.is_brightid_verified]
brightid_verified_phantom_funding_contribution_ids = [ele.profile_id for ele in grant_phantom_funding_contributions if ele.profile.is_brightid_verified]
brightid_verified_profile = list(set(brightid_verified_contribution_ids + brightid_verified_phantom_funding_contribution_ids))
brightid_verified_profile = list(set(brightid_verified_contribution_ids))

# combine
contributing_profile_ids = list(set([c.identity_identifier(mechanism) for c in contribs] + [p.profile_id for p in grant_phantom_funding_contributions]))
contributing_profile_ids = list(set([c.identity_identifier(mechanism) for c in contribs]))

summed_contributions = []

Expand All @@ -409,9 +408,6 @@ def populate_data_for_clr(grants, contributions, phantom_funding_profiles, clr_r
for profile_id in contributing_profile_ids:
profile_contributions = contribs.filter(profile_for_clr__id=profile_id)
sum_of_each_profiles_contributions = float(sum([c.subscription.amount_per_period_usdt * clr_round.contribution_multiplier for c in profile_contributions if c.subscription.amount_per_period_usdt]))
phantom_funding = grant_phantom_funding_contributions.filter(profile_id=profile_id)
if phantom_funding.exists():
sum_of_each_profiles_contributions = sum_of_each_profiles_contributions + phantom_funding.first().value

summed_contributions.append({
'id': str(profile_id),
Expand Down Expand Up @@ -439,13 +435,13 @@ def predict_clr(save_to_db=False, from_date=None, clr_round=None, network='mainn
v_threshold = float(clr_round.verified_threshold)
uv_threshold = float(clr_round.unverified_threshold)

grants, contributions, phantom_funding_profiles = fetch_data(clr_round, network)
grants, contributions = fetch_data(clr_round, network)

if contributions.count() == 0:
print(f'No Contributions for CLR {clr_round.round_num}. Exiting')
return

grant_contributions_curr = populate_data_for_clr(grants, contributions, phantom_funding_profiles, clr_round)
grant_contributions_curr = populate_data_for_clr(grants, contributions, clr_round)

if only_grant_pk:
grants = grants.filter(pk=only_grant_pk)
Expand Down
29 changes: 29 additions & 0 deletions app/grants/migrations/0092_auto_20201105_0831.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Generated by Django 2.2.4 on 2020-11-05 08:31

import django.contrib.postgres.fields.jsonb
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('grants', '0091_contribution_anonymous'),
]

operations = [
migrations.AddField(
model_name='grantclr',
name='collection_filters',
field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=dict, help_text='Grant Collections to be allowed in this CLR round', null=True),
),
migrations.AddField(
model_name='granttype',
name='is_active',
field=models.BooleanField(db_index=True, default=True, help_text='Is Grant Type currently active'),
),
migrations.AlterField(
model_name='matchpledge',
name='pledge_type',
field=models.CharField(blank=True, choices=[('tech', 'tech'), ('media', 'media'), ('health', 'health'), ('change', 'change')], help_text='CLR pledge type', max_length=15, null=True),
),
]
Loading