Skip to content

Commit

Permalink
Merge branch 'testing'
Browse files Browse the repository at this point in the history
  • Loading branch information
Carl-Tabuso committed Jul 4, 2024
2 parents f899fd7 + 7b5e2f4 commit a60ad06
Show file tree
Hide file tree
Showing 19 changed files with 569 additions and 313 deletions.
21 changes: 10 additions & 11 deletions src/accounts.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@
<!--Site Icon-->
<link rel="icon" href="images/sweet-avenue-logo.png" type="image/png" />

<!-- Bootstrap JavaScript -->
<script src="../vendor/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<!-- CDN Scripts -->
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script src="https://cdn.datatables.net/2.0.3/js/dataTables.js"></script>
<script src="https://cdn.datatables.net/2.0.3/js/dataTables.bootstrap5.js"></script>
<!-- Custom JavacScript -->
<script src="javascript/preloader.js" defer></script>
<script src="javascript/accounts.js" defer></script>

<script>
// This will be used to check if an email or username is already taken
const takenEmails = <?php echo json_encode($emails); ?>;
Expand Down Expand Up @@ -287,17 +297,6 @@ class="btn fw-medium btn-medium-brown text-capitalize py-2 px-4">add account</bu
</div>
</div>


<!-- Bootstrap JavaScript -->
<script src="../vendor/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<!-- CDN Scripts -->
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script src="https://cdn.datatables.net/2.0.3/js/dataTables.js"></script>
<script src="https://cdn.datatables.net/2.0.3/js/dataTables.bootstrap5.js"></script>
<!-- Custom JavacScript -->
<script src="javascript/preloader.js"></script>
<script src="javascript/accounts.js"></script>

</body>
</html>
<?php
Expand Down
34 changes: 15 additions & 19 deletions src/add_product.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name'] ?? null;
$category = $_POST['category'] ?? null;
$servingType = $_POST['servingType'] ?? null;
$flavorSize = $_POST['flavorSize'] ?? null;
$servingType = !empty($_POST['servingType']) ? $_POST['servingType'] : null;
$flavorSize = !empty($_POST['flavorSize']) ? $_POST['flavorSize'] : null;
$price = $_POST['price'] ?? null;
$image = $_FILES['image'] ?? null;

if ($name && $category && $price) { // Removed image check here, see below
if ($name && $category && $price) {
// Determine the table based on the category type
$categoryLower = strtolower($category);
if (strpos($categoryLower, 'drink') !== false || in_array($categoryLower, ['froyo', 'coffee & blended'])) {
Expand All @@ -23,14 +23,14 @@
$variationTable = 'drink_variation';
$servingField = 'type';
$flavorField = 'size';
$idField = 'drink_id'; // Add this line for dynamic ID field
$idField = 'drink_id';
} else {
$categoryTable = 'food_item';
$categoryField = 'food_category';
$variationTable = 'food_variation';
$servingField = 'serving';
$flavorField = 'flavor';
$idField = 'food_id'; // Add this line for dynamic ID field
$idField = 'food_id';
}

// Check if the product already exists
Expand Down Expand Up @@ -89,23 +89,19 @@
}
}

