Skip to content

Commit

Permalink
Merge pull request #1 from tonicospinelli/01-flat-php
Browse files Browse the repository at this point in the history
guest user adds product at its wishlist
  • Loading branch information
tonicospinelli authored Jun 12, 2016
2 parents d5bd1d8 + 800d570 commit 7e8697a
Show file tree
Hide file tree
Showing 9 changed files with 284 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/data/*
!/data/.gitkeep
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
Developing for Business
=======================

#### User Story

I as a guest user, I want to add a product sold out in my wish list, so that I receive a notification when it becomes available.

Eu como um usuário convidado, quero adicionar um produto esgotado em minha lista de desejos para que eu receba uma notificação quando ele estiver disponível.


#### Requirements

* PHP 5.6+
* PDO + SQLite Driver

#### Run Application

create sqlite database
```shell
$ php cli/create_tables.php
```

start php built-in server
```shell
$ php -S localhost:8000 -t public
```
8 changes: 8 additions & 0 deletions cli/create_tables.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

require_once __DIR__ . '/../lib/dbconn.php';

$db->query("CREATE TABLE IF NOT EXISTS wishlists (id INTEGER PRIMARY KEY AUTOINCREMENT, email varchar(255), product_id int, status VARCHAR(1) DEFAULT 'P');");
$db->query('CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(255), unit_price DECIMAL(10,2), stock int);');
$stm = $db->query("INSERT INTO products VALUES (null, 'Camiseta', 59.9, 10);");
$stm = $db->query("INSERT INTO products VALUES (null, 'Bermuda', 69.9, 10);");
29 changes: 29 additions & 0 deletions cli/wishlist_notification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

require_once __DIR__ . '/../lib/functions.php';
require_once __DIR__ . '/../lib/dbconn.php';

$query = <<<SQL
SELECT
wishlists.id, wishlists.email, products.name as product_name
FROM
wishlists
INNER JOIN
products ON products.id = product_id
WHERE
products.stock > 0
AND wishlists.status = 'P'
SQL;
$stm = $db->prepare($query);
$stm->execute();
$wishlists = $stm->fetchAll(PDO::FETCH_ASSOC);

foreach ($wishlists as $wishlist) {
echo sprintf(
'sending email for: %s with "%s".',
$wishlist['email'],
$wishlist['product_name']
) . PHP_EOL;
$stm = $db->prepare("UPDATE wishlists SET status = 'S' WHERE id = ?");
$stm->execute([$wishlist['id']]);
}
Empty file added data/.gitkeep
Empty file.
6 changes: 6 additions & 0 deletions lib/dbconn.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php

$database = __DIR__ . '/../data/business.db';
$dsn = 'sqlite:' . $database;
$db = new PDO($dsn);

74 changes: 74 additions & 0 deletions lib/functions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

/**
* validate wish list data
* @param array $data
* @return bool
*/
function isValidProduct(array $data)
{
if (!isset($data['name']) || !assert(is_string($data['name']) !== false)) {
return false;
}
if (!isset($data['stock']) || !assert(is_numeric($data['stock']))) {
return false;
}
return true;
}

/**
* Gets wish list data.
* @param array $data
* @return array
*/
function getProduct(array $data)
{
return array(
'id' => (isset($data['id']) ? $data['id'] : null),
'name' => $data['name'],
'price' => $data['price'],
'stock' => $data['stock']
);
}

/**
* Creates a url to remove product from wish list
* @param int $id
* @return string
*/
function removeUrl($uri, $id, array $extraQuery = array())
{
$query = http_build_query(array_merge(['remove' => $id], $extraQuery));
return sprintf('<a href="/%s?%s">remove</a>', $uri, $query);
}


/**
* validate wish list data
* @param array $data
* @return bool
*/
function isValidWishList(array $data)
{
if (!isset($data['product_id']) || !assert(is_numeric($data['product_id']))) {
return false;
}
if (!isset($data['email']) || !assert(filter_var($data['email'], FILTER_VALIDATE_EMAIL) !== false)) {
return false;
}
return true;
}

/**
* Gets wish list data.
* @param array $data
* @return array
*/
function getWishList(array $data)
{
return array(
'email' => $data['email'],
'product_id' => $data['product_id'],
'status' => 'P',
);
}
58 changes: 58 additions & 0 deletions public/product.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

