Skip to content

Commit

Permalink
order
Browse files Browse the repository at this point in the history
  • Loading branch information
TomConner committed Nov 19, 2023
1 parent bbd544f commit bcd3895
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 21 deletions.
83 changes: 76 additions & 7 deletions generator/layouts/shortcodes/register-form.html
Original file line number Diff line number Diff line change
Expand Up @@ -108,20 +108,27 @@
font-size:0.7em;
}

#lookup-code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New';
color: gray;
font-size: 80%;
margin: 0;
text-align: right;
}

</style>

<section id="register">
<form id="order-form">
<p></p>
<label class="tree" for="rcomment">Comment</label>
<input type="textarea" name="rcomment" placeholder="Anything we need to know"></input>

<label class="tree" for="rnumtrees">Number of Trees</label>
<input type="number" name="rnumtrees" id="rnumtrees" required></input>
<input type="number" name="rnumtrees" min=0 id="rnumtrees" required></input>

<p id="tree-messages">If you have an artificial tree, or no tree, but would like to support Pembroke Troop 105's Scouting program, indicate 0 trees and an additional donation amount.</p>
<label class="tree" for="rextra">Additional Donation Amount</label>
<input type="number" name="rextra" id="rextra" required></input>
<input type="number" min=0 name="rextra" id="rextra" required></input>
<p></p>
<label>Amount to pay: $ <span id="amount"></span></label>
<p></p>
Expand All @@ -142,6 +149,7 @@
<p><strong id="message2"></strong></p>
-->
<p id="lookup-code"></p>

<p id="messageVenmo" hidden="true">
<img src="qr-troop-venmo.png" style="max-width: 25%"></img>
Expand All @@ -157,7 +165,10 @@
}
</style>

<iframe src="/register"></iframe>

<section id="stripe">
<iframe src="/register"></iframe>
</section>

<script>

Expand Down Expand Up @@ -221,14 +232,31 @@
// }

