Skip to content

Commit

Permalink
Merge branch 'master' of github.com:digitalinteraction/intake24
Browse files Browse the repository at this point in the history
  • Loading branch information
mechkg committed Nov 22, 2016
2 parents de8e15a + 21e6a1a commit 74c3dae
Show file tree
Hide file tree
Showing 6 changed files with 141 additions and 149 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ WITH v AS(
LEFT JOIN foods ON foods.code = foods_categories.food_code
LEFT JOIN foods_local as fl1 ON foods.code = fl1.food_code AND fl1.locale_id = v.locale_id
LEFT JOIN foods_local as fl2 ON foods.code = fl2.food_code AND fl2.locale_id IN (SELECT prototype_locale_id FROM locales WHERE id=v.locale_id)
WHERE NOT COALESCE(fl1.do_not_use, fl2.do_not_use)
LEFT JOIN foods_restrictions ON foods.code = foods_restrictions.food_code
WHERE NOT (COALESCE(fl1.do_not_use, fl2.do_not_use))
AND NOT (COALESCE(fl1.do_not_use, fl2.do_not_use))
AND (foods_restrictions.locale_id = {locale_id} OR foods_restrictions.locale_id IS NULL)
)
SELECT locale_id, category_code, code, description, local_description FROM t
UNION ALL
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import uk.ac.ncl.openlab.intake24.services.fooddb.errors.UnexpectedDatabaseError
import uk.ac.ncl.openlab.intake24.services.fooddb.errors.NutrientMappingError
import uk.ac.ncl.openlab.intake24.services.fooddb.errors.RecordNotFound
import uk.ac.ncl.openlab.intake24.services.fooddb.errors.RecordType
import anorm.SqlParser

