proposal_database.rkt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. #lang racket/base
  2. ;; This program updates an entry in a proposals database.
  3. (require racket/cmdline
  4. racket/date
  5. racket/list
  6. db
  7. "config.rkt") ; load configuration file
  8. (define progname "proposal_database.rkt")
  9. ; give us the date in YYYY-MM-DD format
  10. (date-display-format 'iso-8601)
  11. ; parameters
  12. ; start and end date to sub-select proposals within a given range
  13. (define start-date (make-parameter #f))
  14. (define end-date (make-parameter #f))
  15. ; if #t, use proposal type, submitting organiation, solicitation/call, and
  16. ; telescope name from the most recently submitted (i.e., highest ID) proposal
  17. (define reuse-params (make-parameter #f))
  18. ; Set up the mode as a parameter to be provided by command line switches
  19. (define mode (make-parameter #f))
  20. ; set up command line arguments
  21. (command-line
  22. #:program progname
  23. #:once-each
  24. [("-s" "--start-date") sd "Start of date range (YYYY-MM-DD)"
  25. (start-date sd)]
  26. [("-e" "--end-date") ed "End of date range (YYYY-MM-DD)"
  27. (end-date ed)]
  28. [("-r" "--reuse-parameters") "Reuse/auto-fill proposal type, submitting organization, solicitation/call and telescope name from the most recently added proposal."
  29. (reuse-params #t)]
  30. #:once-any
  31. [("--create-database") "Create a new database" (mode "create-database")]
  32. [("-a" "--add") "Add a new proposal" (mode "add")]
  33. [("-u" "--update") "Update a proposal outcome" (mode "update")]
  34. [("--stats") "Calculate and display summary statistics" (mode "stats")]
  35. [("--list-open") "Show all submitted (but not resolved) proposals" (mode "list-open")]
  36. [("--list-closed") "Show all resolved (accepted and rejected) proposals" (mode "list-closed")]
  37. [("--list-accepted") "Show accepted proposals" (mode "list-accepted")]
  38. [("--list-rejected") "Show rejected proposals" (mode "list-rejected")]
  39. #:ps "Copyright 2019-2020, 2022-2024 George Privon")
  40. ; set up a condensed prompt for getting information
  41. (define (getinput prompt)
  42. (write-string prompt)
  43. (write-string ": ")
  44. (read-line))
  45. ; take an input result from the SQL search and write it out nicely
  46. (define (printentry entry issub)
  47. (displayln (string-append
  48. (number->string (vector-ref entry 0))
  49. ": "
  50. (vector-ref entry 1)
  51. "("
  52. (vector-ref entry 2)
  53. "; PI: "
  54. (vector-ref entry 4)
  55. (if (not issub)
  56. (string-append "; "
  57. (vector-ref entry 5))
  58. "")
  59. ") \""
  60. (vector-ref entry 3)
  61. "\"")))
  62. (define (get-last-proposal-call conn)
  63. (displayln "Adopting proposal information from last submission")
  64. (last-proposal-call conn))
  65. ; get information from the most recent proposal submission
  66. (define (last-proposal-call conn)
  67. (vector->list (query-row conn "SELECT type, organization, solicitation, telescope FROM proposals ORDER BY id DESC LIMIT 1")))
  68. ; create the database and create the table
  69. (define (createdb dbloc)
  70. ; make sure we can use the sqlite3 connection
  71. (cond [(not (sqlite3-available?)) (error "Sqlite3 library not available.")])
  72. ; create the database and add the `proposals` table if it doesn't exist
  73. (cond [(file-exists? dbloc) (error "Database exists. Exiting.")])
  74. (write-string (string-append "Creating database " dbloc "\n"))
  75. (define conn (sqlite3-connect #:database dbloc
  76. #:mode 'create))
  77. (query-exec conn "CREATE TABLE proposals (ID INTEGER PRIMARY KEY,
  78. type TEXT NOT NULL,
  79. organization TEXT NOT NULL,
  80. solicitation TEXT NOT NULL,
  81. telescope TEXT DEFAULT '',
  82. orgpropID TEXT NOT NULL,
  83. PI TEXT NOT NULL,
  84. title TEXT NOT NULL,
  85. CoI TEXT NOT NULL,
  86. status TEXT NOT NULL,
  87. submitdate TEXT NOT NULL,
  88. resultdate TEXT DEFAULT '')")
  89. (disconnect conn)
  90. (write-string (string-append "Database created at " dbloc "\n")))
  91. ; check to see if we can access the database
  92. (define (checkdb conn)
  93. (cond [(connected? conn) (write-string "Database created successfully.")]
  94. [else (write-string "Could not connect to database.")]))
  95. ; add a new proposal to the database
  96. (define (addnew conn)
  97. ; full list of input fileds that we will need (these will be the prompts
  98. ; to the user)
  99. (define input-fields (list "Proposal type"
  100. "Submitting Organization"
  101. "Solicitation/Call"
  102. "Telescope"
  103. "Proposal Title"
  104. "PI"
  105. "CoIs"
  106. "Submit date (YYYY-MM-DD)"
  107. "Organization's propsal ID"))
  108. (displayln "Adding new proposal to database.")
  109. ; assume all these proposals are submitted, don't ask the user
  110. (define status "submitted")
  111. ; get the proposal information
  112. (define propinfo
  113. (cond
  114. ; if we're re-using parameters, get info from the most recent submission
  115. ; and append the user input for the remaining fields
  116. [(reuse-params) (append (get-last-proposal-call conn)
  117. (map getinput (list-tail input-fields 4)))]
  118. ; if not using previous information, ask the user for all inputs
  119. [else (map getinput input-fields)]))
  120. ; do the INSERT into the Sqlite database
  121. (let* ([add-proposal-info
  122. (prepare conn "INSERT INTO proposals (type, organization, solicitation, telescope, title, PI, CoI, submitdate, orgpropID, status) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")])
  123. (query-exec conn (bind-prepared-statement add-proposal-info
  124. (flatten (list propinfo status))))))
  125. ; update an entry with new status (accepted, rejected, etc.)
  126. (define (update conn ID)
  127. (displayln (string-append "Updating entry " (number->string ID)))
  128. (define entry (query-maybe-row conn "SELECT * FROM proposals WHERE ID=?" ID))
  129. (cond
  130. [(eq? #f entry) (error "Invalid ID. Row not found")])
  131. (displayln (string-append "Current status is: "
  132. (vector-ref entry 9)
  133. " ("
  134. (vector-ref entry 10)
  135. ")"))
  136. (write-string "Please enter new status: ")
  137. (define newstatus (read-line))
  138. ;(write-string "Please enter date of updated status (leave blank to use current date): ")
  139. ;(define resdate (read-line))
  140. (define resdate (date->string (seconds->date (current-seconds))))
  141. ; now update that entry
  142. (query-exec conn "UPDATE proposals SET status=?, resultdate=? WHERE ID=?"
  143. newstatus
  144. resdate
  145. ID)
  146. (displayln "Entry updated."))
  147. ; if the user selects a date range we need to decide which date to filter on
  148. ; If they're looking at submitted (i.e., open) proposals, use the submitted
  149. ; date.
  150. ; If they're looking at closed/resolved proposals, use the dates proposals
  151. ; were resolved.
  152. (define (date-for-selection submitted)
  153. (if submitted
  154. "submitdate"
  155. "resultdate"))
  156. ; retrieve and print proposals based on status
  157. (define (printprop conn
  158. #:submitted issub
  159. #:accepted [isaccept #f]
  160. #:rejected [isrej #f])
  161. (define selclause (string-append
  162. (if issub
  163. "status='submitted'"
  164. "status!='submitted'")
  165. ; find things that are "accepted" or "funded"
  166. (if isaccept
  167. " AND (status LIKE '%Accepted%' OR status LIKE '%Funded%')"
  168. "")
  169. ; find things that are "rejected"
  170. (if isrej
  171. " AND status LIKE '%Rejected%'"
  172. "")))
  173. ; generate a selection clause if the user requested a restricted range
  174. (define dateclause (string-append
  175. (if (or (start-date) (end-date))
  176. " AND "
  177. "")
  178. (if (start-date)
  179. (string-append
  180. " DATE("
  181. (date-for-selection issub)
  182. ") >= DATE('"
  183. (start-date)
  184. "') ")
  185. "")
  186. (if (and (start-date) (end-date))
  187. " AND "
  188. "")
  189. (if (end-date)
  190. (string-append
  191. " DATE("
  192. (date-for-selection issub)
  193. ") <= DATE('"
  194. (end-date)
  195. "') ")
  196. "")))
  197. (define props (query-rows conn (string-append "SELECT ID,telescope,solicitation,title,PI,status FROM proposals WHERE "
  198. selclause
  199. dateclause)))
  200. (display (string-append (number->string (length props))))
  201. (if issub
  202. (displayln " pending proposals found.")
  203. (cond
  204. [isaccept (displayln " accepted proposals found.")]
  205. [isrej (displayln " rejected proposals found.")]))
  206. (newline)
  207. ; print all the unresolved proposals to the screen
  208. (map (lambda (prop)
  209. (printentry prop issub))
  210. props))
  211. ; find proposals waiting for updates
  212. (define (findpending conn)
  213. (write-string "Updating proposals. ")
  214. (printprop conn #:submitted #t)
  215. (write-string "Please enter a proposal number to edit (enter 0 or nothing to exit): ")
  216. (define upID (read-line))
  217. (cond
  218. [(eq? (string->number upID) 0) (exit)]
  219. [(string->number upID) (update conn (string->number upID))]
  220. [else (exit)]))
  221. ; compute and print some statistics about proposals:
  222. ; - total number of proposals (since earliest date)
  223. ; - number of pending proposals
  224. ; - number of successful proposals and corresponding fraction of the total that are not pending
  225. ; - number of rejected proposals and corresponding fraction of the total that are not pending
  226. ; - do the above two for all proposals and for proposals that I PI'ed. (TODO: PI'ed separation not yet implemented)
  227. (define (proposal-stats conn)
  228. (displayln "Proposal statistics to date.\n")
  229. ; do statistics for all proposals
  230. (displayln "\tAll proposals")
  231. (let-values ([(Nprop Npending Nrejected) (get-stats conn)])
  232. (print-stats Nprop Npending Nrejected))
  233. ; do statistics for proposals as PI
  234. (displayln (string-append "\n\tPI'ed Proposals (by "
  235. PIname
  236. ")"))
  237. (let-values ([(Nprop Npending Nrejected) (get-stats conn #:selclause (string-append "PI LIKE '%"
  238. PIname
  239. "%'"))])
  240. (print-stats Nprop Npending Nrejected))
  241. )
  242. ; given numbers, format somewhat pretty output of proposal statistics
  243. (define (print-stats Nprop Npending Nrejected)
  244. (display (number->string Nprop))
  245. (display "\ttotal proposals entered (")
  246. (display (number->string (- Nprop Npending)))
  247. (display " proposals resolved; ")
  248. (display (number->string Npending))
  249. (displayln " proposals pending).")
  250. (define Naccepted (- Nprop Npending Nrejected))
  251. (display (number->string Naccepted))
  252. (display "\tproposals accepted (f=")
  253. (display (number->string (/ Naccepted
  254. (- Nprop Npending))))
  255. (displayln " of resolved proposals).")
  256. (display (number->string Nrejected))
  257. (display "\tproposals rejected (f=")
  258. (display (number->string (/ Nrejected
  259. (- Nprop Npending))))
  260. (displayln " of resolved proposals)."))
  261. ; retrieve proposal numbers from the database, for statistics
  262. (define (get-stats conn #:selclause [extrasel ""])
  263. (define mysel (if (eq? 0 (string-length extrasel))
  264. ""
  265. (string-append " AND "
  266. extrasel)))
  267. (define mysel-one (if (eq? 0 (string-length extrasel))
  268. ""
  269. (string-append " WHERE "
  270. extrasel)))
  271. (values
  272. ; total number of proposals
  273. (length (query-rows conn
  274. (string-append "SELECT ID FROM proposals"
  275. mysel-one)))
  276. ; Number of pending proposals
  277. (length (query-rows conn
  278. (string-append "SELECT ID FROM proposals WHERE status='submitted'"
  279. mysel)))
  280. ; Number of rejected proposals
  281. (length (query-rows conn
  282. (string-append "SELECT ID FROM proposals WHERE status LIKE '%rejected%'"
  283. mysel)))))
  284. ; make sure we can use the sqlite3 connection
  285. (define checkdblib
  286. (cond (not (sqlite3-available?))
  287. (error "Sqlite3 library not available.")))
  288. ; catch-all routine for when we need to access the database
  289. (define (querysys mode)
  290. ; check if the user would like to create the database or not
  291. (cond
  292. [(regexp-match "create-database" mode) (createdb dbloc)])
  293. ; see if we need write access or if we can use read only
  294. (define dbmode (if (or (regexp-match "add" mode)
  295. (regexp-match "update" mode))
  296. 'read/write
  297. 'read-only))
  298. ; open the database with the specified mode
  299. (define conn (sqlite3-connect #:database dbloc
  300. #:mode dbmode))
  301. ; now handle the user's request
  302. (cond
  303. [(regexp-match "create-database" mode) (checkdb conn)]
  304. [(regexp-match "add" mode) (addnew conn)]
  305. [(regexp-match "update" mode) (findpending conn)]
  306. [(regexp-match "stats" mode) (proposal-stats conn)]
  307. [(regexp-match "list-open" mode) (printprop conn #:submitted #t)]
  308. [(regexp-match "list-closed" mode) (printprop conn #:submitted #f)]
  309. [(regexp-match "list-accepted" mode) (printprop conn #:submitted #f #:accepted #t)]
  310. [(regexp-match "list-rejected" mode) (printprop conn #:submitted #f #:rejected #t)]
  311. [else (error (string-append "Unknown mode. Try " progname " help\n\n"))])
  312. ; close the databse
  313. (disconnect conn))
  314. (querysys (mode))