proposal_database.rkt 14 KB

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