grocery_transactions.sh 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/bin/bash
  2. #
  3. # Copyright (c) Daniel Sheffield 2021
  4. #
  5. # All rights reserved
  6. #
  7. # THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
  8. set -euo pipefail
  9. ENDKW=ROLLBACK
  10. DATE="$(date +%Y-%m-%d)"
  11. STORE=" IS NOT NULL"
  12. usage(){
  13. cat <<EOF
  14. Usage: ./${0##*/} [ -d DATE ] [ -s STORE ] [ -r | -c ] < transactions.txn
  15. Companion script for grocery_transactions.py
  16. Reads transactions from stdin.
  17. ROLLBACK (-r) is enabled by default
  18. Date is optional and by default is set to current day.
  19. Date and store only affect the display of the transactions.
  20. If store is not set, then all stores are shown for that day.
  21. Example:
  22. # load generated transactions with ROLLBACK
  23. ./${0##*/} -d DATE -s STORE < transactions.txn
  24. ./${0##*/} -d DATE -s STORE -r < transactions.txn
  25. # load generated transactions with COMMIT
  26. ./${0##*/} -d DATE -s STORE -c < transactions.txn
  27. EOF
  28. }
  29. while getopts ":crd:s:" options; do
  30. case "${options}" in
  31. c)
  32. ENDKW=COMMIT
  33. ;;
  34. r)
  35. ENDKW=ROLLBACK
  36. ;;
  37. d)
  38. DATE="${OPTARG}"
  39. ;;
  40. s)
  41. STORE=" = \$store\$${OPTARG}\$store\$"
  42. ;;
  43. :)
  44. ;;
  45. *)
  46. usage 1>&2
  47. ;;
  48. esac
  49. done
  50. if [[ -t 0 ]]
  51. then
  52. usage 1>&2
  53. exit 1
  54. fi
  55. if [ -f db_credentials.py ]; then
  56. . db_credentials.py
  57. HOST="-h ${HOST}"
  58. PASSWORD=
  59. else
  60. HOST=
  61. PASSWORD=
  62. fi
  63. psql ${HOST} -d grocery -U ${USER} <<EOF
  64. BEGIN;
  65. $(cat - )
  66. SELECT
  67. date_part('day',ts)||'/'||date_part('month',ts)||' '||date_part('hour',ts)::int%12 AS ts,
  68. code AS shop,
  69. substr(description,1,32) AS description,
  70. quantity AS volume,
  71. substr(unit,1,4) AS unit,
  72. price,
  73. TRUNC(price/quantity,4) AS "\$/unit",
  74. sum(transaction_view.price) OVER (PARTITION BY transaction_view.ts::date ORDER BY transaction_view.ts, transaction_view.description ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS total,
  75. substr(product,1,10) AS product, substr(category,1,8) AS category, substr("group",1,9) AS "group", organic AS og
  76. FROM transaction_view
  77. WHERE ts BETWEEN '${DATE}'::date AND '${DATE}'::date + '23 hours 59 minutes 59 seconds'::interval
  78. AND store ${STORE};
  79. ${ENDKW};
  80. EOF