Skip to content

Commit

Permalink
bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
rideam committed Mar 10, 2023
1 parent 0c912ee commit b4d2449
Show file tree
Hide file tree
Showing 11 changed files with 155 additions and 39 deletions.
Binary file added docs/img/admin/admin-login.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/img/admin/policy-view.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 10 additions & 2 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,8 @@ def as_dict(self):
result[c.name] = getattr(self, c.name).strftime('%d-%m-%Y')
return result

def is_valid(self, date):
return self.start_date <= date <= self.end_date
def is_valid(self, date, farmer_id):
return self.start_date <= date <= self.end_date and self.is_premium_paid(farmer_id)

def my_policy(self, address):
result = False
Expand All @@ -182,6 +182,13 @@ def is_premium_paid(self, farmer_id):
return is_paid.blockchain_url
return ''

def policy_onchain(self, farmer_id):
policy_farmer_rec = PoliciesFarmers.query.filter_by(farmer_id=farmer_id,
policy_id=self.id).first()
if policy_farmer_rec.blockchain_url:
return policy_farmer_rec.blockchain_url
return ''

def __str__(self):
return self.name

Expand All @@ -203,6 +210,7 @@ class PoliciesFarmers(db.Model):
id = db.Column(db.Integer(), primary_key=True)
policy_id = db.Column(db.Integer(), db.ForeignKey('policy.id', ondelete='CASCADE'))
farmer_id = db.Column(db.String(255), db.ForeignKey('user.wallet_address', ondelete='CASCADE'))
blockchain_url = db.Column(db.String(255), nullable=True)

def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
Expand Down
8 changes: 8 additions & 0 deletions routes/appauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ def signup():
passphrase = create_account()
user = User(passphrase=passphrase)
login_user(user)
try:
user_in_db = User.query.filter_by(wallet_address=user.public_key).first()
if not user_in_db:
user.wallet_address = user.public_key
db.session.add(user)
db.session.commit()
except Exception as err:
print(err)
return render_template('mnemonic.html', passphrase=passphrase)


Expand Down
105 changes: 88 additions & 17 deletions routes/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
Event, \
Payout, \
Policy, \
PoliciesFarmers, \
db
from flask import request, jsonify
from flask_login import current_user
import datetime
import settings
from sqlalchemy import desc

from enum import Enum

Expand Down Expand Up @@ -62,7 +64,8 @@ def add_weather_data():
condition_pass = {
'temperature': False,
'humidity': False,
'soil_moisture': False
'soil_moisture': False,
'policy_is_valid': user_policy.is_valid(datetime.datetime.now(), data['user'])
}
# trigger_payout = False
for event in strike_events:
Expand Down Expand Up @@ -120,38 +123,77 @@ def add_weather_data():
@data_bp.route('/policies', methods=['POST', 'GET', 'DELETE'])
def policies():
if request.method == 'GET':
# Get all policy records
policy_recs = Policy.query.all()
return jsonify([{**policy.as_dict(), 'strike_event': policy.strike_event[0].desc,
'myPolicy': policy.my_policy(current_user.public_key)} for policy in policy_recs])

if request.method == 'POST':
# Join policy
id = request.json
policy_to_join = Policy.query.filter_by(id=int(id)).one()
user = User.query.filter_by(wallet_address=current_user.public_key).first()

if user not in policy_to_join.farmers:
policy_to_join.farmers.append(user)
db.session.commit()
policy_recs = Policy.query.all()
return jsonify([{**policy.as_dict(),
'strike_event': policy.strike_event[0].desc,
'myPolicy': policy.my_policy(current_user.public_key)} for policy in policy_recs]
)
policy_details_dict = {
'policy': policy_to_join.name,
'description': policy_to_join.description,
'period': f'{policy_to_join.start_date} to {policy_to_join.end_date}',
'coverage_amount': policy_to_join.coverage_amount,
'strike_event': policy_to_join.strike_event[0].desc,
'signature': f'Joined by {current_user.public_key}'
}

success, txid = current_user.send(0, policy_to_join.receiver, json.dumps(policy_details_dict))
if success:
policy_to_join.farmers.append(user)
db.session.commit()

try:
policy_farmer_rec = PoliciesFarmers.query.filter_by(policy_id=policy_to_join.id,
farmer_id=current_user.public_key).first()
policy_farmer_rec.blockchain_url = f'https://goalseeker.purestake.io/algorand/testnet/transaction/{txid}'
db.session.flush()
db.session.commit()
# print(f'https://goalseeker.purestake.io/algorand/testnet/transaction/{txid}')