function onChangeNumTrees() {
count = document.getElementById("rnumtrees").value;
extra = parseInt(document.getElementById("rextra").value);
value = document.getElementById("rnumtrees").value;
count = value == "" ? 0 : parseInt(value);
value = document.getElementById("rextra").value
extra = value == "" ? 0 : parseInt(value);
console.log(`${count} trees, ${extra} extra`);
amount = (count * 15) + extra;
document.getElementById("amount").innerText = amount;
lookup_code = localStorage.getItem("lookup");
fetch(`/api/v1/pickups/${lookup_code}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
numtrees: count,
extra: extra,
}),
})
.then((response) => response.json())
.then((pickup) => {
console.log(pickup);
});
}

window.addEventListener("load", (event) => {
function loadOrderForm() {
// document.getElementById("registerform").addEventListener("submit", formSubmit);
document.getElementById("rnumtrees").addEventListener("input", onChangeNumTrees);
document.getElementById("rextra").addEventListener("input", onChangeNumTrees);
Expand Down Expand Up @@ -256,5 +284,46 @@
// }
// });
// console.log('ready');
}

function lookup() {
session_start = localStorage.getItem("session_start");
if (session_start == null) {
session_start = Date.now();
sessionStorage.setItem("session_start", session_start);
}
lookup_code = localStorage.getItem("lookup")
if (lookup_code != null) {
console.log(`lookup code from localStorage is ${lookup_code}`);
fetch(`/api/v1/pickups/${lookup_code}`)
.then((response) => response.json())
.then((pickup) => {
console.log(pickup);
// document.getElementById("rnumtrees").value = pickup.numtrees;
// document.getElementById("rextra").value = pickup.extra;
// document.getElementById("rcomment").value = pickup.comment;
// onChangeNumTrees();
});
} else {
// post to /api/v1/pickups
fetch('/api/v1/pickups', {method: "POST"})
.then((response) => response.text())
.then((text) => {
lookup_code = text;
console.log(`new lookup code is ${lookup_code}`);
localStorage.setItem("lookup", lookup_code);
// document.getElementById("rnumtrees").value = pickup.numtrees;
// document.getElementById("rextra").value = pickup.extra;
// document.getElementById("rcomment").value = pickup.comment;
// onChangeNumTrees();
});
}
lookup_code = localStorage.getItem("lookup");
document.getElementById("lookup-code").innerText = `Lookup code: ${lookup_code}`;
loadOrderForm();
}

window.addEventListener("load", (event) => {
lookup();
});
</script>
32 changes: 29 additions & 3 deletions server/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from pathlib import Path
from datetime import datetime
import logging
import random

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

Expand All @@ -15,15 +17,20 @@ class Meta:

class Pickup(TreeModel):
lookup=CharField()

class Address(TreeModel):
lookup=ForeignKeyField(Pickup, backref='address')
name=CharField()
address1=CharField()
address2=CharField()
town=CharField()
state=CharField()

class Order(TreeModel):
pass

lookup=ForeignKeyField(Pickup, backref='Order')
comment=CharField()
trees=IntegerField()
extra=IntegerField()

def random_id():
alphabet='ABCDEFGHJKMNPQRTUVWXYZ'
Expand All @@ -42,7 +49,7 @@ def init_or_connect():
print('initializing database')
DB_FILE.parent.mkdir(parents=True, exist_ok=True)
database.connect()
database.create_tables([Pickup, Order])
database.create_tables([Pickup, Address, Order])
database.close()
else:
print('connecting to database')
Expand All @@ -57,3 +64,22 @@ def before_request():
def teardown_request():
if not database.is_closed():
database.close()

def get_pickups():
logger.debug('get_pickups')
return Pickup.select().dicts()

def get_pickup(lookup):
logger.debug(f'get_pickup {lookup}')
return Pickup.select().where(Pickup.lookup == lookup).dicts().get()

def create_pickup():
logger.debug('create_pickup')
lookup = new_lookup_id()
Pickup.create(lookup=lookup)
return lookup

def update_pickup(lookup):
logger.debug(f'update_pickup {lookup}')
Pickup.update(updated=datetime.now()).where(Pickup.lookup == lookup).execute()
return lookup
28 changes: 17 additions & 11 deletions server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from dotenv import load_dotenv, find_dotenv

import db
from db import Pickup, Order

load_dotenv(find_dotenv())

Expand All @@ -22,6 +21,12 @@

app = Flask(__name__)

def amount_from_request(data):
app.logger.info("amount_from_request")
app.logger.info(data)
amount = data["trees"] * 15 + data["extra"]
return amount*100

# This hook ensures that a connection is opened to handle any queries
# generated by the request.
@app.before_request
Expand All @@ -37,26 +42,27 @@ def db_teardown_request(exc):
@app.route('/api/v1/config', methods=['GET'])
def get_config():
app.logger.info('config')
db.Pickup(lookup="ABCD", name='tom', address1='123 main st', address2='apt 1', town='town', state='MA').save()
return jsonify({'publishableKey': os.getenv('STRIPE_PUBLISHABLE_KEY')})

@app.route('/api/v1/pickups', methods=['GET'])
def get_pickups():
app.logger.info(f"pickup")
pickups = Pickup.select().dicts()
return jsonify([p for p in pickups])
return jsonify([p for p in db.get_pickups()])

@app.route('/api/v1/pickups/<lookup>', methods=['GET'])
def get_pickup(lookup):
app.logger.info(f"pickup {lookup}")
pickup = Pickup.select().where(Pickup.lookup == lookup).dicts().get()
return jsonify(pickup)
return jsonify(db.get_pickup(lookup))

def amount_from_request(data):
app.logger.info("amount_from_request")
app.logger.info(data)
amount = data["trees"] * 15 + data["extra"]
return amount*100
@app.route('/api/v1/pickups', methods=['POST'])
def post_pickup():
app.logger.info(f"post pickup")
return str(db.create_pickup())

@app.route('/api/v1/pickups/<lookup>', methods=['PUT'])
def put_pickup(lookup):
app.logger.info(f"post pickup")
return str(db.update_pickup(lookup))

@app.route('/api/v1/create-payment-intent', methods=['POST'])
def create_payment():
Expand Down

0 comments on commit bcd3895

Please sign in to comment.