Skip to content

Commit

Permalink
logging
Browse files Browse the repository at this point in the history
  • Loading branch information
TomConner committed Nov 20, 2023
1 parent fdf1fa8 commit 7245a24
Show file tree
Hide file tree
Showing 9 changed files with 214 additions and 100 deletions.
3 changes: 2 additions & 1 deletion docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ services:
build:
context: ./generator
working_dir: /tree105/generator
command: hugo server -v -s /tree105/generator --liveReloadPort 443 -d /tree105/public --bind "0.0.0.0" --port 1313
#command: hugo server -v -s /tree105/generator --liveReloadPort 443 -d /tree105/public --bind "0.0.0.0" --port 1313
command: hugo server -v -s /tree105/generator --disableLiveReload -d /tree105/public --bind "0.0.0.0" --port 1313
ports:
- "1313:1313"
volumes:
Expand Down
75 changes: 55 additions & 20 deletions generator/content/register/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,62 @@
<body>
<main>

<!-- <p>Pay for Tree Pickup using Stripe</p> -->
<form id="payment-form">
<div id="link-authentication-element">
<!-- Elements will create authentication element here -->
</div>
<div id="address-element">
<!-- Elements will create address element here -->
</div>

<section id="section-pay-stripe">
<div id="payment-element">
<!-- Elements will create form elements here -->
<section id="stripe-address">
<!-- <p>Pay for Tree Pickup using Stripe</p> -->
<form id="address-form">
<div id="link-authentication-element">
<!-- Elements will create authentication element here -->
</div>
</section>
<button id="button-pay-now">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Pay now</span>
</button>
<button id="button-pay-later" disabled="true">Register now, pay later</button>
<div id="payment-message" class="hidden"></div>
</form>
<div id="address-element">
<!-- Elements will create address element here -->
</div>

<section id="section-pay-stripe">
<div id="payment-element">
<!-- Elements will create form elements here -->
</div>
</section>

<button id="button-pay-now" hidden="true">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Pay</span>
</button>

<div id="payment-message" class="hidden"></div>

<button id="button-register">Register</button>

<section id="post-register" hidden="true">
<p><strong id="message2"></strong></p>
<p id="lookup-code"></p>
</section>

</form>
</section>

<section id="stripe-payment" hidden="true">
<!-- <p>Pay for Tree Pickup using Stripe</p> -->
<form id="payment-form">
<div id="link2-authentication-element">
<!-- Elements will create authentication element here -->
</div>
<div id="address2-element">
<!-- Elements will create address element here -->
</div>

<section id="section-pay-stripe2">
<div id="payment2-element">
<!-- Elements will create form elements here -->
</div>
</section>


<div id="payment-message" class="hidden"></div>
</form>
</section>