except Exception as err:
print(err)
else:
print("trans failed")
return jsonify({
"msg": "Please fund your account with algos to join policy",
"class": "alert-danger"
})
# policy_recs = Policy.query.all()
# return jsonify([{**policy.as_dict(),
# 'strike_event': policy.strike_event[0].desc,
# 'myPolicy': policy.my_policy(current_user.public_key)} for policy in policy_recs]
# )
return jsonify({
"msg": "Enrolled in policy",
"class": "alert-success"
})

if request.method == 'DELETE':
# Remove enrollment from policy
id = request.json
policy_to_cancel = Policy.query.filter_by(id=int(id)).one()
user = User.query.filter_by(wallet_address=current_user.public_key).first()

if user in policy_to_cancel.farmers:
policy_to_cancel.farmers.remove(user)
db.session.commit()
policy_recs = Policy.query.all()
return jsonify([{**policy.as_dict(),
'strike_event': policy.strike_event[0].desc,
'myPolicy': policy.my_policy(current_user.public_key)}
for policy in policy_recs]
)
# policy_recs = Policy.query.all()
# return jsonify([{**policy.as_dict(),
# 'strike_event': policy.strike_event[0].desc,
# 'myPolicy': policy.my_policy(current_user.public_key)}
# for policy in policy_recs]
# )
return jsonify({
"msg": "Cancelled policy",
"class": "alert-danger"
})


@data_bp.route('/mypolicies', methods=['POST', 'GET', 'DELETE'])
Expand All @@ -164,8 +206,9 @@ def mypolicies():
return jsonify([{**policy.as_dict(),
'strike_event': policy.strike_event[0].desc,
'myPolicy': policy.my_policy(current_user.public_key),
'policy_blockchain_url': policy.policy_onchain(current_user.public_key),
'isPremiumPaid': policy.is_premium_paid(current_user.public_key) != '',
'blockchain_url': policy.is_premium_paid(current_user.public_key)}
'premium_blockchain_url': policy.is_premium_paid(current_user.public_key)}
for policy in user_policies]
)

Expand All @@ -176,7 +219,18 @@ def paypremium():
policy_id = request.json

policy = Policy.query.filter_by(id=int(policy_id)).first()
success, txid = current_user.send(policy.premium, policy.receiver, f'Paid by {current_user.public_key}')

policy_details_dict = {
'policy': policy.name,
'description': policy.description,
'period': f'{policy.start_date} to {policy.end_date}',
'coverage_amount': policy.coverage_amount,
'strike_event': policy.strike_event[0].desc,
'signature': f'Paid by {current_user.public_key}',
'month_year': f'{datetime.datetime.now().month}-{datetime.datetime.now().year}'
}

success, txid = current_user.send(policy.premium, policy.receiver, json.dumps(policy_details_dict))