@Singleton
class NutrientMappingServiceSqlImpl @Inject() (@Named("intake24_foods") val dataSource: DataSource) extends NutrientMappingService with FoodDataSqlService {
Expand All @@ -37,14 +38,21 @@ class NutrientMappingServiceSqlImpl @Inject() (@Named("intake24_foods") val data

def nutrientsFor(table_id: String, record_id: String, weight: Double): Either[NutrientMappingError, Map[Nutrient, Double]] = tryWithConnection {
implicit conn =>
val rows = SQL("SELECT nutrient_type_id, units_per_100g FROM nutrient_table_records_nutrients WHERE nutrient_table_record_id={record_id} and nutrient_table_id={table_id}")
.on('record_id -> record_id, 'table_id -> table_id)
.as(Macro.namedParser[NutrientsRow].*)

if (rows.isEmpty)
Left(RecordNotFound(new RuntimeException(s"table_id: $table_id, record_id: $record_id")))
else
Right(rows.map(row => (Nutrient.for_id(row.nutrient_type_id).get -> (weight * row.units_per_100g / 100.0))).toMap)
withTransaction {
val validation = SQL("SELECT 1 FROM nutrient_table_records WHERE id={record_id} AND nutrient_table_id={table_id}")
.on('record_id -> record_id, 'table_id -> table_id)
.executeQuery().as(SqlParser.long(1).singleOpt).isDefined

if (!validation)
Left(RecordNotFound(new RuntimeException(s"table_id: $table_id, record_id: $record_id")))
else {
val rows = SQL("SELECT nutrient_type_id, units_per_100g FROM nutrient_table_records_nutrients WHERE nutrient_table_record_id={record_id} and nutrient_table_id={table_id}")
.on('record_id -> record_id, 'table_id -> table_id)
.as(Macro.namedParser[NutrientsRow].*)

Right(rows.map(row => (Nutrient.for_id(row.nutrient_type_id).get -> (weight * row.units_per_100g / 100.0))).toMap)
}
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -549,12 +549,10 @@ class DataStoreSqlImpl @Inject() (@Named("intake24_system") dataSource: DataSour
if (items.isEmpty) ()
else if (times == 0) throw new DataStoreException("Could not upsert popularity counters in a reasonable number of attempts")
else {

val updateParams = items.map(code => Seq[NamedParameter]('food_code -> code))

val tryInsertItems = {
val updateResult =
BatchSql(Queries.popularityCounterIncrement, updateParams).execute()
val updateResult = BatchSql(Queries.popularityCounterIncrement, updateParams).execute()

// Successfull updates will return 1 as number of rows affected
// everything else indicates failure
Expand All @@ -563,13 +561,13 @@ class DataStoreSqlImpl @Inject() (@Named("intake24_system") dataSource: DataSour

// Bad performance:
// Postgres will throw PSQLException on errors and stop batch execution in case of errors,
// so each individual item has to be processed using a single query

// so each individual item has to be processed using a single query
val retryItems = {
val insertResult = tryInsertItems.map(item => Try {
SQL(Queries.popularityCounterInsert)
.on('food_code -> item)
.executeInsert(SqlParser.str("food_code").single)
.execute()
})

tryInsertItems.zip(insertResult).filter(_._2.isFailure).map(_._1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

import net.scran24.user.shared.FoodData;
import net.scran24.user.shared.FoodPrompt;
import net.scran24.user.shared.lookup.AsServedDef;
Expand All @@ -36,9 +39,6 @@
import net.scran24.user.shared.lookup.LookupResult;
import net.scran24.user.shared.lookup.PortionSizeMethod;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public interface FoodLookupServiceAsync
{
void split( java.lang.String description, String locale, AsyncCallback<java.util.List<java.lang.String>> callback );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,72 +23,80 @@
import com.google.gwt.user.client.History;

/**
* Manages client-side survey serialisation, cross-session persistence and history.
* Manages client-side survey serialisation, cross-session persistence and
* history.
*/
public class StateManager {
private Survey currentState;
private int historyEventCounter = 0;

private final Logger log = Logger.getLogger(StateManager.class.getSimpleName());

public final String version_id;
public final String scheme_id;

public Survey getCurrentState() {
return currentState;
}

public void makeHistoryEntry() {
//log.info("Making history entry #" + historyEventCounter);
//new RuntimeException().printStackTrace();
//log.info(SurveyXmlSerialiser.toXml(currentState));

History.newItem(Integer.toString(historyEventCounter), false);
StateManagerUtil.setHistoryState(CurrentUser.getUserInfo().userName, historyEventCounter, currentState);
historyEventCounter++;
}

public void updateState(Survey newState, boolean makeHistoryEntry) {
currentState = newState;

if (makeHistoryEntry) {
// log.info ("Making history entry");
makeHistoryEntry();
}

StateManagerUtil.setLatestState(CurrentUser.getUserInfo().userName, currentState, scheme_id, version_id);
// log.info("Updated latest state");

// updateUi.call(newState);
}

public StateManager(Survey initialState, String scheme_id, String version_id, final Callback showNextPage, final PortionSizeScriptManager scriptManager) {
this.scheme_id = scheme_id;
this.version_id = version_id;
this.currentState = initialState;

log.info("Making initial history entry");
makeHistoryEntry();

History.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
final int state_id = Integer.parseInt(event.getValue());

StateManagerUtil.getHistoryState(CurrentUser.getUserInfo().userName, state_id, scriptManager).accept(new Option.SideEffectVisitor<Survey>() {
@Override
public void visitSome(Survey item) {
log.info("Switching to historical state #" + state_id);
updateState(item, false);
showNextPage.call();
}

@Override
public void visitNone() {
log.warning("Failed to load historical state, keeping current state");
}
});
}
});
}
private Survey currentState;
private int historyEventCounter = 0;

private final Logger log = Logger.getLogger(StateManager.class.getSimpleName());

public final String version_id;
public final String scheme_id;

public Survey getCurrentState() {
return currentState;
}

public void makeHistoryEntry() {
// log.info("Making history entry #" + historyEventCounter);
// new RuntimeException().printStackTrace();
// log.info(SurveyXmlSerialiser.toXml(currentState));

History.newItem(Integer.toString(historyEventCounter), false);
StateManagerUtil.setHistoryState(CurrentUser.getUserInfo().userName, historyEventCounter, currentState);
historyEventCounter++;
}

public void updateState(Survey newState, boolean makeHistoryEntry) {
currentState = newState;

if (makeHistoryEntry) {
// log.info ("Making history entry");
makeHistoryEntry();
}

StateManagerUtil.setLatestState(CurrentUser.getUserInfo().userName, currentState, scheme_id, version_id);
// log.info("Updated latest state");

// updateUi.call(newState);
}

public StateManager(Survey initialState, String scheme_id, String version_id, final Callback showNextPage,
final PortionSizeScriptManager scriptManager) {
this.scheme_id = scheme_id;
this.version_id = version_id;
this.currentState = initialState;

log.info("Making initial history entry");
makeHistoryEntry();

History.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {

try {
final int state_id = Integer.parseInt(event.getValue());

StateManagerUtil.getHistoryState(CurrentUser.getUserInfo().userName, state_id, scriptManager)
.accept(new Option.SideEffectVisitor<Survey>() {
@Override
public void visitSome(Survey item) {
log.info("Switching to historical state #" + state_id);
updateState(item, false);
showNextPage.call();
}

@Override
public void visitNone() {
log.warning("Failed to load historical state, keeping current state");
}
});
} catch (NumberFormatException e) {
// Ignore malformed state ids
}
}
});
}
}
Loading

0 comments on commit 74c3dae

Please sign in to comment.