// Insert into variations table
if ($servingType || $flavorSize) {
$sql = "INSERT INTO $variationTable ($idField, $servingField, $flavorField, price) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($sql);
if ($stmt) {
$stmt->bind_param("issd", $productId, $servingType, $flavorSize, $price);
if ($stmt->execute()) {
$response['success'] = true;
} else {
$response['message'] = 'Failed to insert product variations: ' . $stmt->error;
}
$stmt->close();
// Always insert the price, even if servingType and flavorSize are not provided
$sql = "INSERT INTO $variationTable ($idField, $servingField, $flavorField, price) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($sql);
if ($stmt) {
$stmt->bind_param("issd", $productId, $servingType, $flavorSize, $price);
if ($stmt->execute()) {
$response['success'] = true;
} else {
$response['message'] = 'Failed to prepare variation insertion statement: ' . $db->error;
$response['message'] = 'Failed to insert product variations: ' . $stmt->error;
}
$stmt->close();
} else {
$response['success'] = true;
$response['message'] = 'Failed to prepare variation insertion statement: ' . $db->error;
}
} else {
$response['message'] = 'Name, category, and price are required';
Expand Down
4 changes: 4 additions & 0 deletions src/add_to_order_cart.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
$quantity = $_POST['quantity'];
$price = $_POST['price'];

// Exclude default variations
$servingOrType = $servingOrType === 'Default' ? '' : $servingOrType;
$flavorOrSize = $flavorOrSize === 'Default' ? '' : $flavorOrSize;

$orderItem = [
// 'product_id' => $productId,
'product_name' => $productName,
Expand Down
46 changes: 28 additions & 18 deletions src/apriori/apriori_algo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import datetime
from sqlalchemy import create_engine, text
import logging
import json

# Enable SQLAlchemy logging
logging.basicConfig()
Expand Down Expand Up @@ -44,23 +45,29 @@
one_week_ago = today - datetime.timedelta(days=7)

query = """
SELECT ip.transaction_id, d.name AS item_name
FROM items_purchased ip
JOIN drink_item d ON ip.item_id = d.id
JOIN transaction t ON ip.transaction_id = t.id
WHERE DATE(t.timestamp) BETWEEN :one_week_ago AND :today
UNION
SELECT ip.transaction_id, f.name AS item_name
FROM items_purchased ip
JOIN food_item f ON ip.item_id = f.id
JOIN transaction t ON ip.transaction_id = t.id
WHERE DATE(t.timestamp) BETWEEN :one_week_ago AND :today
SELECT id, items
FROM transaction
WHERE DATE(timestamp) BETWEEN :one_week_ago AND :today
"""
result = connection.execute(text(query), {"one_week_ago": one_week_ago, "today": today})
rows = result.fetchall()

# Convert data to a DataFrame
df = pd.DataFrame(rows, columns=['transaction_id', 'item_name'])
df = pd.DataFrame(rows, columns=['transaction_id', 'items'])

# Function to load JSON items with error handling
def load_json(items):
try:
return json.loads(items)
except json.JSONDecodeError:
return None

# Convert JSON items to lists and explode the lists into separate rows
df['items'] = df['items'].apply(load_json)
df = df.explode('items').dropna(subset=['items']).reset_index(drop=True)

# Rename 'items' column to 'item_name'
df = df.rename(columns={'items': 'item_name'})

# Print the raw data for inspection
print("Raw DataFrame:")
Expand Down Expand Up @@ -95,9 +102,10 @@
print("Association Rules DataFrame:")
print(rules.head())

# Insert only the rule with the highest conviction
if not rules.empty:
top_rule = rules.iloc[0] # Get the rule with the highest conviction
# Insert the top 5 rules into the database
if not rules.empty:
top_rules = rules.head(5) # Get the top 5 rules with the highest conviction
for index, top_rule in top_rules.iterrows():
antecedents = ', '.join(list(top_rule['antecedents']))
consequents = ', '.join(list(top_rule['consequents']))

Expand All @@ -118,11 +126,13 @@
"conviction": float(top_rule['conviction'])
}
)
print("Inserted top rule successfully.")
connection.commit() # Commit the transaction
print(f"Inserted rule {index + 1} successfully.")
except Exception as e:
print(f"Error inserting top rule: {str(e)}")
print(f"Error inserting rule {index + 1}: {str(e)}")
# Handle error (rollback, logging, etc.)

connection.commit() # Commit all transactions once all rules are inserted


# Close the connection
connection.close()
4 changes: 3 additions & 1 deletion src/get-product-details.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,13 @@
if (!in_array($key, $uniqueKeys)) { // Check if the key already exists
$uniqueKeys[] = $key; // Add the key to the list of seen keys

$sizeWithOz = $row['size'] . 'oz';

$productDetails[] = array(
// 'id' => $row['item_id'],
'name' => $row['item_name'],
'servingOrType' => $row['type'],
'flavorOrSize' => $row['size'],
'flavorOrSize' => $sizeWithOz,
'price' => $row['price']
);
}
Expand Down
Loading

0 comments on commit a60ad06

Please sign in to comment.