proposal_database.rkt 17 KB

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