require_once __DIR__ . '/../lib/functions.php';
require_once __DIR__ . '/../lib/dbconn.php';

$errormsg = null;
$successmsg = null;

if (isset($_POST['submit']) && isValidProduct($_POST['product'])) {
$product = getProduct($_POST['product']);
$db->beginTransaction();
try {
$stm = $db->prepare('INSERT INTO products (name, unit_price, stock) VALUES (?, ?, ?)');
$stm->execute([$product['name'], $product['unit_price'], $product['stock']]);
$db->commit();
$successmsg = 'Product was saved successfully!';
} catch (Exception $e) {
$db->rollBack();
$errormsg = 'Product could not be added! :(';
}
}
$stm = $db->prepare('SELECT * FROM products');
$stm->execute();
$products = $stm->fetchAll(PDO::FETCH_ASSOC);
?>
<html>
<head></head>
<body>
<?php if (null !== $errormsg): ?>
<div class="alert error"><?php echo $errormsg; ?> </div>
<?php elseif (isset($product)): ?>
<div class="alert success"><?php echo $successmsg; ?></div>
<?php endif; ?>
<h3>Products</h3>
<table>
<thead>
<tr>
<th>ID</th>
<th>PRODUCT</th>
<th>UNIT PRICE</th>
<th>STOCK</th>
<th>ACTIONS</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td><?php echo $product['id']; ?> </td>
<td><?php echo $product['name']; ?> </td>
<td><?php echo $product['unit_price']; ?> </td>
<td><?php echo $product['stock']; ?> </td>
<td><?php echo removeUrl('product.php', $product['id']); ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
81 changes: 81 additions & 0 deletions public/wishlist.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

require_once __DIR__ . '/../lib/functions.php';
require_once __DIR__ . '/../lib/dbconn.php';

$errormsg = null;
$successmsg = null;

if (isset($_POST['submit']) && isValidWishList($_POST['wish_item'])) {
$wishItem = getWishList($_POST['wish_item']);
$db->beginTransaction();
try {
$stm = $db->prepare('INSERT INTO wishlists (email, product_id) VALUES (?, ?)');
$stm->execute([$wishItem['email'], $wishItem['product_id']]);
$db->commit();
$successmsg = 'Product was added at wish list successfully!';
} catch (Exception $e) {
$db->rollBack();
$errormsg = 'Product could not be added at wishlist! :(';
}
}

if (isset($_GET['remove'])) {
$db->beginTransaction();
try {
$stm = $db->prepare('DELETE FROM wishlists WHERE id = ?');
$stm->execute([$_GET['remove']]);
$db->commit();
$successmsg = 'Product was removed from wish list successfully!';
} catch (Exception $e) {
$db->rollBack();
$errormsg = 'Product could not be removed at wishlist! :(';
}
header('Location: /wishlist.php?'.http_build_query(['email' => $_GET['email']]));
}

$query = <<<SQL
SELECT
wishlists.id, products.name as product_name, products.stock as product_stock, wishlists.status
FROM
wishlists
INNER JOIN
products ON products.id = product_id
WHERE email = ?
SQL;

$stm = $db->prepare($query);
$stm->execute([$_GET['email']]);
$wishlist = $stm->fetchAll(PDO::FETCH_ASSOC);
?>
<html>
<head></head>
<body>
<?php if (null !== $errormsg): ?>
<div class="alert error"><?php echo $errormsg; ?> </div>
<?php elseif (isset($wishItem)): ?>
<div class="alert success"><?php echo $successmsg; ?></div>
<?php endif; ?>
<h3>My Wish List</h3>
<table>
<thead>
<tr>
<th>ID</th>
<th>PRODUCT</th>
<th>STATUS</th>
<th>ACTIONS</th>
</tr>
</thead>
<tbody>
<?php foreach ($wishlist as $wish): ?>
<tr>
<td><?php echo $wish['id']; ?> </td>
<td><?php echo $wish['product_name']; ?> </td>
<td><?php echo ($wish['status'] == 'P' && $wish['product_stock'] == 0 ? 'Not Available' : 'Available'); ?> </td>
<td><?php echo removeUrl('wishlist.php', $wish['id'], ['email' => $_GET['email']]); ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>

0 comments on commit 7e8697a

Please sign in to comment.