</main>
</body>
</html>
9 changes: 5 additions & 4 deletions generator/content/register/stripe-payment.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,10 @@ document.addEventListener('DOMContentLoaded', async () => {

// Get a reference to the payment form and its sections
//
const form = document.getElementById('payment-form');
const buttonPayNow = document.getElementById('button-pay-now');
const buttonPayLater = document.getElementById('button-pay-later');
const addressForm = document.getElementById('address-form');
const paymentForm = document.getElementById('payment-form');
const buttonRegister = document.getElementById('button-register');
const buttonPay = document.getElementById('button-pay');
const sectionPayStripe = document.getElementById('section-pay-stripe');

// Create and mount the address element
Expand Down Expand Up @@ -150,7 +151,7 @@ document.addEventListener('DOMContentLoaded', async () => {

// When the form is submitted...
let submitted = false;
form.addEventListener('submit', async (e) => {
paymentForm.addEventListener('submit', async (e) => {
e.preventDefault();

// Disable double submission of the form
Expand Down
4 changes: 2 additions & 2 deletions generator/layouts/shortcodes/register-form.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
width: 480px;
}
form > * {
top-margin: 10px;
bottom-margin: 2px;
margin-top: 10px;
margin-bottom: 2px;
}
button {
background-color: var(--accent-color);
Expand Down
170 changes: 106 additions & 64 deletions generator/static/js/register-form.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@


const originalLocalStorage = window.localStorage;
// function urlencodeFormData(fd){
// var s = '';
// function encode(s){ return encodeURIComponent(s).replace(/%20/g,'+'); }
Expand Down Expand Up @@ -86,14 +85,32 @@
});
}


function loadOrderForm() {
// document.getElementById("registerform").addEventListener("submit", formSubmit);
document.getElementById("rnumtrees").addEventListener("input", onChangeNumTrees);
document.getElementById("rextra").addEventListener("input", onChangeNumTrees);
//document.getElementById("cashcheck").checked = true;
document.getElementById("rnumtrees").value = 1;
document.getElementById("rextra").value = 0;
console.debug("loadOrderForm");
const rnumtrees = document.getElementById("rnumtrees");
const rextra = document.getElementById("rextra");
const rcomment = document.getElementById("rcomment");
const pickup = getLocalItem("pickup")
if (pickup != null) {
rnumtrees.value = pickup.numtrees;
rextra.value = pickup.extra;
rcomment.value = pickup.comment;
} else {
// document.getElementById("registerform").addEventListener("submit", formSubmit);

//document.getElementById("cashcheck").checked = true;
rnumtrees.value = 1;
rextra.value = 0;
rcomment.value = "";
}
onChangeNumTrees();
rnumtrees.addEventListener("input", onChangeNumTrees);
rextra.addEventListener("input", onChangeNumTrees);

const lookup_code = getLocalItem("lookup")
document.getElementById("lookup-code").innerText = `Lookup code: ${lookup_code}`;

// document.getElementById("registerform").addEventListener("input", (event) => {
// message1 = document.getElementById("message1")
// isvalid = document.getElementById("registerform").checkValidity();
Expand All @@ -116,71 +133,96 @@
// 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);
// This function will be called when a message is received
function onStripeFrameMessage(event) {
// only trust messages from my own iframe
const expectedOrigins = [window.location.origin, 'https://js.stripe.com'];

// Check if the origin of the message is the expected one
if (!(expectedOrigins.includes(event.origin))) {
console.error('Invalid origin:', event.origin);
return; // Ignore the message
} else {
console.debug('Valid origin:', event.origin);
}
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();

// Handle the message here
//console.debug('Stripe message:', event.data);

// TODO dispatch the message data to other parts of your application as needed
// For example: dispatchEvent(new CustomEvent('messageReceived', { detail: event.data }));
}



async function newPickup() {
console.debug("POSTing to pickups");
// post to /api/v1/pickups
await fetch('/api/v1/pickups', {method: "POST"})
.then((response) => response.json())
.then((data) => {
console.debug(data);
lookup_code = data.lookup;
console.log(`new lookup code is ${lookup_code}`);
localStorage.setItem("lookup", lookup_code);
loadOrderForm();
});
}

function getLocalItem(key) {
try {
const item = window.localStorage.getItem(key);
if (item === undefined) {
return null;
}
if (!item) {
return null;
}
return item;
} catch (error) {
console.error(error);
return null;
}
}

async function pageStart() {
console.debug("pageStart");
const lookup_code = getLocalItem("lookup");
if (lookup_code) {
console.debug(`lookup code from localStorage is ${lookup_code}; fetching pickup`);
try {
await fetch(`/api/v1/pickups/${lookup_code}`)
.then((response) => {
console.debug(response)
if (response.ok) {
pickup = response.json();
localStorage.setItem("pickup", pickup);
loadOrderForm();

} else {
console.log(`lookup code ${lookup_code} not found`);
localStorage.removeItem("lookup");
newPickup();
}
});
} catch (error) {
console.error(error);
localStorage.removeItem("lookup");
newPickup();
}
} 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();
});
console.debug("no lookup code in localStorage");
newPickup();
}
lookup_code = localStorage.getItem("lookup");
document.getElementById("lookup-code").innerText = `Lookup code: ${lookup_code}`;
loadOrderForm();
}

window.addEventListener("load", (event) => {
lookup();

// This function will be called when a message is received
function onStripeFrameMessage(event) {
// only trust messages from my own iframe
const expectedOrigins = [window.location.origin, 'https://js.stripe.com'];

// Check if the origin of the message is the expected one
if (event.origin in expectedOrigins) {
console.error('Invalid origin:', event.origin);
return; // Ignore the message
} else {
console.debug('Valid origin:', event.origin);
}

// Handle the message here
console.log('Stripe message:', event.data);

// You can dispatch the message data to other parts of your application as needed
// For example: dispatchEvent(new CustomEvent('messageReceived', { detail: event.data }));
}

// Assuming 'fooframe' is the ID of your iframe
const stripeFrame = document.querySelector("iframe#stripe-frame");

window.addEventListener("load", (event) => {
pageStart();

// Add the event listener to the iframe's window
const stripeFrame = document.querySelector("iframe#stripe-frame");
stripeFrame.contentWindow.addEventListener('message', onStripeFrameMessage, false);

});

13 changes: 10 additions & 3 deletions server/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from datetime import datetime
import logging
import random
from playhouse.shortcuts import model_to_dict

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
Expand Down Expand Up @@ -71,13 +72,19 @@ def get_pickups():

def get_pickup(lookup):
logger.debug(f'get_pickup {lookup}')
return Pickup.select().where(Pickup.lookup == lookup).dicts().get()
try:
# Assuming 'lookup' is a CharField in your Pickup model
return model_to_dict(Pickup.get(Pickup.lookup == lookup))
# Process the pickup object as needed
except Pickup.DoesNotExist:
# Handle the case where no record matches the condition
logger.error(f"Pickup with the lookup={lookup} does not exist.")
return None

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

def update_pickup(lookup):
logger.debug(f'update_pickup {lookup}')
Expand Down
4 changes: 4 additions & 0 deletions server/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ python-dotenv==0.21.1
stripe==5.1.1
peewee==3.17.*
#debugpy==1.8.*
python-http-client==3.3.7
requests==2.31.0
#sendgrid==6.9.6
#starkbank-ecdsa==2.2.0
22 changes: 22 additions & 0 deletions server/sendgrid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
# import sendgrid
# import os
# from sendgrid.helpers.mail import *
# import dotenv

# dotenv.load_dotenv('.env')

# message = Mail(
# from_email='[email protected]',
# to_emails='[email protected]',
# subject='Sending with Twilio SendGrid is Fun',
# html_content='<strong>and easy to do anywhere, even with Python</strong>')
# try:
# sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
# response = sg.send(message)
# print(response.status_code)
# print(response.body)
# print(response.headers)
# except Exception as e:
# print(e.message)
Loading

0 comments on commit 7245a24

Please sign in to comment.