if success:
pymt_dict = {
Expand All @@ -192,10 +246,27 @@ def paypremium():

return jsonify({
"msg": "Payment success",
"class": "alert-success"
"class": "alert-success",
"balance": current_user.get_balance()
})

return jsonify({
"msg": "Payment error",
"class": "alert-danger"
})


@data_bp.route('/farmdata', methods=['GET'])
def farmdata():
try:
farm = request.args['farm']
try:
limit = request.args['limit']
except Exception as err:
limit = 100
farm_weather_data = Weather.query.filter_by(farm=farm) \
.order_by(desc(Weather.created_at)).limit(limit) \
.all()
return jsonify([f.as_dict() for f in farm_weather_data])
except Exception as err:
return jsonify([])
22 changes: 16 additions & 6 deletions static/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -87,25 +87,35 @@ th, td {
}

.mt-1 {
margin-top: 0.5rem ;
margin-top: 0.5rem;
}

.mt-2 {
margin-top: 1rem ;
margin-top: 1rem;
}

.mt-3 {
margin-top: 1.5rem ;
margin-top: 1.5rem;
}

.mt-4 {
margin-top: 2.5rem ;
margin-top: 2.5rem;
}

.mt-5 {
margin-top: 3.5rem ;
margin-top: 3.5rem;
}

.text-sm{
.text-sm {
font-size: 11px !important;
}

.d-none {
display: none !important
}


.t-alert {
padding: 5px;
border-radius: 5px;
}
15 changes: 13 additions & 2 deletions templates/bootstrap3/enrol.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@
<div class="mt-4">
<h4>Policies</h4>
</div>

<div class="mt-3 pt-2 d-none" id="msg"></div>

<div class="d-none mt-3" id="loadersp">
<p class=" t-alert text-white alert-warning">Joining policy ....</p>
</div>

<div class="mt-4" id="tableData"></div>
{% endblock %}

Expand Down Expand Up @@ -112,7 +119,7 @@ <h4>Policies</h4>
contentType: 'application/json;charset=UTF-8',
type: 'DELETE',
success: function (response) {
$('#msg').removeClass('d-none').html(`<p class="p-3 ${response['class']} " >${response['msg']}</p>`)
$('#msg').removeClass('d-none').html(`<p class="p-3 t-alert ${response['class']} " >${response['msg']}</p>`)
setTimeout(() => {
$('#msg').addClass('d-none')
}, 3000)
Expand All @@ -127,6 +134,9 @@ <h4>Policies</h4>

$('#tableData').on('click', '.joinBtn', function () {

$('#loadersp').removeClass('d-none')


let id = $(this).val(); // capture value of clicked button (date)

$.ajax({
Expand All @@ -135,7 +145,8 @@ <h4>Policies</h4>
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function (response) {
$('#msg').removeClass('d-none').html(`<p class="p-3 ${response['class']} " >${response['msg']}</p>`)
$('#loadersp').addClass('d-none')
$('#msg').removeClass('d-none').html(`<p class="p-3 t-alert ${response['class']} " >${response['msg']}</p>`)
setTimeout(() => {
$('#msg').addClass('d-none')
}, 3000)
Expand Down
22 changes: 15 additions & 7 deletions templates/bootstrap3/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ <h4>Account Details</h4>
</tr>
<tr>
<td colspan="2">Balance</td>
<td><b>{{ balance }}</b> <span class="badge text-white bg-primary text-sm">Algos</span></td>
<td><b id="amount">{{ balance }}</b> <span class="badge text-white bg-primary text-sm">Algos</span></td>
</tr>
</tbody>
</table>
Expand All @@ -20,11 +20,12 @@ <h4>Account Details</h4>
<div class="mt-3 pt-2 d-none" id="msg"></div>

<div class="d-none" id="loadersp">
<div class="d-flex justify-content-center " >
<p class=" t-alert text-white alert-warning">Processing payment ....</p>
{#<div class="d-flex justify-content-center " >
<div class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
</div>#}
</div>

<div class="mt-5">
Expand Down Expand Up @@ -102,9 +103,15 @@ <h4>My Policies</h4>
</button>`;
}

if (tableData[i].blockchain_url !== "") {
if (tableData[i].premium_blockchain_url !== "") {
tableRows += `
<a href="${tableData[i].blockchain_url}" class="btn btn-success btn-sm ml-2 mt-1" target="_blank"> Premium Paid on chain</a>
<a href="${tableData[i].premium_blockchain_url}" class="btn btn-success btn-sm ml-2 mt-1" target="_blank"> Premium Paid on chain</a>
`
}

if (tableData[i].policy_blockchain_url !== "") {
tableRows += `
<a href="${tableData[i].policy_blockchain_url}" class="btn btn-success btn-sm ml-2 mt-1" target="_blank"> Policy on chain</a>
`
}

Expand Down Expand Up @@ -137,7 +144,7 @@ <h4>My Policies</h4>
contentType: 'application/json;charset=UTF-8',
type: 'DELETE',
success: function (response) {
$('#msg').removeClass('d-none').html(`<p class="p-3 ${response['class']} " >${response['msg']}</p>`)
$('#msg').removeClass('d-none').html(`<p class="p-3 text-white t-alert ${response['class']} " >${response['msg']}</p>`)
setTimeout(() => {
$('#msg').addClass('d-none')
}, 3000)
Expand All @@ -162,10 +169,11 @@ <h4>My Policies</h4>
type: 'POST',
success: function (response) {
$('#loadersp').addClass('d-none')
$('#msg').removeClass('d-none').html(`<p class="p-3 text-white ${response['class']} " >${response['msg']}</p>`)
$('#msg').removeClass('d-none').html(`<p class="p-3 text-white t-alert ${response['class']} " >${response['msg']}</p>`)
setTimeout(() => {
$('#msg').addClass('d-none')
}, 3000)
$('#amount').text(response['balance'])
},
error: function (error) {
console.log(error);
Expand Down
4 changes: 2 additions & 2 deletions templates/bootstrap3/nav.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@
Payouts
</a>
</li>
<li {% if request.path==url_for('main_bp.farmdata') %}
<li {% if request.path==url_for('main_bp.sensordata') %}
class="nav-item active"{% else %} class="nav-item"{% endif %}>
<a class="nav-link" href="{{ url_for('main_bp.farmdata') }}">
<a class="nav-link" href="{{ url_for('main_bp.sensordata') }}">
Sensor Data
</a>
</li>
Expand Down
File renamed without changes.
Loading

0 comments on commit b4d2449

Please sign in to comment.